Skip to main content

ssruntime/ffi/
mod.rs

1//! The C ABI — how every non-Rust Player talks to the runtime.
2//!
3//! A flat set of `extern "C"` functions mirroring the Rust API, plus the opaque handles
4//! that carry state across the boundary. `cbindgen` generates `ssruntime.h` from this
5//! module and opens it with this text, so it is written for the C or C++ integrator.
6//!
7//! # Handles
8//!
9//! Every handle is an opaque `void *`. The two that every Player holds:
10//!
11//! - **Resource** (`ss_resource_create_copy` / `_borrow` → `ss_resource_destroy`) — parsed
12//!   `.ssab` data. Internally reference-counted, so it is safe to destroy a resource that
13//!   contexts are still bound to; the buffer stays alive until the last one lets go.
14//!   The `_borrow` variant does *not* copy, so the caller's buffer must outlive the
15//!   resource and every context and effect slot holding it.
16//! - **Context** (`ss_runtime_create` → `ss_runtime_destroy`) — the playback state of
17//!   one animated object: a stack of tracks, each playing an animation, layered onto the
18//!   setup pose. Bind a resource with `ss_runtime_bind_resource`; several contexts may
19//!   share one.
20//!
21//! Effect and instance parts get their own handles (`ss_effect_slot_create`,
22//! `ss_instance_slot_create`), stepped once per tick by the Player.
23//!
24//! # Calling convention
25//!
26//! Fallible calls return `bool` (or a null pointer, or `SS_RUNTIME_INVALID_HANDLE`) and
27//! record the reason on the context. `ss_runtime_get_last_error` reads back a stable code,
28//! and `ss_runtime_error_message` turns that code into the text to put in front of a
29//! user — which is what a Player owes its caller.
30//! **The message takes the code, not the context**, so it is a pure lookup with nothing
31//! to own and nothing to outlive. The track and source getters that return a float use
32//! `NaN` for a track or source that does not exist, which is distinguishable from a
33//! legitimate `0.0`. The context-wide ones (`ss_runtime_get_frame_no`,
34//! `ss_runtime_get_speed_scale` and `ss_runtime_update`) have no such case, and return
35//! `0.0` for a null context.
36//!
37//! The two `ss_resource_create_*` constructors and `ss_effect_slot_create` are the
38//! exception: they take no context, so a null return is the whole report. For a resource
39//! that is enough, because there are only two ways to get one — a null `ptr`, which the
40//! caller passed, and an `.ssab` whose schema version this runtime does not read. (Bytes
41//! that are not an `.ssab` at all are not among them; nothing here validates the input.
42//! See *Validation* below.)
43//!
44//! # Building a resource
45//!
46//! `ss_resource_create_*` then `ss_runtime_bind_resource` is the full form: it leaves
47//! you holding the resource handle, which is what `ss_effect_slot_create` takes and
48//! what lets one parsed pack serve several contexts. `ss_runtime_load_ssab_*` is the
49//! one-liner for when you need neither — it creates, binds, and drops its own reference.
50//!
51//! **They are alternatives, not a sequence.** Calling both on the same bytes parses the
52//! pack twice, and the parse is where every animation's metadata is built.
53//!
54//! Buffers handed out through `out_data` / `out_len` pairs point into runtime-owned
55//! memory and stay valid only until the next call that rewrites them. Copy anything you
56//! need to keep.
57//!
58//! # Safety
59//!
60//! Every entry point that takes a handle or a pointer relies on one contract, stated
61//! here rather than on each of them (it is why they are `unsafe` to call from Rust):
62//!
63//! - A handle is null, or what its own create function returned and not yet destroyed:
64//!   a context where a context is asked for, a slot where a slot is. A null handle is
65//!   never dereferenced.
66//! - A handle is not used from two threads at once. Different handles may be used from
67//!   different threads at the same time, contexts that share one resource included.
68//! - An `out_data` / `out_len` pointer is null or valid for a write.
69//!
70//! The ones that read a data or string pointer add their own `# Safety` section.
71//!
72//! # Validation
73//!
74//! Loading does not validate the `.ssab` (see "Limitations to design around" in the
75//! `ssruntime` crate docs). Every entry point that takes a data pointer trusts it.
76
77#![allow(clippy::missing_safety_doc)]
78#![allow(clippy::doc_lazy_continuation)]
79
80pub use crate::types::*;
81
82use alloc::boxed::Box;
83use alloc::sync::Arc;
84use core::ffi::{CStr, c_char, c_float, c_int, c_uchar, c_void};
85use core::sync::atomic::{AtomicPtr, Ordering};
86
87/// Severity passed to `SsLogCallback`. The runtime only ever emits `ERROR`
88/// today; `WARN` and `INFO` are reserved so a host can switch on the level
89/// without its arms going stale when the runtime starts using them.
90pub const SS_RUNTIME_LOG_ERROR: c_int = 1;
91/// See `SS_RUNTIME_LOG_ERROR`.
92pub const SS_RUNTIME_LOG_WARN: c_int = 2;
93/// See `SS_RUNTIME_LOG_ERROR`.
94pub const SS_RUNTIME_LOG_INFO: c_int = 3;
95
96pub type SsLogCallback = extern "C" fn(level: core::ffi::c_int, message: *const core::ffi::c_char);
97static LOG_CALLBACK: AtomicPtr<c_void> = AtomicPtr::new(core::ptr::null_mut());
98
99/// Register the function that receives a message for every failure the runtime
100/// records, for the whole process. It runs on the thread of the failing call, and
101/// `message` is valid only during it. `level` is one of `SS_RUNTIME_LOG_*`.
102#[unsafe(no_mangle)]
103pub extern "C" fn ss_runtime_set_log_callback(callback: SsLogCallback) {
104    LOG_CALLBACK.store(callback as *mut c_void, Ordering::Relaxed);
105}
106
107macro_rules! ss_log {
108    ($level:expr, $($arg:tt)*) => {{
109        let cb_ptr = $crate::ffi::LOG_CALLBACK.load(::core::sync::atomic::Ordering::Relaxed);
110        // Nothing is formatted while no callback is registered, so an unwatched
111        // build pays one relaxed load per failure and no allocation.
112        if !cb_ptr.is_null()
113            && let Ok(message) = ::alloc::ffi::CString::new(::alloc::format!($($arg)*))
114        {
115            // Safety: `LOG_CALLBACK` only ever holds what
116            // `ss_runtime_set_log_callback` stored, which is this type.
117            let cb: $crate::ffi::SsLogCallback = unsafe { ::core::mem::transmute(cb_ptr) };
118            cb($level, message.as_ptr());
119        }
120    }};
121}
122
123use crate::SsabResource;
124use crate::owning::{OwningContext, OwningEffectSlot};
125
126struct FfiContext {
127    ctx: OwningContext,
128    /// The reason the last call that tracks one failed, or `None` if it
129    /// succeeded.
130    last_error: Option<crate::error::SSRuntimeError>,
131}
132impl FfiContext {
133    /// Record a failure on both faces: [`ss_runtime_get_last_error`] for the
134    /// caller that checks the return value, and the log callback for the one
135    /// that does not. `api` names the entry point, because the error text
136    /// alone ("Animation not found") does not say which call produced it.
137    fn fail(&mut self, api: &str, err: crate::error::SSRuntimeError) {
138        ss_log!(SS_RUNTIME_LOG_ERROR, "{}: {}", api, err);
139        self.last_error = Some(err);
140    }
141}
142
143impl Default for FfiContext {
144    fn default() -> Self {
145        Self::new()
146    }
147}
148
149impl FfiContext {
150    fn new() -> Self {
151        Self { ctx: OwningContext::new(), last_error: None }
152    }
153}
154
155#[inline(always)]
156unsafe fn get_context<'a>(ptr: *mut c_void) -> Option<&'a mut FfiContext> {
157    if ptr.is_null() {
158        return None;
159    }
160    unsafe { Some(&mut *(ptr as *mut FfiContext)) }
161}
162
163/// Parse `data` into a resource handle, keeping the reason on failure.
164///
165/// The two `ss_resource_create_*` entry points have no context to record it on
166/// and return a null handle; the `ss_runtime_load_ssab_*` pair records it,
167/// readable through [`ss_runtime_get_last_error`].
168///
169/// # Safety
170///
171/// Same as [`SsabResource::new`]: `data` must hold a valid `.ssab`. Every entry point below
172/// passes that precondition on to its C caller in its "Security and Validation" section.
173unsafe fn create_ffi_resource(data: crate::SsabData) -> Result<*mut c_void, crate::error::SSRuntimeError> {
174    // SAFETY: forwarded from this function's own contract.
175    let arc = unsafe { SsabResource::new(data) };
176    if arc.resource().is_none() {
177        return Err(arc.parse_error().cloned().unwrap_or(crate::error::SSRuntimeError::Unknown));
178    }
179    Ok(Arc::into_raw(arc) as *mut c_void)
180}
181
182/// Another share of the resource behind `resource`, for a context or slot to hold.
183///
184/// # Safety
185///
186/// `resource` must be a live handle from `ss_resource_create_*`.
187unsafe fn share_resource(resource: *const c_void) -> Arc<SsabResource> {
188    let resource = resource as *const SsabResource;
189    // SAFETY: the handle is an `Arc::into_raw` that `ss_resource_destroy` has not yet released.
190    unsafe {
191        Arc::increment_strong_count(resource);
192        Arc::from_raw(resource)
193    }
194}
195
196#[unsafe(no_mangle)]
197/// Create a resource from a copy of the `len` bytes at `ptr`, which may be freed
198/// on return. Release it with `ss_resource_destroy`. Returns null for a null `ptr`
199/// or a pack of another schema version.
200///
201/// # Security and Validation
202/// To maximize performance and minimize binary size, `libssruntime` **does not validate** the input `.ssab` data.
203/// Passing corrupted or maliciously crafted data will cause undefined behavior (e.g., out-of-bounds reads).
204/// The caller MUST ensure the data is trusted or validated before passing it to this function.
205///
206/// # Safety
207///
208/// `ptr` must point to `len` readable bytes.
209pub unsafe extern "C" fn ss_resource_create_copy(ptr: *const c_uchar, len: usize) -> *mut c_void {
210    if ptr.is_null() {
211        return core::ptr::null_mut();
212    }
213    let data = unsafe { ::core::slice::from_raw_parts(ptr, len) };
214    match crate::SsabData::load_copy(data) {
215        // SAFETY: the C caller guarantees a valid `.ssab` (see "Security and Validation").
216        Ok(ssab_data) => unsafe { create_ffi_resource(ssab_data) }.unwrap_or(core::ptr::null_mut()),
217        Err(_) => core::ptr::null_mut(),
218    }
219}
220
221#[unsafe(no_mangle)]
222/// Create a resource that reads the `len` bytes at `ptr` in place, with no copy.
223/// Release it with `ss_resource_destroy`. Returns null for a null `ptr` or a pack
224/// of another schema version.
225///
226/// # Security and Validation
227/// To maximize performance and minimize binary size, `libssruntime` **does not validate** the input `.ssab` data.
228/// Passing corrupted or maliciously crafted data will cause undefined behavior (e.g., out-of-bounds reads).
229/// The caller MUST ensure the data is trusted or validated before passing it to this function.
230///
231/// # Safety
232///
233/// `ptr` must point to `len` readable bytes, which stay valid and unmodified until
234/// this handle is destroyed and no context or effect slot holds the resource.
235pub unsafe extern "C" fn ss_resource_create_borrow(ptr: *const c_uchar, len: usize) -> *mut c_void {
236    if ptr.is_null() {
237        return core::ptr::null_mut();
238    }
239    match unsafe { crate::SsabData::load_borrow(ptr, len) } {
240        // SAFETY: the C caller guarantees a valid `.ssab` (see "Security and Validation").
241        Ok(ssab_data) => unsafe { create_ffi_resource(ssab_data) }.unwrap_or(core::ptr::null_mut()),
242        Err(_) => core::ptr::null_mut(),
243    }
244}
245
246/// Release this handle. Null is ignored. A context or effect slot bound to the
247/// resource keeps its own share, so this is safe while they live.
248#[unsafe(no_mangle)]
249pub unsafe extern "C" fn ss_resource_destroy(resource: *mut c_void) {
250    if resource.is_null() {
251        return;
252    }
253    unsafe {
254        let _ = Arc::from_raw(resource as *mut SsabResource);
255    }
256}
257
258/// Create an empty context. Bind a resource and set up an animation before playing.
259/// Release it with `ss_runtime_destroy`.
260#[unsafe(no_mangle)]
261pub extern "C" fn ss_runtime_create() -> *mut c_void {
262    let c = FfiContext::new();
263    Box::into_raw(Box::new(c)) as *mut c_void
264}
265
266/// Release a context and its share of the bound resource. Null is ignored.
267#[unsafe(no_mangle)]
268pub unsafe extern "C" fn ss_runtime_destroy(context: *mut c_void) {
269    if let Some(context) = unsafe { get_context(context) } {
270        unsafe {
271            let _ = Box::from_raw(context as *mut FfiContext);
272        }
273    }
274}
275
276/// Return a context to its just-created state: the resource is unbound, and the
277/// last error, the overrides and the playback and coordinate settings are cleared.
278#[unsafe(no_mangle)]
279pub unsafe extern "C" fn ss_runtime_reset(context: *mut c_void) {
280    if let Some(ffi_context) = unsafe { get_context(context) } {
281        ffi_context.ctx.reset();
282        ffi_context.last_error = None;
283    }
284}
285
286/// Why the last call that tracks a reason failed, as a stable code: `1`
287/// `EmptyData`, `2` `InvalidVersion`, `3` `AnimationNotFound`, `4` `NotLoaded`,
288/// `5` `InvalidParameter`, `6` `MemoryError`, `7` `MalformedEffect`, `99` `Unknown`.
289/// `0` means the last such call succeeded, and so does a null `context`.
290///
291/// Every fallible entry point that has a context to write to clears this on
292/// entry, so it always describes the most recent one rather than some earlier
293/// failure. The exceptions are the constructors that take no context
294/// (`ss_resource_create_borrow` / `ss_resource_create_copy` and
295/// `ss_effect_slot_create`), which have nowhere to record: a null return from
296/// those is all there is.
297///
298/// Reading does not clear it. Read it immediately after the call that returned
299/// `false`, before making another on the same context.
300#[unsafe(no_mangle)]
301pub unsafe extern "C" fn ss_runtime_get_last_error(context: *mut c_void) -> i32 {
302    match unsafe { get_context(context) } {
303        Some(ffi_context) => ffi_context.last_error.as_ref().map_or(0, |e| e.as_code()),
304        None => 0,
305    }
306}
307
308/// The wording behind a code from `ss_runtime_get_last_error`, as
309/// NUL-terminated UTF-8.
310///
311/// **Takes the code, not a context**, so it is a pure lookup: no lifetime to
312/// respect, nothing to free, and the same answer forever. An unrecognised code
313/// — including `0`, which is "no error" — gives an empty string, so the result
314/// goes straight into a log call without a branch.
315///
316/// The text carries no numbers. `InvalidVersion` reads "Invalid SSAB version";
317/// a Player that wants to say *which* versions should compare
318/// `ss_runtime_ssab_schema_version` against the pack's own `version` field,
319/// which gives it two integers rather than a sentence to parse.
320#[unsafe(no_mangle)]
321pub extern "C" fn ss_runtime_error_message(code: i32) -> *const c_char {
322    // `&'static CStr` literals: no allocation, and nothing for the caller to own.
323    // Keyed off the code rather than a variant because the code is what crossed
324    // the ABI; `error_message_matches_every_variant` pins the two together.
325    let text: &'static CStr = match code {
326        0 => c"",
327        1 => c"SSAB data is empty",
328        2 => c"Invalid SSAB version",
329        3 => c"Animation not found",
330        4 => c"SSAB data is not loaded",
331        5 => c"Invalid parameter",
332        6 => c"Memory allocation failed",
333        7 => c"Effect data is malformed",
334        99 => c"Unknown error occurred",
335        _ => c"",
336    };
337    text.as_ptr()
338}
339
340/// The `.ssab` schema version this runtime reads.
341///
342/// The counterpart of `ss_converter_ssab_schema_version`, and what turns an
343/// `InvalidVersion` failure into something a Player can say: compare it against
344/// the `version` field of the pack it just failed to load.
345#[unsafe(no_mangle)]
346pub extern "C" fn ss_runtime_ssab_schema_version() -> u32 {
347    ssab::SSAB_SCHEMA_VERSION
348}
349
350/// Bind a resource to a context, which takes its own share of it. One resource can
351/// be bound to several contexts, and `ss_resource_destroy` is safe while they are:
352/// the resource lives until the last of them is destroyed, reset or bound to another.
353/// A `_borrow` resource's buffer is the caller's to keep alive for as long.
354///
355/// Drops the context's tracks and overrides; `ss_runtime_setup_animation` comes next.
356/// Returns `false` with `InvalidParameter` for a null `resource`.
357#[unsafe(no_mangle)]
358pub unsafe extern "C" fn ss_runtime_bind_resource(context: *mut c_void, resource: *mut c_void) -> bool {
359    let Some(ffi_context) = (unsafe { get_context(context) }) else {
360        return false;
361    };
362    ffi_context.last_error = None;
363    if resource.is_null() {
364        ffi_context.fail("ss_runtime_bind_resource", crate::error::SSRuntimeError::InvalidParameter);
365        return false;
366    }
367
368    // SAFETY: the C caller passes a live handle from `ss_resource_create_*`.
369    let resource = unsafe { share_resource(resource) };
370    // `EmptyData` is a handle whose pack did not parse; `ss_resource_create_*` never returns one.
371    if let Err(e) = ffi_context.ctx.bind(resource) {
372        ffi_context.fail("ss_runtime_bind_resource", e);
373        return false;
374    }
375    true
376}
377
378/// Create a resource from a copy of the `len` bytes at `ptr` and bind it to
379/// `context`, in one call, for a caller that needs no resource handle. Returns
380/// `false` with `InvalidParameter` for a null `ptr`, or `InvalidVersion` for a pack
381/// of another schema version.
382///
383/// # Security and Validation
384/// To maximize performance and minimize binary size, `libssruntime` **does not validate** the input `.ssab` data.
385/// Passing corrupted or maliciously crafted data will cause undefined behavior (e.g., out-of-bounds reads).
386/// The caller MUST ensure the data is trusted or validated before passing it to this function.
387///
388/// # Safety
389///
390/// `ptr` must point to `len` readable bytes.
391#[unsafe(no_mangle)]
392pub unsafe extern "C" fn ss_runtime_load_ssab_copy(context: *mut c_void, ptr: *const c_uchar, len: usize) -> bool {
393    let Some(ffi_context) = (unsafe { get_context(context) }) else {
394        return false;
395    };
396    ffi_context.last_error = None;
397    if ptr.is_null() {
398        ffi_context.fail("ss_runtime_load_ssab_copy", crate::error::SSRuntimeError::InvalidParameter);
399        return false;
400    }
401
402    let data = unsafe { ::core::slice::from_raw_parts(ptr, len) };
403    match crate::SsabData::load_copy(data) {
404        Ok(ssab_data) => {
405            // SAFETY: the C caller guarantees a valid `.ssab` (see "Security and Validation").
406            let res_ptr = match unsafe { create_ffi_resource(ssab_data) } {
407                Ok(p) => p,
408                Err(e) => {
409                    ffi_context.fail("ss_runtime_load_ssab_copy", e);
410                    return false;
411                }
412            };
413            let success = unsafe { ss_runtime_bind_resource(context, res_ptr) };
414            unsafe { ss_resource_destroy(res_ptr) };
415            success
416        }
417        Err(e) => {
418            ffi_context.fail("ss_runtime_load_ssab_copy", e);
419            false
420        }
421    }
422}
423
424/// Create a resource that reads the `len` bytes at `ptr` in place and bind it to
425/// `context`, in one call, for a caller that needs no resource handle. Returns
426/// `false` with `InvalidParameter` for a null `ptr`, or `InvalidVersion` for a pack
427/// of another schema version.
428///
429/// # Security and Validation
430/// To maximize performance and minimize binary size, `libssruntime` **does not validate** the input `.ssab` data.
431/// Passing corrupted or maliciously crafted data will cause undefined behavior (e.g., out-of-bounds reads).
432/// The caller MUST ensure the data is trusted or validated before passing it to this function.
433///
434/// # Safety
435///
436/// `ptr` must point to `len` readable bytes, which stay valid and unmodified until
437/// `context` is destroyed, reset or bound to another resource.
438#[unsafe(no_mangle)]
439pub unsafe extern "C" fn ss_runtime_load_ssab_borrow(context: *mut c_void, ptr: *const c_uchar, len: usize) -> bool {
440    let Some(ffi_context) = (unsafe { get_context(context) }) else {
441        return false;
442    };
443    ffi_context.last_error = None;
444    if ptr.is_null() {
445        ffi_context.fail("ss_runtime_load_ssab_borrow", crate::error::SSRuntimeError::InvalidParameter);
446        return false;
447    }
448
449    match unsafe { crate::SsabData::load_borrow(ptr, len) } {
450        Ok(ssab_data) => {
451            // SAFETY: the C caller guarantees a valid `.ssab` (see "Security and Validation").
452            let res_ptr = match unsafe { create_ffi_resource(ssab_data) } {
453                Ok(p) => p,
454                Err(e) => {
455                    ffi_context.fail("ss_runtime_load_ssab_borrow", e);
456                    return false;
457                }
458            };
459            let success = unsafe { ss_runtime_bind_resource(context, res_ptr) };
460            unsafe { ss_resource_destroy(res_ptr) };
461            success
462        }
463        Err(e) => {
464            ffi_context.fail("ss_runtime_load_ssab_borrow", e);
465            false
466        }
467    }
468}
469
470/// The bound resource's `.ssab` bytes. Returns `false` and writes nothing when
471/// no resource is bound (`NotLoaded`).
472#[unsafe(no_mangle)]
473pub unsafe extern "C" fn ss_runtime_get_ssab(context: *mut c_void, out_data: *mut *const c_uchar, out_len: *mut usize) -> bool {
474    let Some(ffi_context) = (unsafe { get_context(context) }) else {
475        return false;
476    };
477    ffi_context.last_error = None;
478    if let Some(ssab_buf) = ffi_context.ctx.get_ssab_data() {
479        unsafe {
480            if !out_data.is_null() {
481                *out_data = ssab_buf.as_ptr() as *const c_uchar;
482            }
483            if !out_len.is_null() {
484                *out_len = ssab_buf.len();
485            }
486        }
487        true
488    } else {
489        ffi_context.fail("ss_runtime_get_ssab", crate::error::SSRuntimeError::NotLoaded);
490        false
491    }
492}
493
494/// The bound resource's `.ssab` bytes, or null with `NotLoaded` when none is bound.
495#[unsafe(no_mangle)]
496pub unsafe extern "C" fn ss_runtime_get_ssab_buf(context: *mut c_void) -> *const c_uchar {
497    if let Some(ffi_context) = unsafe { get_context(context) } {
498        ffi_context.last_error = None;
499        if let Some(ssab_buf) = ffi_context.ctx.get_ssab_data() {
500            return ssab_buf.as_ptr() as *const c_uchar;
501        } else {
502            ffi_context.fail("ss_runtime_get_ssab_buf", crate::error::SSRuntimeError::NotLoaded);
503        }
504    }
505    core::ptr::null()
506}
507
508/// The length of `ss_runtime_get_ssab_buf`, or `0` with `NotLoaded` when none is bound.
509#[unsafe(no_mangle)]
510pub unsafe extern "C" fn ss_runtime_get_ssab_len(context: *mut c_void) -> usize {
511    if let Some(ffi_context) = unsafe { get_context(context) } {
512        ffi_context.last_error = None;
513        if let Some(ssab_buf) = ffi_context.ctx.get_ssab_data() {
514            return ssab_buf.len();
515        } else {
516            ffi_context.fail("ss_runtime_get_ssab_len", crate::error::SSRuntimeError::NotLoaded);
517        }
518    }
519    0
520}
521
522/// Select the animation `name` of the bound resource and move to its first frame.
523/// This does not start it; `ss_runtime_play` does. It drops every track but 0, the
524/// section and the loop count, and keeps the speed, the frame rate, the frame skip
525/// and the direction. Returns `false` with `NotLoaded`, `AnimationNotFound`, or
526/// `InvalidParameter` for a null `name`.
527///
528/// # Safety
529///
530/// `name` must be null or a valid null-terminated string.
531#[unsafe(no_mangle)]
532pub unsafe extern "C" fn ss_runtime_setup_animation(context: *mut c_void, name: *const c_char) -> bool {
533    let Some(ffi_context) = (unsafe { get_context(context) }) else {
534        return false;
535    };
536    ffi_context.last_error = None;
537    if name.is_null() {
538        ffi_context.fail("ss_runtime_setup_animation", crate::error::SSRuntimeError::InvalidParameter);
539        return false;
540    }
541    let c_buf = unsafe { CStr::from_ptr(name) };
542    let a = c_buf.to_str().unwrap_or_default();
543    match ffi_context.ctx.setup_animation(a) {
544        Ok(_) => true,
545        Err(e) => {
546            ffi_context.fail("ss_runtime_setup_animation", e);
547            false
548        }
549    }
550}
551
552/// `ss_runtime_setup_animation` by the hash `ss_runtime_hash_string` gives for the name.
553#[unsafe(no_mangle)]
554pub unsafe extern "C" fn ss_runtime_setup_animation_by_hash(context: *mut c_void, name_hash: u32) -> bool {
555    let Some(ffi_context) = (unsafe { get_context(context) }) else {
556        return false;
557    };
558    ffi_context.last_error = None;
559    match ffi_context.ctx.setup_animation_by_hash(name_hash) {
560        Ok(_) => true,
561        Err(e) => {
562            ffi_context.fail("ss_runtime_setup_animation_by_hash", e);
563            false
564        }
565    }
566}
567
568/// Build the FrameData of `frame_no`, which is in `[first frame, last frame + 1)`
569/// of the animation, and write where it is to `out_data` and `out_len`.
570///
571/// Returns `false` and writes nothing when no frame can be built, with the
572/// reason on `ss_runtime_get_last_error`: `NotLoaded` with no resource bound,
573/// `AnimationNotFound` with no animation set up, `InvalidParameter` for a
574/// `frame_no` out of range.
575///
576/// The buffer belongs to the context, and stays valid until the next
577/// `ss_runtime_get_frame_data` on it, or until it is rebound, reset or destroyed.
578#[unsafe(no_mangle)]
579pub unsafe extern "C" fn ss_runtime_get_frame_data(context: *mut c_void, frame_no: c_float, out_data: *mut *const c_uchar, out_len: *mut usize) -> bool {
580    let Some(ffi_context) = (unsafe { get_context(context) }) else {
581        return false;
582    };
583    ffi_context.last_error = None;
584    match ffi_context.ctx.get_frame_data(frame_no) {
585        Ok(ret) => {
586            unsafe {
587                if !out_data.is_null() {
588                    *out_data = ret.as_ptr();
589                }
590                if !out_len.is_null() {
591                    *out_len = ret.len();
592                }
593            }
594            true
595        }
596        Err(e) => {
597            ffi_context.fail("ss_runtime_get_frame_data", e);
598            false
599        }
600    }
601}
602
603/// Per-part world matrices for the current frame, written by
604/// `ss_runtime_get_frame_data`: 16 floats per part, indexed by `part_index * 16`, with
605/// the translation at `[12]` and `[13]`. The SceneGraph render mode does not compute them.
606#[unsafe(no_mangle)]
607pub unsafe extern "C" fn ss_runtime_get_world_matrices(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
608    if let Some(ffi_context) = unsafe { get_context(context) } {
609        ffi_context.last_error = None;
610        unsafe {
611            if !out_data.is_null() {
612                *out_data = ffi_context.ctx.get_world_matrices_ptr();
613            }
614            if !out_len.is_null() {
615                *out_len = ffi_context.ctx.get_world_matrices_len();
616            }
617        }
618    }
619}
620
621/// Per-part UVs for the current frame, written by `ss_runtime_get_frame_data`,
622/// matching `ss_runtime_get_local_vertices`:
623/// `[lt.u, lt.v, rt.u, rt.v, lb.u, lb.v, rb.u, rb.v, center.u, center.v]` = 10 floats,
624/// indexed by `part_index * 10`, in the cellmap's texture-pixel space. Divide by the
625/// texture size to normalize.
626#[unsafe(no_mangle)]
627pub unsafe extern "C" fn ss_runtime_get_local_uvs(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
628    if let Some(ffi_context) = unsafe { get_context(context) } {
629        ffi_context.last_error = None;
630        unsafe {
631            if !out_data.is_null() {
632                *out_data = ffi_context.ctx.get_local_uvs_ptr();
633            }
634            if !out_len.is_null() {
635                *out_len = ffi_context.ctx.get_local_uvs_len();
636            }
637        }
638    }
639}
640
641#[unsafe(no_mangle)]
642/// Per-part resolved cell metadata for the current frame, written by
643/// `ss_runtime_get_frame_data`. Layout:
644/// `[pivot_x, pivot_y, size_w, size_h, rect_left, rect_top]` per part,
645/// indexed by `part_index * 6`. `(rect_left, rect_top)` is the cell
646/// rectangle origin in the cellmap's texture pixel space, letting a
647/// Player build a complete source rect (origin + size) without its own
648/// cellmap lookup. Parts without a current cell carry zeros.
649pub unsafe extern "C" fn ss_runtime_get_cell_meta(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
650    if let Some(ffi_context) = unsafe { get_context(context) } {
651        ffi_context.last_error = None;
652        unsafe {
653            if !out_data.is_null() {
654                *out_data = ffi_context.ctx.get_cell_meta_ptr();
655            }
656            if !out_len.is_null() {
657                *out_len = ffi_context.ctx.get_cell_meta_len();
658            }
659        }
660    }
661}
662
663#[unsafe(no_mangle)]
664/// Per-part local-space vertex positions for the current frame, written by
665/// `ss_runtime_get_frame_data`. Layout per part:
666/// `[lt.x, lt.y, rt.x, rt.y, lb.x, lb.y, rb.x, rb.y, center.x, center.y]`
667/// = 10 floats, indexed by `part_index * 10`. Coordinates are in part-local
668/// space with `coordinate_system` (Y-Up/Y-Down) flip already applied, so a
669/// Player just multiplies them by the world matrix. Includes pivot, image
670/// flip, and per-frame vertex deformation. Parts without a current cell
671/// carry zeros. Replaces `FrameData::vertices` for renderers that consume
672/// pre-resolved SoA buffers.
673pub unsafe extern "C" fn ss_runtime_get_local_vertices(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
674    if let Some(ffi_context) = unsafe { get_context(context) } {
675        ffi_context.last_error = None;
676        unsafe {
677            if !out_data.is_null() {
678                *out_data = ffi_context.ctx.get_local_vertices_ptr();
679            }
680            if !out_len.is_null() {
681                *out_len = ffi_context.ctx.get_local_vertices_len();
682            }
683        }
684    }
685}
686
687#[unsafe(no_mangle)]
688/// Per-part shape vertex positions for the current frame, written by
689/// `ss_runtime_get_frame_data`. Layout: 12 vertices × `(x, y)` = 24 floats
690/// (`SHAPE_VERTICES_STRIDE`) per part, indexed by `part_index * 24`.
691/// Vertices are in local space, post-pivot, post-coord-system, so a Player
692/// just multiplies them by the world matrix. Only the first
693/// `ss_runtime_get_shape_vertex_counts(...)[part_index]` vertices are
694/// valid; remaining slots are zero-initialized. Non-shape parts carry zero
695/// count and zero-filled vertex slots. When no part of the pack is a shape,
696/// the buffer is empty, as is `ss_runtime_get_shape_vertex_box_coords`.
697pub unsafe extern "C" fn ss_runtime_get_shape_vertices(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
698    if let Some(ffi_context) = unsafe { get_context(context) } {
699        ffi_context.last_error = None;
700        unsafe {
701            if !out_data.is_null() {
702                *out_data = ffi_context.ctx.get_shape_vertices_ptr();
703            }
704            if !out_len.is_null() {
705                *out_len = ffi_context.ctx.get_shape_vertices_len();
706            }
707        }
708    }
709}
710
711#[unsafe(no_mangle)]
712/// Per-vertex normalized bounding-box coordinates paired with
713/// `ss_runtime_get_shape_vertices`. Layout: 12 vertices × `(fx, fy)` = 24
714/// floats (`SHAPE_VERTICES_STRIDE`) per part, indexed by `part_index * 24`.
715/// `(0, 0)` corresponds to the LT corner of the shape's pre-pivot bounding
716/// box, `(1, 1)` to the RB corner, regardless of pivot offset or coordinate
717/// system. Players use this to interpolate the four part-color corners
718/// without re-deriving the box layout.
719pub unsafe extern "C" fn ss_runtime_get_shape_vertex_box_coords(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
720    if let Some(ffi_context) = unsafe { get_context(context) } {
721        ffi_context.last_error = None;
722        unsafe {
723            if !out_data.is_null() {
724                *out_data = ffi_context.ctx.get_shape_vertex_box_coords_ptr();
725            }
726            if !out_len.is_null() {
727                *out_len = ffi_context.ctx.get_shape_vertex_box_coords_len();
728            }
729        }
730    }
731}
732
733#[unsafe(no_mangle)]
734/// Per-part valid vertex count for `ss_runtime_get_shape_vertices`. Indexed
735/// by `part_index`. Zero for parts that are not shape parts (or shape
736/// parts whose size collapsed to zero).
737pub unsafe extern "C" fn ss_runtime_get_shape_vertex_counts(context: *mut c_void, out_data: *mut *const i32, out_len: *mut usize) {
738    if let Some(ffi_context) = unsafe { get_context(context) } {
739        ffi_context.last_error = None;
740        unsafe {
741            if !out_data.is_null() {
742                *out_data = ffi_context.ctx.get_shape_vertex_counts_ptr();
743            }
744            if !out_len.is_null() {
745                *out_len = ffi_context.ctx.get_shape_vertex_counts_len();
746            }
747        }
748    }
749}
750
751#[unsafe(no_mangle)]
752/// Mesh per-vertex X coordinates in world space, concatenated across all
753/// parts. Pair with `ss_runtime_get_mesh_vertex_offsets` to slice per-part
754/// ranges: part `p`'s vertices live at indices `offsets[p]..offsets[p + 1]`.
755/// Non-mesh parts contribute an empty range. SceneGraph render mode leaves the
756/// buffer empty (length 0).
757pub unsafe extern "C" fn ss_runtime_get_mesh_vertices_x(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
758    if let Some(ffi_context) = unsafe { get_context(context) } {
759        ffi_context.last_error = None;
760        unsafe {
761            if !out_data.is_null() {
762                *out_data = ffi_context.ctx.get_mesh_vertices_x_ptr();
763            }
764            if !out_len.is_null() {
765                *out_len = ffi_context.ctx.get_mesh_vertices_x_len();
766            }
767        }
768    }
769}
770
771#[unsafe(no_mangle)]
772/// Mesh per-vertex Y coordinates. SoA companion to
773/// `ss_runtime_get_mesh_vertices_x`; sliced identically via
774/// `ss_runtime_get_mesh_vertex_offsets`.
775pub unsafe extern "C" fn ss_runtime_get_mesh_vertices_y(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
776    if let Some(ffi_context) = unsafe { get_context(context) } {
777        ffi_context.last_error = None;
778        unsafe {
779            if !out_data.is_null() {
780                *out_data = ffi_context.ctx.get_mesh_vertices_y_ptr();
781            }
782            if !out_len.is_null() {
783                *out_len = ffi_context.ctx.get_mesh_vertices_y_len();
784            }
785        }
786    }
787}
788
789#[unsafe(no_mangle)]
790/// CSR-style prefix sum (length = `num_parts + 1`) describing where each
791/// part's mesh vertices live inside `ss_runtime_get_mesh_vertices_x`
792/// / `_y`. Part `p` occupies indices `[offsets[p], offsets[p + 1])`; non-mesh
793/// parts have `offsets[p] == offsets[p + 1]`.
794pub unsafe extern "C" fn ss_runtime_get_mesh_vertex_offsets(context: *mut c_void, out_data: *mut *const u32, out_len: *mut usize) {
795    if let Some(ffi_context) = unsafe { get_context(context) } {
796        ffi_context.last_error = None;
797        unsafe {
798            if !out_data.is_null() {
799                *out_data = ffi_context.ctx.get_mesh_vertex_offsets_ptr();
800            }
801            if !out_len.is_null() {
802                *out_len = ffi_context.ctx.get_mesh_vertex_offsets_len();
803            }
804        }
805    }
806}
807
808#[unsafe(no_mangle)]
809/// Mesh per-vertex UV coordinates in cellmap texture-pixel space, interleaved
810/// `[u, v, ...]`, concatenated across all parts. Static — resolved once from
811/// each mesh part's frame-0 Cell. Sliced per-part by
812/// `ss_runtime_get_mesh_vertex_offsets`, identically to the vertex buffers.
813pub unsafe extern "C" fn ss_runtime_get_mesh_uvs(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
814    if let Some(ffi_context) = unsafe { get_context(context) } {
815        ffi_context.last_error = None;
816        unsafe {
817            if !out_data.is_null() {
818                *out_data = ffi_context.ctx.get_mesh_uvs_ptr();
819            }
820            if !out_len.is_null() {
821                *out_len = ffi_context.ctx.get_mesh_uvs_len();
822            }
823        }
824    }
825}
826
827#[unsafe(no_mangle)]
828/// Mesh triangle indices (part-local, 0-based), concatenated across all parts.
829/// Static. Slice part `p`'s range via `ss_runtime_get_mesh_index_offsets`:
830/// `[offsets[p], offsets[p + 1])`.
831pub unsafe extern "C" fn ss_runtime_get_mesh_indices(context: *mut c_void, out_data: *mut *const i32, out_len: *mut usize) {
832    if let Some(ffi_context) = unsafe { get_context(context) } {
833        ffi_context.last_error = None;
834        unsafe {
835            if !out_data.is_null() {
836                *out_data = ffi_context.ctx.get_mesh_indices_ptr();
837            }
838            if !out_len.is_null() {
839                *out_len = ffi_context.ctx.get_mesh_indices_len();
840            }
841        }
842    }
843}
844
845#[unsafe(no_mangle)]
846/// CSR-style prefix sum (length = `num_parts + 1`) for the triangle indices in
847/// `ss_runtime_get_mesh_indices`. Part `p` occupies `[offsets[p], offsets[p + 1])`;
848/// non-mesh parts have an empty range.
849pub unsafe extern "C" fn ss_runtime_get_mesh_index_offsets(context: *mut c_void, out_data: *mut *const u32, out_len: *mut usize) {
850    if let Some(ffi_context) = unsafe { get_context(context) } {
851        ffi_context.last_error = None;
852        unsafe {
853            if !out_data.is_null() {
854                *out_data = ffi_context.ctx.get_mesh_index_offsets_ptr();
855            }
856            if !out_len.is_null() {
857                *out_len = ffi_context.ctx.get_mesh_index_offsets_len();
858            }
859        }
860    }
861}
862
863#[unsafe(no_mangle)]
864/// Nine-Slice per-vertex positions for the current frame, interleaved
865/// `[x, y, ...]` and concatenated across all parts, written by
866/// `ss_runtime_get_frame_data`. Slice per part with
867/// `ss_runtime_get_nines_vertex_offsets`; parts drawn by another
868/// `DrawBatchKind` occupy an empty range.
869///
870/// Coordinates are part-local with pivot, image flip and the
871/// `coordinate_system` (Y-Up/Y-Down) flip already applied — exactly like
872/// `ss_runtime_get_local_vertices` — so a Player just multiplies them by the
873/// part's world matrix. The grid is a 4x4 sheet for `nines_fill_mode == 0`
874/// (stretch) and independent quads per repeat for `== 1` (tile).
875pub unsafe extern "C" fn ss_runtime_get_nines_vertices(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
876    if let Some(ffi_context) = unsafe { get_context(context) } {
877        ffi_context.last_error = None;
878        unsafe {
879            if !out_data.is_null() {
880                *out_data = ffi_context.ctx.get_nines_vertices_ptr();
881            }
882            if !out_len.is_null() {
883                *out_len = ffi_context.ctx.get_nines_vertices_len();
884            }
885        }
886    }
887}
888
889#[unsafe(no_mangle)]
890/// Nine-Slice per-vertex UVs in cellmap texture-pixel space, interleaved
891/// `[u, v, ...]`. Shares the vertex CSR of
892/// `ss_runtime_get_nines_vertex_offsets`. Divide by the texture size to
893/// normalize, the same as `ss_runtime_get_local_uvs`.
894pub unsafe extern "C" fn ss_runtime_get_nines_uvs(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
895    if let Some(ffi_context) = unsafe { get_context(context) } {
896        ffi_context.last_error = None;
897        unsafe {
898            if !out_data.is_null() {
899                *out_data = ffi_context.ctx.get_nines_uvs_ptr();
900            }
901            if !out_len.is_null() {
902                *out_len = ffi_context.ctx.get_nines_uvs_len();
903            }
904        }
905    }
906}
907
908#[unsafe(no_mangle)]
909/// Nine-Slice per-vertex box coordinates, interleaved `[fx, fy, ...]` with
910/// `0` at the part's left / top edge and `1` at its right / bottom edge.
911/// Shares the vertex CSR of `ss_runtime_get_nines_vertex_offsets`.
912///
913/// Use them to bilinearly interpolate the four `part_color` corners across the
914/// grid — the same weighting `ss_runtime_get_shape_vertex_box_coords` provides
915/// for Shape parts. A part flip is already folded in, so `fx` / `fy` always
916/// describe the drawn box.
917pub unsafe extern "C" fn ss_runtime_get_nines_box_coords(context: *mut c_void, out_data: *mut *const c_float, out_len: *mut usize) {
918    if let Some(ffi_context) = unsafe { get_context(context) } {
919        ffi_context.last_error = None;
920        unsafe {
921            if !out_data.is_null() {
922                *out_data = ffi_context.ctx.get_nines_box_coords_ptr();
923            }
924            if !out_len.is_null() {
925                *out_len = ffi_context.ctx.get_nines_box_coords_len();
926            }
927        }
928    }
929}
930
931#[unsafe(no_mangle)]
932/// Nine-Slice triangle indices, concatenated across all parts and sliced by
933/// `ss_runtime_get_nines_index_offsets`. Values are **part-local**
934/// (`0..vertex_count`), so a Player passes them alongside the part's vertex
935/// slice without rebasing. Each quad is wound `LT, RT, LB / LB, RT, RB`.
936pub unsafe extern "C" fn ss_runtime_get_nines_indices(context: *mut c_void, out_data: *mut *const i32, out_len: *mut usize) {
937    if let Some(ffi_context) = unsafe { get_context(context) } {
938        ffi_context.last_error = None;
939        unsafe {
940            if !out_data.is_null() {
941                *out_data = ffi_context.ctx.get_nines_indices_ptr();
942            }
943            if !out_len.is_null() {
944                *out_len = ffi_context.ctx.get_nines_indices_len();
945            }
946        }
947    }
948}
949
950#[unsafe(no_mangle)]
951/// CSR-style prefix sum (length = `num_parts + 1`) over the vertex buffers
952/// `ss_runtime_get_nines_vertices` / `_uvs` / `_box_coords`. Part `p` occupies
953/// vertices `[offsets[p], offsets[p + 1])` — multiply by 2 to index the
954/// interleaved floats. Non-nines parts have an empty range.
955pub unsafe extern "C" fn ss_runtime_get_nines_vertex_offsets(context: *mut c_void, out_data: *mut *const u32, out_len: *mut usize) {
956    if let Some(ffi_context) = unsafe { get_context(context) } {
957        ffi_context.last_error = None;
958        unsafe {
959            if !out_data.is_null() {
960                *out_data = ffi_context.ctx.get_nines_vertex_offsets_ptr();
961            }
962            if !out_len.is_null() {
963                *out_len = ffi_context.ctx.get_nines_vertex_offsets_len();
964            }
965        }
966    }
967}
968
969#[unsafe(no_mangle)]
970/// CSR-style prefix sum (length = `num_parts + 1`) for the triangle indices in
971/// `ss_runtime_get_nines_indices`. Part `p` occupies
972/// `[offsets[p], offsets[p + 1])`; non-nines parts have an empty range.
973pub unsafe extern "C" fn ss_runtime_get_nines_index_offsets(context: *mut c_void, out_data: *mut *const u32, out_len: *mut usize) {
974    if let Some(ffi_context) = unsafe { get_context(context) } {
975        ffi_context.last_error = None;
976        unsafe {
977            if !out_data.is_null() {
978                *out_data = ffi_context.ctx.get_nines_index_offsets_ptr();
979            }
980            if !out_len.is_null() {
981                *out_len = ffi_context.ctx.get_nines_index_offsets_len();
982            }
983        }
984    }
985}
986
987/// The playhead of track 0's main animation, with its fraction: what
988/// `ss_runtime_update` last returned, or where a seek put it.
989#[unsafe(no_mangle)]
990pub unsafe extern "C" fn ss_runtime_get_frame_no(context: *mut c_void) -> c_float {
991    if let Some(ffi_context) = unsafe { get_context(context) } {
992        return ffi_context.ctx.get_frame_no();
993    }
994    0.0
995}
996
997/// Returns `true` once the configured loops have completed, staying `true`
998/// until the next `ss_runtime_play` / `ss_runtime_setup_animation`. Always
999/// `false` under an infinite loop count, and never raised by
1000/// `ss_runtime_stop`.
1001///
1002/// This is a *state*, not a pulse: to notify once, take its rising edge.
1003#[unsafe(no_mangle)]
1004pub unsafe extern "C" fn ss_runtime_is_finished(context: *mut c_void) -> bool {
1005    if let Some(ffi_context) = unsafe { get_context(context) } {
1006        return ffi_context.ctx.is_finished();
1007    }
1008    false
1009}
1010
1011/// `true` for the single `ss_runtime_update` that took playback back to the start of
1012/// its cycle; the next update clears it. Never raised on the last cycle of a finite
1013/// loop count, which finishes instead.
1014#[unsafe(no_mangle)]
1015pub unsafe extern "C" fn ss_runtime_just_looped(context: *mut c_void) -> bool {
1016    if let Some(ffi_context) = unsafe { get_context(context) } {
1017        return ffi_context.ctx.just_looped();
1018    }
1019    false
1020}
1021
1022/// `true` while the clock runs and track 0 has not finished. A paused character is still playing.
1023#[unsafe(no_mangle)]
1024pub unsafe extern "C" fn ss_runtime_is_playing(context: *mut c_void) -> bool {
1025    if let Some(ffi_context) = unsafe { get_context(context) } {
1026        return ffi_context.ctx.is_playing();
1027    }
1028    false
1029}
1030
1031/// Whether track 0's playhead is moving forward now. A ping-pong's return leg reads
1032/// `false`, as does a backward animation's outward leg.
1033#[unsafe(no_mangle)]
1034pub unsafe extern "C" fn ss_runtime_is_playing_forward(context: *mut c_void) -> bool {
1035    if let Some(ffi_context) = unsafe { get_context(context) } {
1036        return ffi_context.ctx.is_playing_forward();
1037    }
1038    false
1039}
1040
1041/// `true` while a playing character is held by `ss_runtime_pause`. Once track 0 has
1042/// finished this reads `false`; `ss_runtime_is_clock_pausing` still reads the hold.
1043#[unsafe(no_mangle)]
1044pub unsafe extern "C" fn ss_runtime_is_pausing(context: *mut c_void) -> bool {
1045    if let Some(ffi_context) = unsafe { get_context(context) } {
1046        return ffi_context.ctx.is_pausing();
1047    }
1048    false
1049}
1050
1051/// `true` from `ss_runtime_play` until `ss_runtime_stop` or the next setup:
1052/// the character's clock, which stays `true` after track 0 finishes while
1053/// the other tracks and the fades run on. `ss_runtime_is_playing` reads
1054/// track 0's state instead.
1055#[unsafe(no_mangle)]
1056pub unsafe extern "C" fn ss_runtime_is_clock_playing(context: *mut c_void) -> bool {
1057    unsafe { get_context(context) }.is_some_and(|c| c.ctx.is_clock_playing())
1058}
1059
1060/// `true` while `ss_runtime_pause` holds a playing clock, after track 0 has
1061/// finished as well. Implies `ss_runtime_is_clock_playing`.
1062#[unsafe(no_mangle)]
1063pub unsafe extern "C" fn ss_runtime_is_clock_pausing(context: *mut c_void) -> bool {
1064    unsafe { get_context(context) }.is_some_and(|c| c.ctx.is_clock_pausing())
1065}
1066
1067/// `true` while the track stack would move the pose on a running clock for a
1068/// reason other than track 0's own animation stepping: a fade on any track, or
1069/// another source still playing on a track that is heard. Independent of the
1070/// clock; read it with `ss_runtime_is_clock_playing` and
1071/// `ss_runtime_is_clock_pausing`.
1072#[unsafe(no_mangle)]
1073pub unsafe extern "C" fn ss_runtime_is_stack_in_motion(context: *mut c_void) -> bool {
1074    unsafe { get_context(context) }.is_some_and(|c| c.ctx.is_stack_in_motion())
1075}
1076
1077/// What `ss_runtime_set_skip_frames` stored.
1078#[unsafe(no_mangle)]
1079pub unsafe extern "C" fn ss_runtime_get_skip_frames(context: *mut c_void) -> bool {
1080    if let Some(ffi_context) = unsafe { get_context(context) } {
1081        return ffi_context.ctx.get_skip_frames();
1082    }
1083    false
1084}
1085
1086/// 0 = forward, 1 = backward.
1087#[unsafe(no_mangle)]
1088pub unsafe extern "C" fn ss_runtime_get_playback_direction(context: *mut c_void) -> i32 {
1089    if let Some(ffi_context) = unsafe { get_context(context) } { if ffi_context.ctx.get_playback_direction() == crate::eval::playback_controller::PlaybackDirection::Forward { 0 } else { 1 } } else { 0 }
1090}
1091
1092/// 0 = normal, 1 = ping-pong.
1093#[unsafe(no_mangle)]
1094pub unsafe extern "C" fn ss_runtime_get_playback_style(context: *mut c_void) -> i32 {
1095    if let Some(ffi_context) = unsafe { get_context(context) } {
1096        return ffi_context.ctx.get_playback_style() as i32;
1097    }
1098    0
1099}
1100
1101/// `-1` for an animation that loops forever, otherwise the cycles it plays.
1102#[unsafe(no_mangle)]
1103pub unsafe extern "C" fn ss_runtime_get_loop_count(context: *mut c_void) -> i32 {
1104    if let Some(ffi_context) = unsafe { get_context(context) } {
1105        return ffi_context.ctx.get_loop_count();
1106    }
1107    0
1108}
1109
1110/// The cycles left, `0` once finished; `-1` for an animation that loops forever.
1111#[unsafe(no_mangle)]
1112pub unsafe extern "C" fn ss_runtime_get_remaining_loops(context: *mut c_void) -> i32 {
1113    if let Some(ffi_context) = unsafe { get_context(context) } {
1114        return ffi_context.ctx.get_remaining_loops();
1115    }
1116    0
1117}
1118
1119/// The first frame of the playback range: the section's when one is set, otherwise the animation's.
1120#[unsafe(no_mangle)]
1121pub unsafe extern "C" fn ss_runtime_get_start_frame(context: *mut c_void) -> i32 {
1122    if let Some(ffi_context) = unsafe { get_context(context) } {
1123        return ffi_context.ctx.get_start_frame();
1124    }
1125    0
1126}
1127
1128/// The last frame of the playback range: the section's when one is set, otherwise the animation's.
1129#[unsafe(no_mangle)]
1130pub unsafe extern "C" fn ss_runtime_get_end_frame(context: *mut c_void) -> i32 {
1131    if let Some(ffi_context) = unsafe { get_context(context) } {
1132        return ffi_context.ctx.get_end_frame();
1133    }
1134    0
1135}
1136
1137/// The rate track 0's animation plays at, in frames per second: the override when one
1138/// is set, otherwise the rate it was authored at.
1139#[unsafe(no_mangle)]
1140pub unsafe extern "C" fn ss_runtime_get_frame_rate(context: *mut c_void) -> i32 {
1141    if let Some(ffi_context) = unsafe { get_context(context) } {
1142        return ffi_context.ctx.get_frame_rate();
1143    }
1144    0
1145}
1146
1147/// The playback speed in effect, as a multiple of `ss_runtime_get_frame_rate`.
1148///
1149/// Reads back what `ss_runtime_set_speed_scale` stored, which is not
1150/// always what it was handed: a negative rate clamps to `0.0`.
1151#[unsafe(no_mangle)]
1152pub unsafe extern "C" fn ss_runtime_get_speed_scale(context: *mut c_void) -> c_float {
1153    if let Some(ffi_context) = unsafe { get_context(context) } {
1154        return ffi_context.ctx.get_speed_scale();
1155    }
1156    0.0
1157}
1158
1159/// `true` (the default) advances by the time elapsed, skipping frames to keep up.
1160/// `false` advances one frame at a time, at most one per update.
1161#[unsafe(no_mangle)]
1162pub unsafe extern "C" fn ss_runtime_set_skip_frames(context: *mut c_void, skip: bool) {
1163    if let Some(ffi_context) = unsafe { get_context(context) } {
1164        ffi_context.ctx.set_skip_frames(skip);
1165    }
1166}
1167
1168/// `n > 0` plays n cycles and then finishes; `0` or a negative count loops forever.
1169/// `ss_runtime_setup_animation` resets it to looping forever, so set it after.
1170#[unsafe(no_mangle)]
1171pub unsafe extern "C" fn ss_runtime_set_loop_count(context: *mut c_void, loop_count: c_int) {
1172    if let Some(ffi_context) = unsafe { get_context(context) } {
1173        ffi_context.ctx.set_loop_count(loop_count);
1174    }
1175}
1176
1177/// Play at `frame_rate` frames per second instead of the authored rate; `0` or a
1178/// negative rate clears the override. It survives `ss_runtime_setup_animation`.
1179#[unsafe(no_mangle)]
1180pub unsafe extern "C" fn ss_runtime_set_frame_rate(context: *mut c_void, frame_rate: c_int) {
1181    if let Some(ffi_context) = unsafe { get_context(context) } {
1182        ffi_context.ctx.set_frame_rate(frame_rate);
1183    }
1184}
1185
1186/// `direction`: 0 = forward, otherwise backward. `style`: 0 = normal, otherwise
1187/// ping-pong. Call it before `ss_runtime_play`. It survives `ss_runtime_setup_animation`.
1188#[unsafe(no_mangle)]
1189pub unsafe extern "C" fn ss_runtime_set_playback_direction(context: *mut c_void, direction: c_int, style: c_int) {
1190    if let Some(ffi_context) = unsafe { get_context(context) } {
1191        let d = if direction == 0 { crate::eval::playback_controller::PlaybackDirection::Forward } else { crate::eval::playback_controller::PlaybackDirection::Backward };
1192        let s = if style == 0 { crate::eval::playback_controller::PlaybackStyle::Normal } else { crate::eval::playback_controller::PlaybackStyle::PingPong };
1193        ffi_context.ctx.set_playback_direction(d, s);
1194    }
1195}
1196
1197/// Playback speed as a multiple of the frame rate. `0.0` stops the playhead while
1198/// `ss_runtime_is_playing` stays `true`, and a negative speed clamps to `0.0`; direction
1199/// is `ss_runtime_set_playback_direction`'s. It survives `ss_runtime_setup_animation`.
1200#[unsafe(no_mangle)]
1201pub unsafe extern "C" fn ss_runtime_set_speed_scale(context: *mut c_void, speed_scale: c_float) {
1202    if let Some(ffi_context) = unsafe { get_context(context) } {
1203        ffi_context.ctx.set_speed_scale(speed_scale);
1204    }
1205}
1206
1207/// Limits playback to `[start_frame, end_frame]`, both ends included. An end
1208/// out of the animation's range (`-1`, say) is the animation's edge on that
1209/// side. Returns `false`, with `InvalidParameter` for
1210/// `ss_runtime_get_last_error`, when both ends are in range and the end is
1211/// before the start; the section and the playhead stay as they were.
1212#[unsafe(no_mangle)]
1213pub unsafe extern "C" fn ss_runtime_set_animation_section(context: *mut c_void, start_frame: c_int, end_frame: c_int) -> bool {
1214    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1215        return false;
1216    };
1217    ffi_context.last_error = None;
1218    match ffi_context.ctx.set_animation_section(start_frame, end_frame) {
1219        Ok(()) => true,
1220        Err(e) => {
1221            ffi_context.fail("ss_runtime_set_animation_section", e);
1222            false
1223        }
1224    }
1225}
1226
1227/// Advance by `delta` **milliseconds** and return the frame to pass to
1228/// `ss_runtime_get_frame_data`. With animation mixing it advances every track and fade;
1229/// the frame returned is track 0's.
1230///
1231/// `delta` must not be negative. A negative value does not play backwards, and where it
1232/// leaves the playhead is unspecified. Clamp it to 0 first: a browser's
1233/// `requestAnimationFrame` timestamp can be earlier than the `performance.now()` read
1234/// before it.
1235#[unsafe(no_mangle)]
1236pub unsafe extern "C" fn ss_runtime_update(context: *mut c_void, delta: f32) -> c_float {
1237    if let Some(ffi_context) = unsafe { get_context(context) } {
1238        return ffi_context.ctx.update(delta);
1239    }
1240    0.0
1241}
1242
1243/// Start track 0 from the start of its range (the end when playing backward), with its
1244/// loop count re-armed, and start the clock the other tracks and fades run on.
1245#[unsafe(no_mangle)]
1246pub unsafe extern "C" fn ss_runtime_play(context: *mut c_void) {
1247    if let Some(ffi_context) = unsafe { get_context(context) } {
1248        ffi_context.ctx.play();
1249    }
1250}
1251
1252/// `ss_runtime_play`, starting from `frame_no`. A negative `frame_no` starts where `ss_runtime_play` does.
1253#[unsafe(no_mangle)]
1254pub unsafe extern "C" fn ss_runtime_play_with_start_frame(context: *mut c_void, frame_no: f32) {
1255    if let Some(ffi_context) = unsafe { get_context(context) } {
1256        ffi_context.ctx.play_with_start_frame(frame_no);
1257    }
1258}
1259
1260/// Holds playback where it stands, keeping the current frame. With animation
1261/// mixing it holds every track and every fade, as `ss_runtime_stop` stops them.
1262///
1263/// Idempotent: pausing an already-paused animation leaves it paused.
1264/// `ss_runtime_is_playing` stays true while held — a pause is a hold, not a
1265/// stop — so tell the two apart with `ss_runtime_is_pausing`. Lift the hold
1266/// with `ss_runtime_resume`; `ss_runtime_play` rewinds and cannot resume.
1267#[unsafe(no_mangle)]
1268pub unsafe extern "C" fn ss_runtime_pause(context: *mut c_void) {
1269    if let Some(ffi_context) = unsafe { get_context(context) } {
1270        ffi_context.ctx.pause();
1271    }
1272}
1273
1274/// Lifts a `ss_runtime_pause`, carrying on from the frame it stopped at.
1275///
1276/// Idempotent, and a no-op on an animation that was never paused. It does not
1277/// start a stopped animation; use `ss_runtime_play` for that.
1278#[unsafe(no_mangle)]
1279pub unsafe extern "C" fn ss_runtime_resume(context: *mut c_void) {
1280    if let Some(ffi_context) = unsafe { get_context(context) } {
1281        ffi_context.ctx.resume();
1282    }
1283}
1284
1285/// Stop every track and fade where they stand. Nothing rewinds; `ss_runtime_play` starts them again.
1286#[unsafe(no_mangle)]
1287pub unsafe extern "C" fn ss_runtime_stop(context: *mut c_void) {
1288    if let Some(ffi_context) = unsafe { get_context(context) } {
1289        ffi_context.ctx.stop();
1290    }
1291}
1292
1293/// Seek track 0 to `frame`, clamped to the playback range. The events of the frames in between do not fire.
1294#[unsafe(no_mangle)]
1295pub unsafe extern "C" fn ss_runtime_set_frame_no(context: *mut c_void, frame: c_float) {
1296    if let Some(ffi_context) = unsafe { get_context(context) } {
1297        ffi_context.ctx.set_frame_no(frame);
1298    }
1299}
1300
1301/// Step track 0 one whole frame forward, whatever the direction and style. Does nothing on the range's last frame.
1302#[unsafe(no_mangle)]
1303pub unsafe extern "C" fn ss_runtime_next_frame(context: *mut c_void) {
1304    if let Some(ffi_context) = unsafe { get_context(context) } {
1305        ffi_context.ctx.next_frame();
1306    }
1307}
1308
1309/// Step track 0 one whole frame back, whatever the direction and style. Does nothing on the range's first frame.
1310#[unsafe(no_mangle)]
1311pub unsafe extern "C" fn ss_runtime_prev_frame(context: *mut c_void) {
1312    if let Some(ffi_context) = unsafe { get_context(context) } {
1313        ffi_context.ctx.prev_frame();
1314    }
1315}
1316
1317/// Run a fallible `Context` call, recording the error code on failure. Every
1318/// bool-returning track entry point funnels through this so the `last_error`
1319/// contract is stated once; `api` is that entry point, for [`FfiContext::fail`].
1320fn report<F>(ffi_context: &mut FfiContext, api: &str, f: F) -> bool
1321where
1322    F: FnOnce(&mut crate::Context<'static>) -> Result<(), crate::error::SSRuntimeError>,
1323{
1324    match f(&mut ffi_context.ctx) {
1325        Ok(()) => true,
1326        Err(e) => {
1327            ffi_context.fail(api, e);
1328            false
1329        }
1330    }
1331}
1332
1333/// # Safety
1334/// `p` must be null or a valid null-terminated string.
1335unsafe fn cstr_to_string(p: *const c_char) -> Option<alloc::string::String> {
1336    if p.is_null() {
1337        return None;
1338    }
1339    let c_buf = unsafe { CStr::from_ptr(p) };
1340    Some(alloc::string::String::from_utf8_lossy(c_buf.to_bytes()).into_owned())
1341}
1342
1343/// Sentinel returned on failure by the functions that return a source handle,
1344/// and by `ss_runtime_get_track_blend` / `ss_runtime_get_track_sync` for a track
1345/// that does not exist. No live handle ever equals it.
1346pub const SS_RUNTIME_INVALID_HANDLE: u32 = u32::MAX;
1347
1348/// Track blend operators: what `ss_runtime_set_track_blend` takes and
1349/// `ss_runtime_get_track_blend` returns.
1350pub const SS_RUNTIME_TRACK_BLEND_MIX: u32 = 0;
1351pub const SS_RUNTIME_TRACK_BLEND_ADDITIVE: u32 = 1;
1352
1353/// Where the animations laid on a track start: what `ss_runtime_set_track_sync`
1354/// takes and `ss_runtime_get_track_sync` returns.
1355pub const SS_RUNTIME_TRACK_SYNC_FREE: u32 = 0;
1356pub const SS_RUNTIME_TRACK_SYNC_START: u32 = 1;
1357
1358// Animation mixing — the track stack. Tracks fold onto the setup pose in
1359// ascending order: `alpha` is a track's strength, `weight` only decides
1360// proportions among several sources sharing one track. Track 0 carries the
1361// structure (discrete attributes and events) and is what `setup_animation`
1362// establishes.
1363
1364/// Put `name` on `track`, replacing what it played and cancelling its fade. Tracks
1365/// grow on demand. Returns `false` with `NotLoaded`, `AnimationNotFound` (an unknown
1366/// name, or no `ss_runtime_setup_animation` yet), or `InvalidParameter` for a null
1367/// `name`.
1368///
1369/// # Safety
1370/// `name` must be a valid null-terminated UTF-8 (or lossy-decodable) string.
1371#[unsafe(no_mangle)]
1372pub unsafe extern "C" fn ss_runtime_set_track_animation(context: *mut c_void, track: u32, name: *const c_char) -> bool {
1373    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1374        return false;
1375    };
1376    ffi_context.last_error = None;
1377    let Some(a) = (unsafe { cstr_to_string(name) }) else {
1378        ffi_context.fail("ss_runtime_set_track_animation", crate::error::SSRuntimeError::InvalidParameter);
1379        return false;
1380    };
1381    report(ffi_context, "ss_runtime_set_track_animation", |ctx| ctx.set_track_animation(track, &a))
1382}
1383
1384/// `ss_runtime_set_track_animation` by the hash of the name.
1385#[unsafe(no_mangle)]
1386pub unsafe extern "C" fn ss_runtime_set_track_animation_by_hash(context: *mut c_void, track: u32, hash: u32) -> bool {
1387    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1388        return false;
1389    };
1390    ffi_context.last_error = None;
1391    report(ffi_context, "ss_runtime_set_track_animation_by_hash", |ctx| ctx.set_track_animation_by_hash(track, hash))
1392}
1393
1394/// The strength of `track`: `0` contributes nothing, `1` all of it, and values above
1395/// `1` extrapolate. Returns `false` with `InvalidParameter` for a `NaN` or a track that does
1396/// not exist.
1397#[unsafe(no_mangle)]
1398pub unsafe extern "C" fn ss_runtime_set_track_alpha(context: *mut c_void, track: u32, alpha: c_float) -> bool {
1399    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1400        return false;
1401    };
1402    ffi_context.last_error = None;
1403    report(ffi_context, "ss_runtime_set_track_alpha", |ctx| ctx.set_track_alpha(track, alpha))
1404}
1405
1406/// Returns `NaN` for a track that does not exist, so callers can tell it apart
1407/// from a valid `alpha` of 0.
1408#[unsafe(no_mangle)]
1409pub unsafe extern "C" fn ss_runtime_get_track_alpha(context: *mut c_void, track: u32) -> c_float {
1410    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_alpha(track)).unwrap_or(f32::NAN)
1411}
1412
1413/// `blend` is one of `SS_RUNTIME_TRACK_BLEND_*`.
1414#[unsafe(no_mangle)]
1415pub unsafe extern "C" fn ss_runtime_set_track_blend(context: *mut c_void, track: u32, blend: u32) -> bool {
1416    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1417        return false;
1418    };
1419    ffi_context.last_error = None;
1420    let blend = match blend {
1421        SS_RUNTIME_TRACK_BLEND_MIX => crate::TrackBlend::Mix,
1422        SS_RUNTIME_TRACK_BLEND_ADDITIVE => crate::TrackBlend::Additive,
1423        _ => {
1424            ffi_context.fail("ss_runtime_set_track_blend", crate::error::SSRuntimeError::InvalidParameter);
1425            return false;
1426        }
1427    };
1428    report(ffi_context, "ss_runtime_set_track_blend", |ctx| ctx.set_track_blend(track, blend))
1429}
1430
1431/// Returns `SS_RUNTIME_INVALID_HANDLE` for a track that does not exist.
1432#[unsafe(no_mangle)]
1433pub unsafe extern "C" fn ss_runtime_get_track_blend(context: *mut c_void, track: u32) -> u32 {
1434    match unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_blend(track)) {
1435        Some(crate::TrackBlend::Mix) => SS_RUNTIME_TRACK_BLEND_MIX,
1436        Some(crate::TrackBlend::Additive) => SS_RUNTIME_TRACK_BLEND_ADDITIVE,
1437        None => SS_RUNTIME_INVALID_HANDLE,
1438    }
1439}
1440
1441/// `sync` is one of `SS_RUNTIME_TRACK_SYNC_*`. Set it before laying an
1442/// animation on the track; a track with nothing on it yet is created for it.
1443#[unsafe(no_mangle)]
1444pub unsafe extern "C" fn ss_runtime_set_track_sync(context: *mut c_void, track: u32, sync: u32) -> bool {
1445    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1446        return false;
1447    };
1448    ffi_context.last_error = None;
1449    let sync = match sync {
1450        SS_RUNTIME_TRACK_SYNC_FREE => crate::TrackSync::Free,
1451        SS_RUNTIME_TRACK_SYNC_START => crate::TrackSync::Start,
1452        _ => {
1453            ffi_context.fail("ss_runtime_set_track_sync", crate::error::SSRuntimeError::InvalidParameter);
1454            return false;
1455        }
1456    };
1457    report(ffi_context, "ss_runtime_set_track_sync", |ctx| ctx.set_track_sync(track, sync))
1458}
1459
1460/// Returns `SS_RUNTIME_INVALID_HANDLE` for a track that does not exist.
1461#[unsafe(no_mangle)]
1462pub unsafe extern "C" fn ss_runtime_get_track_sync(context: *mut c_void, track: u32) -> u32 {
1463    match unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_sync(track)) {
1464        Some(crate::TrackSync::Free) => SS_RUNTIME_TRACK_SYNC_FREE,
1465        Some(crate::TrackSync::Start) => SS_RUNTIME_TRACK_SYNC_START,
1466        None => SS_RUNTIME_INVALID_HANDLE,
1467    }
1468}
1469
1470/// How many tracks exist, silent ones included; at least 1.
1471#[unsafe(no_mangle)]
1472pub unsafe extern "C" fn ss_runtime_get_track_count(context: *mut c_void) -> u32 {
1473    unsafe { get_context(context) }.map_or(0, |c| c.ctx.get_track_count())
1474}
1475
1476/// Silence `track`: its sources are released and its fade cancelled. Track 0 cannot be
1477/// cleared (`InvalidParameter`); fade it to alpha 0 instead.
1478#[unsafe(no_mangle)]
1479pub unsafe extern "C" fn ss_runtime_clear_track(context: *mut c_void, track: u32) -> bool {
1480    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1481        return false;
1482    };
1483    ffi_context.last_error = None;
1484    report(ffi_context, "ss_runtime_clear_track", |ctx| ctx.clear_track(track))
1485}
1486
1487/// Fade `track` to `name` over `duration_ms` — the same time unit as
1488/// `ss_runtime_update`'s delta. A `track` that does not exist yet is created.
1489/// Returns `false` with `InvalidParameter` for a `duration_ms` that is not positive,
1490/// a `NaN` or a null `name`, and with `AnimationNotFound` for a `name` the pack does
1491/// not have or before `ss_runtime_setup_animation`.
1492///
1493/// # Safety
1494/// `name` must be a valid null-terminated UTF-8 (or lossy-decodable) string.
1495#[unsafe(no_mangle)]
1496pub unsafe extern "C" fn ss_runtime_crossfade(context: *mut c_void, track: u32, name: *const c_char, duration_ms: c_float) -> bool {
1497    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1498        return false;
1499    };
1500    ffi_context.last_error = None;
1501    let Some(a) = (unsafe { cstr_to_string(name) }) else {
1502        ffi_context.fail("ss_runtime_crossfade", crate::error::SSRuntimeError::InvalidParameter);
1503        return false;
1504    };
1505    report(ffi_context, "ss_runtime_crossfade", |ctx| ctx.crossfade(track, &a, duration_ms))
1506}
1507
1508/// `ss_runtime_crossfade` by the hash of the name.
1509#[unsafe(no_mangle)]
1510pub unsafe extern "C" fn ss_runtime_crossfade_by_hash(context: *mut c_void, track: u32, hash: u32, duration_ms: c_float) -> bool {
1511    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1512        return false;
1513    };
1514    ffi_context.last_error = None;
1515    report(ffi_context, "ss_runtime_crossfade_by_hash", |ctx| ctx.crossfade_by_hash(track, hash, duration_ms))
1516}
1517
1518/// Drive the alpha of `track` to `target_alpha` over `duration_ms`, the same time unit
1519/// as `ss_runtime_update`'s delta. Returns `false` with `InvalidParameter` for a
1520/// `duration_ms` that is not positive, a `NaN`, or a track that does not exist.
1521#[unsafe(no_mangle)]
1522pub unsafe extern "C" fn ss_runtime_fade_track(context: *mut c_void, track: u32, target_alpha: c_float, duration_ms: c_float) -> bool {
1523    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1524        return false;
1525    };
1526    ffi_context.last_error = None;
1527    report(ffi_context, "ss_runtime_fade_track", |ctx| ctx.fade_track(track, target_alpha, duration_ms))
1528}
1529
1530/// Progress in `[0, 1]` of the fade on `track`; `NaN` when it is not fading.
1531#[unsafe(no_mangle)]
1532pub unsafe extern "C" fn ss_runtime_get_track_fade_progress(context: *mut c_void, track: u32) -> c_float {
1533    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_fade_progress(track)).unwrap_or(f32::NAN)
1534}
1535
1536/// Cancel the fade on `track`, leaving its alpha and weights where they stand.
1537#[unsafe(no_mangle)]
1538pub unsafe extern "C" fn ss_runtime_cancel_track_fade(context: *mut c_void, track: u32) -> bool {
1539    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1540        return false;
1541    };
1542    ffi_context.last_error = None;
1543    report(ffi_context, "ss_runtime_cancel_track_fade", |ctx| ctx.cancel_track_fade(track))
1544}
1545
1546/// Seek the animation on `track`, which is how an axis authored as an animation is
1547/// driven. Returns `false` with `InvalidParameter` when the track has no animation.
1548#[unsafe(no_mangle)]
1549pub unsafe extern "C" fn ss_runtime_set_track_frame(context: *mut c_void, track: u32, frame: c_float) -> bool {
1550    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1551        return false;
1552    };
1553    ffi_context.last_error = None;
1554    report(ffi_context, "ss_runtime_set_track_frame", |ctx| ctx.set_track_frame(track, frame))
1555}
1556
1557/// Returns `NaN` when the track has no animation on it.
1558#[unsafe(no_mangle)]
1559pub unsafe extern "C" fn ss_runtime_get_track_frame(context: *mut c_void, track: u32) -> c_float {
1560    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_frame(track)).unwrap_or(f32::NAN)
1561}
1562
1563/// The speed of `track`, as a multiple of each animation's frame rate. The track keeps
1564/// it across a crossfade or a new animation. Track 0's is `ss_runtime_set_speed_scale`.
1565#[unsafe(no_mangle)]
1566pub unsafe extern "C" fn ss_runtime_set_track_speed(context: *mut c_void, track: u32, speed: c_float) -> bool {
1567    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1568        return false;
1569    };
1570    ffi_context.last_error = None;
1571    report(ffi_context, "ss_runtime_set_track_speed", |ctx| ctx.set_track_speed(track, speed))
1572}
1573
1574/// What `ss_runtime_set_track_speed` stored (a negative speed reads back as
1575/// `0.0`); `NaN` for a track that does not exist.
1576#[unsafe(no_mangle)]
1577pub unsafe extern "C" fn ss_runtime_get_track_speed(context: *mut c_void, track: u32) -> c_float {
1578    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_speed(track)).unwrap_or(f32::NAN)
1579}
1580
1581/// The rate in frames per second `track` plays its animations at; `0` or a negative
1582/// rate clears it. The track keeps it, as it does its speed.
1583#[unsafe(no_mangle)]
1584pub unsafe extern "C" fn ss_runtime_set_track_frame_rate(context: *mut c_void, track: u32, frame_rate: c_int) -> bool {
1585    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1586        return false;
1587    };
1588    ffi_context.last_error = None;
1589    report(ffi_context, "ss_runtime_set_track_frame_rate", |ctx| ctx.set_track_frame_rate(track, frame_rate))
1590}
1591
1592/// The rate the track's animation plays at; `0` for a track with no animation
1593/// and no override, `-1` for a track that does not exist.
1594#[unsafe(no_mangle)]
1595pub unsafe extern "C" fn ss_runtime_get_track_frame_rate(context: *mut c_void, track: u32) -> i32 {
1596    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_frame_rate(track)).unwrap_or(-1)
1597}
1598
1599/// `ss_runtime_set_skip_frames` for `track`. The track keeps it, as it does its speed.
1600#[unsafe(no_mangle)]
1601pub unsafe extern "C" fn ss_runtime_set_track_skip_frames(context: *mut c_void, track: u32, skip: bool) -> bool {
1602    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1603        return false;
1604    };
1605    ffi_context.last_error = None;
1606    report(ffi_context, "ss_runtime_set_track_skip_frames", |ctx| ctx.set_track_skip_frames(track, skip))
1607}
1608
1609/// `false` for a track that does not exist.
1610#[unsafe(no_mangle)]
1611pub unsafe extern "C" fn ss_runtime_get_track_skip_frames(context: *mut c_void, track: u32) -> bool {
1612    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_skip_frames(track)).unwrap_or(false)
1613}
1614
1615/// `direction`: 0 = forward, otherwise backward. `style`: 0 = normal,
1616/// otherwise ping-pong; as `ss_runtime_set_playback_direction`.
1617#[unsafe(no_mangle)]
1618pub unsafe extern "C" fn ss_runtime_set_track_playback_direction(context: *mut c_void, track: u32, direction: c_int, style: c_int) -> bool {
1619    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1620        return false;
1621    };
1622    ffi_context.last_error = None;
1623    let d = if direction == 0 { crate::eval::playback_controller::PlaybackDirection::Forward } else { crate::eval::playback_controller::PlaybackDirection::Backward };
1624    let s = if style == 0 { crate::eval::playback_controller::PlaybackStyle::Normal } else { crate::eval::playback_controller::PlaybackStyle::PingPong };
1625    report(ffi_context, "ss_runtime_set_track_playback_direction", |ctx| ctx.set_track_playback_direction(track, d, s))
1626}
1627
1628/// 0 = forward, 1 = backward; `-1` for a track that does not exist.
1629#[unsafe(no_mangle)]
1630pub unsafe extern "C" fn ss_runtime_get_track_playback_direction(context: *mut c_void, track: u32) -> i32 {
1631    match unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_playback_direction(track)) {
1632        Some(crate::eval::playback_controller::PlaybackDirection::Forward) => 0,
1633        Some(crate::eval::playback_controller::PlaybackDirection::Backward) => 1,
1634        None => -1,
1635    }
1636}
1637
1638/// 0 = normal, 1 = ping-pong; `-1` for a track that does not exist.
1639#[unsafe(no_mangle)]
1640pub unsafe extern "C" fn ss_runtime_get_track_playback_style(context: *mut c_void, track: u32) -> i32 {
1641    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_playback_style(track)).map(|s| s as i32).unwrap_or(-1)
1642}
1643
1644/// How many times the track's animation plays before it holds its last frame;
1645/// `0` or a negative count loops forever. It belongs to the animation on the
1646/// track: laying another one there starts it looping forever again.
1647#[unsafe(no_mangle)]
1648pub unsafe extern "C" fn ss_runtime_set_track_loop_count(context: *mut c_void, track: u32, loop_count: c_int) -> bool {
1649    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1650        return false;
1651    };
1652    ffi_context.last_error = None;
1653    report(ffi_context, "ss_runtime_set_track_loop_count", |ctx| ctx.set_track_loop_count(track, loop_count))
1654}
1655
1656/// `-1` for a track that loops forever; `0` for a track with no animation.
1657#[unsafe(no_mangle)]
1658pub unsafe extern "C" fn ss_runtime_get_track_loop_count(context: *mut c_void, track: u32) -> i32 {
1659    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_loop_count(track)).unwrap_or(0)
1660}
1661
1662/// `true` once the track's animation has played its loop count out and holds
1663/// its last frame, as `ss_runtime_is_finished` is for track 0. `false` for a
1664/// track with no animation.
1665#[unsafe(no_mangle)]
1666pub unsafe extern "C" fn ss_runtime_is_track_finished(context: *mut c_void, track: u32) -> bool {
1667    unsafe { get_context(context) }.is_some_and(|c| c.ctx.is_track_finished(track))
1668}
1669
1670/// `true` for the update in which the track's animation wrapped back to its
1671/// start, as `ss_runtime_just_looped` is for track 0.
1672#[unsafe(no_mangle)]
1673pub unsafe extern "C" fn ss_runtime_track_just_looped(context: *mut c_void, track: u32) -> bool {
1674    unsafe { get_context(context) }.is_some_and(|c| c.ctx.track_just_looped(track))
1675}
1676
1677/// How far into a crossfade on `track` the outgoing side keeps firing events:
1678/// it fires while its share of the track, `1 - t`, is at least `threshold`.
1679/// The default, `+inf`, keeps it silent from the moment the fade begins.
1680#[unsafe(no_mangle)]
1681pub unsafe extern "C" fn ss_runtime_set_track_outgoing_event_threshold(context: *mut c_void, track: u32, threshold: c_float) -> bool {
1682    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1683        return false;
1684    };
1685    ffi_context.last_error = None;
1686    report(ffi_context, "ss_runtime_set_track_outgoing_event_threshold", |ctx| ctx.set_track_outgoing_event_threshold(track, threshold))
1687}
1688
1689/// `NaN` for a track that does not exist.
1690#[unsafe(no_mangle)]
1691pub unsafe extern "C" fn ss_runtime_get_track_outgoing_event_threshold(context: *mut c_void, track: u32) -> c_float {
1692    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_outgoing_event_threshold(track)).unwrap_or(f32::NAN)
1693}
1694
1695/// Handle of the source carrying the track's animation, so it can be given a
1696/// weight once the track holds several. `SS_RUNTIME_INVALID_HANDLE` when the
1697/// track has no animation.
1698#[unsafe(no_mangle)]
1699pub unsafe extern "C" fn ss_runtime_get_track_main_source(context: *mut c_void, track: u32) -> u32 {
1700    unsafe { get_context(context) }.and_then(|c| c.ctx.get_track_main_source(track)).unwrap_or(SS_RUNTIME_INVALID_HANDLE)
1701}
1702
1703/// Add another weighted source to `track` (locomotion-style blending). Returns
1704/// `SS_RUNTIME_INVALID_HANDLE` on failure.
1705///
1706/// # Safety
1707/// `name` must be a valid null-terminated UTF-8 (or lossy-decodable) string.
1708#[unsafe(no_mangle)]
1709pub unsafe extern "C" fn ss_runtime_add_track_source(context: *mut c_void, track: u32, name: *const c_char, weight: c_float) -> u32 {
1710    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1711        return SS_RUNTIME_INVALID_HANDLE;
1712    };
1713    ffi_context.last_error = None;
1714    let Some(a) = (unsafe { cstr_to_string(name) }) else {
1715        ffi_context.fail("ss_runtime_add_track_source", crate::error::SSRuntimeError::InvalidParameter);
1716        return SS_RUNTIME_INVALID_HANDLE;
1717    };
1718    match ffi_context.ctx.add_track_source(track, &a, weight) {
1719        Ok(h) => h,
1720        Err(e) => {
1721            ffi_context.fail("ss_runtime_add_track_source", e);
1722            SS_RUNTIME_INVALID_HANDLE
1723        }
1724    }
1725}
1726
1727/// `ss_runtime_add_track_source` by the hash of the name.
1728#[unsafe(no_mangle)]
1729pub unsafe extern "C" fn ss_runtime_add_track_source_by_hash(context: *mut c_void, track: u32, hash: u32, weight: c_float) -> u32 {
1730    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1731        return SS_RUNTIME_INVALID_HANDLE;
1732    };
1733    ffi_context.last_error = None;
1734    match ffi_context.ctx.add_track_source_by_hash(track, hash, weight) {
1735        Ok(h) => h,
1736        Err(e) => {
1737            ffi_context.fail("ss_runtime_add_track_source_by_hash", e);
1738            SS_RUNTIME_INVALID_HANDLE
1739        }
1740    }
1741}
1742
1743/// The proportion of a source within its track; `ss_runtime_set_track_alpha` is the
1744/// strength of the track as a whole. Returns `false` with `InvalidParameter` for an
1745/// invalid or released handle.
1746#[unsafe(no_mangle)]
1747pub unsafe extern "C" fn ss_runtime_set_source_weight(context: *mut c_void, handle: u32, weight: c_float) -> bool {
1748    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1749        return false;
1750    };
1751    ffi_context.last_error = None;
1752    report(ffi_context, "ss_runtime_set_source_weight", |ctx| ctx.set_source_weight(handle, weight))
1753}
1754
1755/// Returns `NaN` for an invalid or released handle, so `weight == 0` stays
1756/// distinguishable from "no such source".
1757#[unsafe(no_mangle)]
1758pub unsafe extern "C" fn ss_runtime_get_source_weight(context: *mut c_void, handle: u32) -> c_float {
1759    unsafe { get_context(context) }.and_then(|c| c.ctx.get_source_weight(handle)).unwrap_or(f32::NAN)
1760}
1761
1762/// Seek one source. Returns `false` with `InvalidParameter` for an invalid or released handle.
1763#[unsafe(no_mangle)]
1764pub unsafe extern "C" fn ss_runtime_set_source_frame(context: *mut c_void, handle: u32, frame: c_float) -> bool {
1765    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1766        return false;
1767    };
1768    ffi_context.last_error = None;
1769    report(ffi_context, "ss_runtime_set_source_frame", |ctx| ctx.set_source_frame(handle, frame))
1770}
1771
1772/// Which animation the source `handle` plays, as an index into the ssab's
1773/// `animations()`; `-1` for a handle that names no source. An event index
1774/// addresses the `events()` of the animation of the source that fired it
1775/// (`ss_runtime_get_passed_event_source_handle`), track 0's included: after a
1776/// crossfade on track 0 that is the incoming animation.
1777#[unsafe(no_mangle)]
1778pub unsafe extern "C" fn ss_runtime_get_source_animation_index(context: *mut c_void, handle: u32) -> i32 {
1779    unsafe { get_context(context) }.and_then(|c| c.ctx.get_source_animation_index(handle)).map(|i| i as i32).unwrap_or(-1)
1780}
1781
1782/// Which animation track 0's main source plays, as an index into the ssab's
1783/// `animations()`: a crossfade or a track animation on track 0 changes it from
1784/// the call on. `-1` before anything is set up.
1785#[unsafe(no_mangle)]
1786pub unsafe extern "C" fn ss_runtime_get_current_animation_index(context: *mut c_void) -> i32 {
1787    unsafe { get_context(context) }.and_then(|c| c.ctx.get_current_animation_index()).map(|i| i as i32).unwrap_or(-1)
1788}
1789
1790/// The playhead of a source; `NaN` for an invalid or released handle.
1791#[unsafe(no_mangle)]
1792pub unsafe extern "C" fn ss_runtime_get_source_frame(context: *mut c_void, handle: u32) -> c_float {
1793    unsafe { get_context(context) }.and_then(|c| c.ctx.get_source_frame(handle)).unwrap_or(f32::NAN)
1794}
1795
1796/// A source fires events once its weight reaches `threshold`. The default, `+inf`,
1797/// keeps every source silent but track 0's main one, which always fires. Returns `false`
1798/// with `InvalidParameter` for an invalid or released handle.
1799#[unsafe(no_mangle)]
1800pub unsafe extern "C" fn ss_runtime_set_source_event_threshold(context: *mut c_void, handle: u32, threshold: c_float) -> bool {
1801    let Some(ffi_context) = (unsafe { get_context(context) }) else {
1802        return false;
1803    };
1804    ffi_context.last_error = None;
1805    report(ffi_context, "ss_runtime_set_source_event_threshold", |ctx| ctx.set_source_event_threshold(handle, threshold))
1806}
1807
1808/// `NaN` for an invalid or released handle.
1809#[unsafe(no_mangle)]
1810pub unsafe extern "C" fn ss_runtime_get_source_event_threshold(context: *mut c_void, handle: u32) -> c_float {
1811    unsafe { get_context(context) }.and_then(|c| c.ctx.get_source_event_threshold(handle)).unwrap_or(f32::NAN)
1812}
1813
1814/// Create a new EffectSlot bound to `resource`. Returns null on failure
1815/// (resource not loaded, effect_name_hash not found, malformed effect data).
1816///
1817/// The slot holds its own reference to `resource`, so `ss_resource_destroy`
1818/// may be called while the slot is still alive, exactly as it may while a
1819/// Context is still bound.
1820#[unsafe(no_mangle)]
1821pub unsafe extern "C" fn ss_effect_slot_create(resource: *const c_void, effect_name_hash: u32, seed: u32) -> *mut c_void {
1822    if resource.is_null() {
1823        return core::ptr::null_mut();
1824    }
1825    // SAFETY: the C caller passes a live handle from `ss_resource_create_*`.
1826    let resource = unsafe { share_resource(resource) };
1827    match OwningEffectSlot::new(resource, effect_name_hash, seed) {
1828        Ok(slot) => Box::into_raw(Box::new(slot)) as *mut c_void,
1829        Err(_) => core::ptr::null_mut(),
1830    }
1831}
1832
1833/// Release a slot and its share of the resource. Null is ignored.
1834#[unsafe(no_mangle)]
1835pub unsafe extern "C" fn ss_effect_slot_destroy(slot: *mut c_void) {
1836    if slot.is_null() {
1837        return;
1838    }
1839    unsafe {
1840        let _ = Box::from_raw(slot as *mut OwningEffectSlot);
1841    }
1842}
1843
1844/// Reset the slot's playback / "last started key" memory to its just-created
1845/// state without destroying it. Call on an explicit head-out (`ss_runtime_play`
1846/// / replay) so a re-played animation re-fires its effect from scratch instead
1847/// of debouncing the first key as the same one the slot last started. The
1848/// resource binding and emitter caches are preserved.
1849#[unsafe(no_mangle)]
1850pub unsafe extern "C" fn ss_effect_slot_reset(slot: *mut c_void) {
1851    if slot.is_null() {
1852        return;
1853    }
1854    let slot = unsafe { &mut *(slot as *mut OwningEffectSlot) };
1855    slot.reset();
1856}
1857
1858/// Advance the slot one frame. The caller resolves the active effect event
1859/// (via `ss_runtime_get_active_effect_event`) and feeds it here together with
1860/// timing inputs. `parent_looped` re-arms transition detection across the
1861/// parent's loop edge.
1862///
1863/// `y_flip = true` mirrors each particle's Y position, rotation sign and quad, for
1864/// Y-down rendering of Y-up authored content (Godot, pixi.js). Pass `false` for
1865/// Y-up engines (Unity 2D).
1866///
1867/// `vert_stride` selects the vertex layout of the returned `EffectDrawPlan`:
1868/// `2` packs (x, y) pairs (Godot, pixi.js, wgpu); `3` packs (x, y, 0) triples
1869/// (Unity Mesh, Unreal procedural mesh). Other values fall back to `2`.
1870///
1871/// `draw` is whether the part is in this frame's `draw_order`. Step a hidden
1872/// part's slot anyway, with `draw = false`: it keeps the effect's clock and
1873/// transitions moving and builds no plan, and the next drawn step builds the
1874/// plan an always-drawn slot would. A caller that steps before it has this
1875/// frame's `draw_order` passes `true`.
1876///
1877/// Returns `EffectDrawPlan` FlatBuffer pointer + length when visible. Buffer
1878/// is valid only until the next call on the same slot.
1879#[unsafe(no_mangle)]
1880pub unsafe extern "C" fn ss_effect_slot_step(slot: *mut c_void, ev: ss_effect_event_info, parent_frame: f32, delta_seconds: f32, fps: f32, parent_looped: bool, y_flip: bool, vert_stride: u8, draw: bool) -> ss_effect_step_result {
1881    if slot.is_null() {
1882        return ss_effect_step_result::not_visible();
1883    }
1884    let slot = unsafe { &mut *(slot as *mut OwningEffectSlot) };
1885    slot.step(ev, parent_frame, delta_seconds, fps, parent_looped, y_flip, vert_stride, draw)
1886}
1887
1888/// The seed the slot was created with; `0` for a null slot.
1889#[unsafe(no_mangle)]
1890pub unsafe extern "C" fn ss_effect_slot_get_seed(slot: *mut c_void) -> u32 {
1891    if slot.is_null() {
1892        return 0;
1893    }
1894    let slot = unsafe { &*(slot as *const OwningEffectSlot) };
1895    slot.get_seed()
1896}
1897
1898/// Whether the slot is currently running independently of the parent's frame.
1899/// Reflects the most recently seen `EventEffect.independent`. Callers use
1900/// this to decide whether to schedule continuous tick updates regardless of
1901/// parent frame change.
1902#[unsafe(no_mangle)]
1903pub unsafe extern "C" fn ss_effect_slot_is_independent(slot: *mut c_void) -> bool {
1904    if slot.is_null() {
1905        return false;
1906    }
1907    let slot = unsafe { &*(slot as *const OwningEffectSlot) };
1908    slot.is_independent()
1909}
1910
1911/// Create a fresh InstanceSlot. Slots are stateless at construction (no
1912/// resource binding) — `step` operates against a child runtime context
1913/// supplied per call.
1914#[unsafe(no_mangle)]
1915pub extern "C" fn ss_instance_slot_create() -> *mut c_void {
1916    Box::into_raw(Box::new(crate::InstanceSlot::new())) as *mut c_void
1917}
1918
1919/// Release a slot. Null is ignored.
1920#[unsafe(no_mangle)]
1921pub unsafe extern "C" fn ss_instance_slot_destroy(slot: *mut c_void) {
1922    if slot.is_null() {
1923        return;
1924    }
1925    unsafe {
1926        let _ = Box::from_raw(slot as *mut crate::InstanceSlot);
1927    }
1928}
1929
1930/// Reset the slot's "last started key" memory to its just-created state without
1931/// destroying it. Call on an explicit head-out (`ss_runtime_play` / replay) so a
1932/// re-played animation re-fires the instance child from scratch instead of
1933/// debouncing the first key as the same one the slot last started.
1934#[unsafe(no_mangle)]
1935pub unsafe extern "C" fn ss_instance_slot_reset(slot: *mut c_void) {
1936    if slot.is_null() {
1937        return;
1938    }
1939    let slot = unsafe { &mut *(slot as *mut crate::InstanceSlot) };
1940    slot.reset();
1941}
1942
1943/// Drive the instance slot for one tick. The caller resolves the active
1944/// EventInstance (via `ss_runtime_get_active_event_instance` against the
1945/// *parent* runtime context) and passes the *child* runtime context here so
1946/// that label resolution and frame stepping happen against the right Context.
1947/// Returns `transitioned == true` on EventInstance edges, having configured the
1948/// child for the new key without starting it: the caller then calls
1949/// `ss_runtime_play` on the child (an independent child never advances
1950/// otherwise). Draw the child at `child_frame_no` on that tick too: the slot
1951/// already put it where `play` snaps it, and a synced child's value follows the
1952/// parent, which reading the frame back after `play` would lose.
1953#[unsafe(no_mangle)]
1954pub unsafe extern "C" fn ss_instance_slot_step(slot: *mut c_void, ev: ss_event_instance_info, child_ctx: *mut c_void, parent_frame: f32, delta_seconds: f32, parent_looped: bool) -> ss_instance_step_result {
1955    if slot.is_null() {
1956        return ss_instance_step_result::not_visible();
1957    }
1958    let Some(child_ffi) = (unsafe { get_context(child_ctx) }) else {
1959        return ss_instance_step_result::not_visible();
1960    };
1961    let slot = unsafe { &mut *(slot as *mut crate::InstanceSlot) };
1962    slot.step(ev, &mut child_ffi.ctx, parent_frame, delta_seconds, parent_looped)
1963}
1964
1965/// Whether the slot's current key plays the child on its own time rather than the parent's frame.
1966#[unsafe(no_mangle)]
1967pub unsafe extern "C" fn ss_instance_slot_is_independent(slot: *mut c_void) -> bool {
1968    if slot.is_null() {
1969        return false;
1970    }
1971    let slot = unsafe { &*(slot as *const crate::InstanceSlot) };
1972    slot.is_independent()
1973}
1974
1975/// The speed the most recent `ss_instance_slot_step` drove the child at, `1.0`
1976/// before the first or for a null slot. Usually the key's `speed`, but while
1977/// the slot ignores the implicit frame-0 key it keeps the last real key's, so
1978/// the event the host resolved says `1.0` when the child is not running at it.
1979/// Scale the elapsed time handed to the child's own instance and effect slots
1980/// by its absolute value, not by the resolved event's `speed`.
1981#[unsafe(no_mangle)]
1982pub unsafe extern "C" fn ss_instance_slot_get_speed(slot: *mut c_void) -> f32 {
1983    if slot.is_null() {
1984        return 1.0;
1985    }
1986    let slot = unsafe { &*(slot as *const crate::InstanceSlot) };
1987    slot.get_speed()
1988}
1989
1990/// Set the render mode. `mode` is interpreted as:
1991///   0 = Direct       (pre-bake world matrices; default)
1992///   1 = SceneGraph   (skip world matrix pre-computation)
1993/// Unknown values fall back to Direct.
1994#[unsafe(no_mangle)]
1995pub unsafe extern "C" fn ss_runtime_set_render_mode(context: *mut c_void, mode: u8) {
1996    if let Some(ffi_context) = unsafe { get_context(context) } {
1997        ffi_context.ctx.set_render_mode(crate::eval::RenderMode::from_u8(mode));
1998    }
1999}
2000
2001/// 0 = Direct, 1 = SceneGraph.
2002#[unsafe(no_mangle)]
2003pub unsafe extern "C" fn ss_runtime_get_render_mode(context: *mut c_void) -> u8 {
2004    if let Some(ffi_context) = unsafe { get_context(context) } {
2005        return ffi_context.ctx.render_mode() as u8;
2006    }
2007    crate::eval::RenderMode::Direct as u8
2008}
2009
2010/// 0 = Y-up (the default), 1 = Y-down, which flips Y coordinates and rotation. Any other value is Y-up.
2011#[unsafe(no_mangle)]
2012pub unsafe extern "C" fn ss_runtime_set_coordinate_system(context: *mut c_void, coordinate_system: i32) {
2013    if let Some(ffi_context) = unsafe { get_context(context) } {
2014        let cs = match coordinate_system {
2015            1 => crate::eval::SsCoordinateSystem::YDown,
2016            _ => crate::eval::SsCoordinateSystem::YUp,
2017        };
2018        ffi_context.ctx.set_coordinate_system(cs);
2019    }
2020}
2021
2022/// 0 = Y-up, 1 = Y-down.
2023#[unsafe(no_mangle)]
2024pub unsafe extern "C" fn ss_runtime_get_coordinate_system(context: *mut c_void) -> i32 {
2025    if let Some(ffi_context) = unsafe { get_context(context) } {
2026        match ffi_context.ctx.get_coordinate_system() {
2027            crate::eval::SsCoordinateSystem::YDown => 1,
2028            crate::eval::SsCoordinateSystem::YUp => 0,
2029        }
2030    } else {
2031        0
2032    }
2033}
2034
2035/// 0 = the canvas center (the default), 1 = its top-left corner, which offsets root
2036/// parts by half the canvas. Any other value is the center.
2037#[unsafe(no_mangle)]
2038pub unsafe extern "C" fn ss_runtime_set_origin(context: *mut c_void, origin: i32) {
2039    if let Some(ffi_context) = unsafe { get_context(context) } {
2040        let o = match origin {
2041            1 => crate::eval::SsOrigin::TopLeft,
2042            _ => crate::eval::SsOrigin::Center,
2043        };
2044        ffi_context.ctx.set_origin(o);
2045    }
2046}
2047
2048/// 0 = the canvas center, 1 = its top-left corner.
2049#[unsafe(no_mangle)]
2050pub unsafe extern "C" fn ss_runtime_get_origin(context: *mut c_void) -> i32 {
2051    if let Some(ffi_context) = unsafe { get_context(context) } {
2052        match ffi_context.ctx.get_origin() {
2053            crate::eval::SsOrigin::TopLeft => 1,
2054            crate::eval::SsOrigin::Center => 0,
2055        }
2056    } else {
2057        0
2058    }
2059}
2060
2061/// 0 = pixels (the default), 1 = normalized, which divides each part's position by the
2062/// canvas size. Sizes, local vertices and UVs stay in pixels. Any other value is pixels.
2063#[unsafe(no_mangle)]
2064pub unsafe extern "C" fn ss_runtime_set_unit(context: *mut c_void, unit: i32) {
2065    if let Some(ffi_context) = unsafe { get_context(context) } {
2066        let u = match unit {
2067            1 => crate::eval::SsUnit::Normalized,
2068            _ => crate::eval::SsUnit::Pixel,
2069        };
2070        ffi_context.ctx.set_unit(u);
2071    }
2072}
2073
2074/// 0 = pixels, 1 = normalized.
2075#[unsafe(no_mangle)]
2076pub unsafe extern "C" fn ss_runtime_get_unit(context: *mut c_void) -> i32 {
2077    if let Some(ffi_context) = unsafe { get_context(context) } {
2078        match ffi_context.ctx.get_unit() {
2079            crate::eval::SsUnit::Normalized => 1,
2080            crate::eval::SsUnit::Pixel => 0,
2081        }
2082    } else {
2083        0
2084    }
2085}
2086
2087/// How many events the last `ss_runtime_update` passed. They stay until the next one,
2088/// `ss_runtime_setup_animation`, `ss_runtime_bind_resource` or `ss_runtime_reset`.
2089#[unsafe(no_mangle)]
2090pub unsafe extern "C" fn ss_runtime_get_passed_event_count(context: *mut c_void) -> i32 {
2091    if let Some(ffi_context) = unsafe { get_context(context) } {
2092        return ffi_context.ctx.get_passed_event_indices().len() as i32;
2093    }
2094    0
2095}
2096
2097/// Collected event `index`, as an index into the `events()` of the animation of the
2098/// source that fired it (`ss_runtime_get_passed_event_source_handle`); `-1` out of range.
2099#[unsafe(no_mangle)]
2100pub unsafe extern "C" fn ss_runtime_get_passed_event_index(context: *mut c_void, index: i32) -> i32 {
2101    if let Some(ffi_context) = unsafe { get_context(context) }
2102        && let Some(&event_idx) = ffi_context.ctx.get_passed_event_indices().get(index as usize)
2103    {
2104        return event_idx;
2105    }
2106    -1
2107}
2108
2109/// Which source fired the collected event at `index` — parallel to
2110/// `ss_runtime_get_passed_event_index`, and read with the same index.
2111///
2112/// With every source and every track's outgoing side at the default event
2113/// threshold (`+∞`) this is uniformly `ss_runtime_get_track_main_source` of
2114/// track 0, so a Player that does not use animation mixing can ignore it. It
2115/// diverges once a secondary source opts in to firing events via
2116/// `ss_runtime_set_source_event_threshold`, or a crossfade's outgoing side via
2117/// `ss_runtime_set_track_outgoing_event_threshold`, and that is when a host
2118/// needs it: without it, two blended animations' events arrive in one
2119/// undifferentiated list.
2120///
2121/// Returns `SS_RUNTIME_INVALID_HANDLE` for a negative or out-of-range `index`,
2122/// which no live handle ever equals.
2123#[unsafe(no_mangle)]
2124pub unsafe extern "C" fn ss_runtime_get_passed_event_source_handle(context: *mut c_void, index: i32) -> u32 {
2125    if index >= 0
2126        && let Some(ffi_context) = unsafe { get_context(context) }
2127        && let Some(&handle) = ffi_context.ctx.get_passed_event_source_handles().get(index as usize)
2128    {
2129        return handle;
2130    }
2131    u32::MAX
2132}
2133
2134/// Resolve the active `EventInstance` for `slot_index` on the parent's
2135/// currently selected animation, at the current frame. Returns SS6
2136/// default semantics (`is_synthetic_default = true`, `loop_num = 1`,
2137/// `speed = 1.0`) when no event is active, so callers don't need to
2138/// branch on the no-event case.
2139///
2140/// `start_label_hash` / `end_label_hash` are returned raw. They are
2141/// already resolved internally by `ss_instance_slot_step` for the
2142/// child runtime — most Players should consume the slot helper rather
2143/// than resolving labels themselves.
2144#[unsafe(no_mangle)]
2145pub unsafe extern "C" fn ss_runtime_get_active_event_instance(context: *mut c_void, slot_index: u32) -> ss_event_instance_info {
2146    if let Some(ffi_context) = unsafe { get_context(context) } {
2147        return ffi_context.ctx.get_active_event_instance(slot_index);
2148    }
2149    ss_event_instance_info::synthetic_default()
2150}
2151
2152/// Resolve the active `EventEffect` for `slot_index` on the parent's
2153/// currently selected animation, at the current frame. When no real event
2154/// has fired yet, falls back to `InitialEvents.effect` for the slot (with
2155/// `is_synthetic_default = true`); if neither exists, returns full SS6
2156/// defaults (`start_time = 0`, `speed = 1.0`, `independent = false`).
2157#[unsafe(no_mangle)]
2158pub unsafe extern "C" fn ss_runtime_get_active_effect_event(context: *mut c_void, slot_index: u32) -> ss_effect_event_info {
2159    if let Some(ffi_context) = unsafe { get_context(context) } {
2160        return ffi_context.ctx.get_active_effect_event(slot_index);
2161    }
2162    ss_effect_event_info::synthetic_default()
2163}
2164
2165/// The FNV-1a hash the converter stores for a name, which the `_by_hash` calls
2166/// take. `0` for a null or non-UTF-8 string.
2167///
2168/// # Safety
2169///
2170/// `s` must be null or a valid null-terminated string.
2171#[unsafe(no_mangle)]
2172pub unsafe extern "C" fn ss_runtime_hash_string(s: *const c_char) -> u32 {
2173    if s.is_null() {
2174        return 0;
2175    }
2176    let c_str = unsafe { core::ffi::CStr::from_ptr(s) };
2177    if let Ok(rust_str) = c_str.to_str() { crate::fnv1a_hash_str(rust_str) } else { 0 }
2178}
2179
2180/// Resolve a part name to its `part_index` in the current primary animation.
2181/// Returns `-1` on null context / null or invalid name / not found.
2182///
2183/// # Safety
2184/// `part_name` must be null or a valid null-terminated string.
2185#[unsafe(no_mangle)]
2186pub unsafe extern "C" fn ss_runtime_find_part_index(context: *mut c_void, part_name: *const c_char) -> i32 {
2187    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2188        return -1;
2189    };
2190    if part_name.is_null() {
2191        return -1;
2192    }
2193    let c_str = unsafe { CStr::from_ptr(part_name) };
2194    let Ok(name) = c_str.to_str() else {
2195        return -1;
2196    };
2197    ffi_context.ctx.find_part_index(name)
2198}
2199
2200/// Set or clear a per-part visibility override.
2201/// `force`: `0` = clear/revert, `1` = force-hide. Anything else, `2` (reserved for
2202/// force-visible) included, returns `false` with `InvalidParameter`.
2203/// `cascade != 0` propagates a force-hide to descendants.
2204#[unsafe(no_mangle)]
2205pub unsafe extern "C" fn ss_runtime_set_part_visibility_override(context: *mut c_void, part: u32, force: c_uchar, cascade: c_uchar) -> bool {
2206    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2207        return false;
2208    };
2209    ffi_context.last_error = None;
2210    match ffi_context.ctx.set_part_visibility_override(part, force, cascade != 0) {
2211        Ok(_) => true,
2212        Err(e) => {
2213            ffi_context.fail("ss_runtime_set_part_visibility_override", e);
2214            false
2215        }
2216    }
2217}
2218
2219/// Clear a part's visibility override (revert to animation).
2220#[unsafe(no_mangle)]
2221pub unsafe extern "C" fn ss_runtime_clear_part_visibility_override(context: *mut c_void, part: u32) -> bool {
2222    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2223        return false;
2224    };
2225    ffi_context.last_error = None;
2226    match ffi_context.ctx.clear_part_visibility_override(part) {
2227        Ok(_) => true,
2228        Err(e) => {
2229            ffi_context.fail("ss_runtime_clear_part_visibility_override", e);
2230            false
2231        }
2232    }
2233}
2234
2235/// Set a per-part color override from a single packed RGBA (`0xRRGGBBAA`, fills
2236/// all four corners). `blend_op`: `0=Mix 1=Mul 2=Add 3=Sub`. `priority_mode`:
2237/// `0=OverwriteOnNextKeyframe 1=HoldUntilNextAnimation 2=Permanent`. Normal
2238/// parts only.
2239#[unsafe(no_mangle)]
2240pub unsafe extern "C" fn ss_runtime_set_part_color_override(context: *mut c_void, part: u32, blend_op: c_uchar, rgba: u32, priority_mode: c_uchar) -> bool {
2241    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2242        return false;
2243    };
2244    ffi_context.last_error = None;
2245    match ffi_context.ctx.set_part_color_override(part, blend_op, rgba, priority_mode) {
2246        Ok(_) => true,
2247        Err(e) => {
2248            ffi_context.fail("ss_runtime_set_part_color_override", e);
2249            false
2250        }
2251    }
2252}
2253
2254/// Set a per-part color override from four packed RGBA corners in ssruntime
2255/// order `lt, rt, lb, rb` (`rgba_ltrtlbrb` points to 4 `uint32` = `0xRRGGBBAA`).
2256///
2257/// # Safety
2258/// `rgba_ltrtlbrb` must be null or point to 4 readable `uint32`.
2259#[unsafe(no_mangle)]
2260pub unsafe extern "C" fn ss_runtime_set_part_color_override_corners(context: *mut c_void, part: u32, blend_op: c_uchar, rgba_ltrtlbrb: *const u32, priority_mode: c_uchar) -> bool {
2261    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2262        return false;
2263    };
2264    ffi_context.last_error = None;
2265    if rgba_ltrtlbrb.is_null() {
2266        ffi_context.fail("ss_runtime_set_part_color_override_corners", crate::error::SSRuntimeError::InvalidParameter);
2267        return false;
2268    }
2269    let packed = unsafe { core::slice::from_raw_parts(rgba_ltrtlbrb, 4) };
2270    let corners = [packed[0].to_be_bytes(), packed[1].to_be_bytes(), packed[2].to_be_bytes(), packed[3].to_be_bytes()];
2271    match ffi_context.ctx.set_part_color_override_corners(part, blend_op, corners, priority_mode) {
2272        Ok(_) => true,
2273        Err(e) => {
2274            ffi_context.fail("ss_runtime_set_part_color_override_corners", e);
2275            false
2276        }
2277    }
2278}
2279
2280/// Clear a part's color override.
2281#[unsafe(no_mangle)]
2282pub unsafe extern "C" fn ss_runtime_clear_part_color_override(context: *mut c_void, part: u32) -> bool {
2283    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2284        return false;
2285    };
2286    ffi_context.last_error = None;
2287    match ffi_context.ctx.clear_part_color_override(part) {
2288        Ok(_) => true,
2289        Err(e) => {
2290            ffi_context.fail("ss_runtime_clear_part_color_override", e);
2291            false
2292        }
2293    }
2294}
2295
2296/// Set a per-part cell override, identified by FNV-1a hashes of the cellmap name
2297/// (without `.ssce`) and the cell name. `(0, 0)` reverts to the animation.
2298/// `priority_mode`: `0=OverwriteOnNextKeyframe 1=HoldUntilNextAnimation 2=
2299/// Permanent`. Normal + Mask parts only. Fails if the cell cannot be resolved.
2300#[unsafe(no_mangle)]
2301pub unsafe extern "C" fn ss_runtime_set_part_cell_override(context: *mut c_void, part: u32, cellmap_name_hash: u32, cell_name_hash: u32, priority_mode: c_uchar) -> bool {
2302    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2303        return false;
2304    };
2305    ffi_context.last_error = None;
2306    match ffi_context.ctx.set_part_cell_override(part, cellmap_name_hash, cell_name_hash, priority_mode) {
2307        Ok(_) => true,
2308        Err(e) => {
2309            ffi_context.fail("ss_runtime_set_part_cell_override", e);
2310            false
2311        }
2312    }
2313}
2314
2315/// Clear a part's cell override.
2316#[unsafe(no_mangle)]
2317pub unsafe extern "C" fn ss_runtime_clear_part_cell_override(context: *mut c_void, part: u32) -> bool {
2318    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2319        return false;
2320    };
2321    ffi_context.last_error = None;
2322    match ffi_context.ctx.clear_part_cell_override(part) {
2323        Ok(_) => true,
2324        Err(e) => {
2325            ffi_context.fail("ss_runtime_clear_part_cell_override", e);
2326            false
2327        }
2328    }
2329}
2330
2331/// Clear every per-part override on the context.
2332#[unsafe(no_mangle)]
2333pub unsafe extern "C" fn ss_runtime_clear_all_part_overrides(context: *mut c_void) -> bool {
2334    let Some(ffi_context) = (unsafe { get_context(context) }) else {
2335        return false;
2336    };
2337    ffi_context.last_error = None;
2338    ffi_context.ctx.clear_all_part_overrides();
2339    true
2340}
2341
2342#[cfg(all(test, feature = "std"))]
2343mod tests {
2344    use super::*;
2345    use core::ffi::c_void;
2346    use std::ffi::{CStr, CString};
2347
2348    /// The code a context is holding, and the wording that code maps to.
2349    fn read_error(ctx: *mut c_void) -> (i32, std::string::String) {
2350        let code = unsafe { ss_runtime_get_last_error(ctx) };
2351        let text = unsafe { CStr::from_ptr(ss_runtime_error_message(code)) };
2352        (code, text.to_string_lossy().into_owned())
2353    }
2354
2355    /// A valid FlatBuffer root with no parts or animations, at `version`.
2356    fn empty_ssab(version: u32) -> std::vec::Vec<u8> {
2357        use ssab::ssab::ss::format as fmt;
2358        let mut b = flatbuffers::FlatBufferBuilder::new();
2359        let name = b.create_string("empty");
2360        let parts = b.create_vector::<flatbuffers::ForwardsUOffset<fmt::PartData>>(&[]);
2361        let animations = b.create_vector::<flatbuffers::ForwardsUOffset<fmt::AnimationData>>(&[]);
2362        let keyframes = crate::eval::keyframes::create_empty_keyframes(&mut b);
2363        let root = fmt::SsAnimeBinary::create(&mut b, &fmt::SsAnimeBinaryArgs { version, name: Some(name), parts: Some(parts), animations: Some(animations), keyframes: Some(keyframes), ..Default::default() });
2364        fmt::finish_ss_anime_binary_buffer(&mut b, root);
2365        b.finished_data().to_vec()
2366    }
2367
2368    /// A pack whose `version` is not the one this runtime was built against —
2369    /// the failure a user hits by playing a pack from a different converter.
2370    fn ssab_with_wrong_version() -> std::vec::Vec<u8> {
2371        empty_ssab(ssab::SSAB_SCHEMA_VERSION + 1)
2372    }
2373
2374    /// A failure is reported on both faces: the code for the caller that checks
2375    /// the return value, and a log line for the one that does not. The line
2376    /// names the entry point, because "SSAB data is not loaded" on its own does
2377    /// not say which call said so.
2378    #[test]
2379    fn a_failure_reaches_the_log_callback_tagged_with_its_entry_point() {
2380        static LINES: std::sync::Mutex<std::vec::Vec<(i32, std::string::String)>> = std::sync::Mutex::new(std::vec::Vec::new());
2381
2382        extern "C" fn record(level: c_int, message: *const c_char) {
2383            let text = unsafe { CStr::from_ptr(message) }.to_string_lossy().into_owned();
2384            LINES.lock().unwrap().push((level, text));
2385        }
2386        ss_runtime_set_log_callback(record);
2387
2388        let ctx = ss_runtime_create();
2389        let name = CString::new("walk").unwrap();
2390        // Nothing bound, so the runtime has no animation to set up.
2391        assert!(!unsafe { ss_runtime_setup_animation(ctx, name.as_ptr()) });
2392        // The track entry points record theirs through `report`.
2393        assert!(!unsafe { ss_runtime_set_track_alpha(ctx, 0, f32::NAN) });
2394        unsafe { ss_runtime_destroy(ctx) };
2395
2396        // The callback is a process-global the ABI gives no way to clear, so
2397        // other tests' failures land in here too -- look for this one rather
2398        // than counting.
2399        let lines = LINES.lock().unwrap();
2400        for api in ["ss_runtime_setup_animation", "ss_runtime_set_track_alpha"] {
2401            let tag = std::format!("{api}: ");
2402            assert!(lines.iter().any(|(level, text)| *level == SS_RUNTIME_LOG_ERROR && text.starts_with(&tag)), "{api}'s failure never reached the log callback: {lines:?}");
2403        }
2404    }
2405
2406    /// The name a failure is logged under is written out by hand at each call,
2407    /// so a line copied from another entry point keeps that one's name.
2408    #[test]
2409    fn every_failure_is_logged_under_the_entry_point_that_failed() {
2410        let source = std::fs::read_to_string("src/ffi/mod.rs").expect("read ffi/mod.rs");
2411        let mut entry_point = None;
2412        let mut checked = 0usize;
2413        let mut wrong = std::vec::Vec::new();
2414        for (no, line) in source.lines().enumerate() {
2415            if let Some(name) = exported_c_symbols(line).into_iter().next() {
2416                entry_point = Some(name);
2417            }
2418            for marker in [".fail(\"", "report(ffi_context, \""] {
2419                for (at, _) in line.match_indices(marker) {
2420                    let named: std::string::String = line[at + marker.len()..].chars().take_while(|c| *c != '"').collect();
2421                    checked += 1;
2422                    if entry_point.as_deref() != Some(named.as_str()) {
2423                        wrong.push(std::format!("line {}: {} logs as {named}", no + 1, entry_point.as_deref().unwrap_or("no entry point")));
2424                    }
2425                }
2426            }
2427        }
2428        assert!(checked > 40, "the scan found only {checked} named failures; the scan itself is broken");
2429        assert!(wrong.is_empty(), "failures logged under another entry point's name:\n  {}", wrong.join("\n  "));
2430    }
2431
2432    /// The clear on entry is written out by hand at each entry point, so one
2433    /// without it reports an earlier call's failure after it succeeds.
2434    #[test]
2435    fn every_entry_point_that_records_a_failure_clears_the_last_one_first() {
2436        let source = std::fs::read_to_string("src/ffi/mod.rs").expect("read ffi/mod.rs");
2437        let source = source.split("\nmod tests {").next().expect("the code before the tests");
2438        let (mut entry_point, mut cleared, mut awaiting_clear) = (None, false, false);
2439        let mut checked = 0usize;
2440        let mut wrong = std::collections::BTreeSet::new();
2441        for line in source.lines() {
2442            if let Some(name) = exported_c_symbols(line).into_iter().next() {
2443                (entry_point, cleared, awaiting_clear) = (Some(name), false, false);
2444                continue;
2445            }
2446            let code = line.trim();
2447            if awaiting_clear {
2448                // Only the `else` of a `let`-`else` may come between the lookup and the clear.
2449                if code == "ffi_context.last_error = None;" {
2450                    (cleared, awaiting_clear) = (true, false);
2451                } else if !(code.starts_with("return ") || code == "};") {
2452                    awaiting_clear = false;
2453                }
2454            } else if !cleared && code.contains("get_context(") {
2455                awaiting_clear = true;
2456            }
2457            if [".fail(\"", "report(ffi_context, \""].iter().any(|marker| line.contains(marker)) {
2458                checked += 1;
2459                if !cleared {
2460                    wrong.insert(entry_point.clone().unwrap_or_default());
2461                }
2462            }
2463        }
2464        assert!(checked > 40, "the scan found only {checked} recorded failures; the scan itself is broken");
2465        assert!(wrong.is_empty(), "entry points that record a failure without clearing the last one on entry:\n  {}", wrong.into_iter().collect::<std::vec::Vec<_>>().join("\n  "));
2466    }
2467
2468    #[test]
2469    fn a_fresh_context_reports_no_error() {
2470        let ctx = ss_runtime_create();
2471        assert_eq!(read_error(ctx), (0, std::string::String::new()));
2472        unsafe { ss_runtime_destroy(ctx) };
2473    }
2474
2475    #[test]
2476    fn a_failure_reports_a_code_and_the_matching_text() {
2477        let ctx = ss_runtime_create();
2478        let name = CString::new("walk").unwrap();
2479        // Nothing bound, so the runtime has no animation to set up.
2480        assert!(!unsafe { ss_runtime_setup_animation(ctx, name.as_ptr()) });
2481        let (code, text) = read_error(ctx);
2482        assert_eq!(code, crate::error::SSRuntimeError::NotLoaded.as_code());
2483        assert_eq!(text, "SSAB data is not loaded");
2484        unsafe { ss_runtime_destroy(ctx) };
2485    }
2486
2487    #[test]
2488    fn the_reason_is_always_the_most_recent_one() {
2489        let ctx = ss_runtime_create();
2490        let name = CString::new("walk").unwrap();
2491        assert!(!unsafe { ss_runtime_setup_animation(ctx, name.as_ptr()) });
2492        assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, crate::error::SSRuntimeError::NotLoaded.as_code());
2493
2494        // A different failure replaces it rather than being masked by it.
2495        assert!(!unsafe { ss_runtime_load_ssab_borrow(ctx, core::ptr::null(), 0) });
2496        assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, crate::error::SSRuntimeError::InvalidParameter.as_code());
2497
2498        // And `ss_runtime_reset` clears it.
2499        let ssab = ssab_with_wrong_version();
2500        let _ = unsafe { ss_runtime_load_ssab_borrow(ctx, ssab.as_ptr(), ssab.len()) };
2501        unsafe { ss_runtime_reset(ctx) };
2502        assert_eq!(read_error(ctx), (0, std::string::String::new()));
2503        unsafe { ss_runtime_destroy(ctx) };
2504    }
2505
2506    /// The pack getters can fail too, so a success clears what an earlier call
2507    /// left behind.
2508    #[test]
2509    fn a_successful_pack_read_clears_an_earlier_failure() {
2510        let ctx = ss_runtime_create();
2511        let ssab = empty_ssab(ssab::SSAB_SCHEMA_VERSION);
2512        assert!(unsafe { ss_runtime_load_ssab_copy(ctx, ssab.as_ptr(), ssab.len()) });
2513        let name = CString::new("walk").unwrap();
2514        let reads: [(&str, &dyn Fn()); 3] = [
2515            ("ss_runtime_get_ssab", &|| {
2516                let (mut data, mut len) = (core::ptr::null(), 0);
2517                unsafe { ss_runtime_get_ssab(ctx, &mut data, &mut len) };
2518                assert_eq!(len, ssab.len());
2519            }),
2520            ("ss_runtime_get_ssab_buf", &|| assert!(!unsafe { ss_runtime_get_ssab_buf(ctx) }.is_null())),
2521            ("ss_runtime_get_ssab_len", &|| assert_eq!(unsafe { ss_runtime_get_ssab_len(ctx) }, ssab.len())),
2522        ];
2523        for (api, read) in reads {
2524            assert!(!unsafe { ss_runtime_setup_animation(ctx, name.as_ptr()) });
2525            assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, crate::error::SSRuntimeError::AnimationNotFound.as_code());
2526            read();
2527            assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, 0, "{api}");
2528        }
2529        unsafe { ss_runtime_destroy(ctx) };
2530    }
2531
2532    /// The two calls that hand out a buffer say when there is none, and leave
2533    /// the out parameters as the caller set them.
2534    #[test]
2535    fn the_buffer_getters_report_failure_and_leave_their_out_parameters_alone() {
2536        let not_loaded = crate::error::SSRuntimeError::NotLoaded.as_code();
2537        let ctx = ss_runtime_create();
2538        let (mut data, mut len): (*const c_uchar, usize) = (core::ptr::null(), 7);
2539        assert!(!unsafe { ss_runtime_get_ssab(ctx, &mut data, &mut len) });
2540        assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, not_loaded);
2541        assert!(!unsafe { ss_runtime_get_frame_data(ctx, 0.0, &mut data, &mut len) });
2542        assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, not_loaded);
2543        assert!(data.is_null());
2544        assert_eq!(len, 7);
2545        unsafe { ss_runtime_destroy(ctx) };
2546        assert!(!unsafe { ss_runtime_get_frame_data(core::ptr::null_mut(), 0.0, &mut data, &mut len) });
2547    }
2548
2549    /// A pack from another converter is a version mismatch, which is what the user
2550    /// can act on. The numbers come from `ss_runtime_ssab_schema_version`.
2551    #[test]
2552    fn a_version_mismatch_is_not_reported_as_a_memory_error() {
2553        let ctx = ss_runtime_create();
2554        let ssab = ssab_with_wrong_version();
2555        assert!(!unsafe { ss_runtime_load_ssab_borrow(ctx, ssab.as_ptr(), ssab.len()) });
2556
2557        let (code, text) = read_error(ctx);
2558        assert_eq!(code, crate::error::SSRuntimeError::InvalidVersion { expected: 0, got: 0 }.as_code());
2559        assert_eq!(text, "Invalid SSAB version");
2560        unsafe { ss_runtime_destroy(ctx) };
2561    }
2562
2563    /// The porting guide may only name C entry points that exist: a reader cannot
2564    /// tell a documented-but-absent API from one they merely cannot find, so the
2565    /// guide is checked against the exports.
2566    #[test]
2567    fn the_guide_only_names_entry_points_that_exist() {
2568        // Names the guide is allowed to mention without exporting them.
2569        const ALLOWED: &[(&str, &str)] = &[];
2570
2571        // Both C ABIs the guide covers: the runtime's, and the converter's —
2572        // the editor-integration page documents `ss_converter_*`, and a check
2573        // that only knew about this crate would call every one of them a ghost.
2574        let mut exported = exported_c_symbols(&std::fs::read_to_string("src/ffi/mod.rs").expect("read ffi/mod.rs"));
2575        exported.extend(exported_c_symbols(&std::fs::read_to_string("../ssconverter/src/ffi/mod.rs").expect("read ssconverter's ffi/mod.rs")));
2576        assert!(exported.len() > 100, "the export scan found only {} symbols; the scan itself is broken", exported.len());
2577        let families: std::collections::BTreeSet<&str> = exported.iter().map(|s| family_of(s)).collect();
2578
2579        let mut ghosts = std::vec::Vec::new();
2580        let mut pages = 0usize;
2581        for entry in walk_markdown(std::path::Path::new("docs")) {
2582            pages += 1;
2583            let text = std::fs::read_to_string(&entry).expect("read a guide page");
2584            for name in backticked_ss_names(&text) {
2585                // Only names in a family this ABI actually exports. Derived from
2586                // the exports rather than listed, so a new family is covered the
2587                // day it lands — and so that `ss_partcolor_blend` (a GLSL helper
2588                // in a shader example) is read as what it is rather than as a
2589                // missing entry point.
2590                if !families.contains(family_of(&name)) || exported.contains(&name) || ALLOWED.iter().any(|(p, _)| name.starts_with(p)) {
2591                    continue;
2592                }
2593                ghosts.push(std::format!("{}: `{}`", entry.display(), name));
2594            }
2595        }
2596        assert!(pages > 20, "the page walk found only {pages} pages; the walk itself is broken");
2597        ghosts.sort();
2598        ghosts.dedup();
2599        assert!(ghosts.is_empty(), "the guide names C entry points that are not exported:\n  {}", ghosts.join("\n  "));
2600    }
2601
2602    /// The first two segments of a C entry point's name — `ss_runtime_play` is
2603    /// in the `ss_runtime` family. What tells one of this ABI's names apart from
2604    /// any other identifier that happens to start with `ss_`.
2605    fn family_of(name: &str) -> &str {
2606        match name.match_indices('_').nth(1) {
2607            Some((i, _)) => &name[..i],
2608            None => name,
2609        }
2610    }
2611
2612    /// The wasm face reports through `js_error`, never by formatting an error
2613    /// itself: `Debug` prints the Rust variant name, an identifier from a language
2614    /// a JS caller is not writing, which then reaches their user through whatever
2615    /// the Player shows.
2616    #[test]
2617    fn the_wasm_face_does_not_debug_format_an_error() {
2618        let web = std::fs::read_to_string("src/web/mod.rs").expect("read web/mod.rs");
2619        assert!(web.contains("fn js_error("), "js_error is gone; this test is pinning nothing");
2620        assert!(!web.contains("{:?}"), "src/web/mod.rs formats something with Debug. A fallible binding reports through `js_error`.");
2621    }
2622
2623    /// A JS exception is an `Error`, so that whoever catches it finds `message` and a
2624    /// stack. Nothing on this face has another use for a plain string.
2625    #[test]
2626    fn the_wasm_face_throws_errors_not_strings() {
2627        let web = std::fs::read_to_string("src/web/mod.rs").expect("read web/mod.rs");
2628        assert!(web.contains("JsError::new"), "js_message is gone; this test is pinning nothing");
2629        assert!(!web.contains("JsValue::from_str"), "src/web/mod.rs builds a plain string. A fallible binding reports through `js_error` or `js_message`.");
2630    }
2631
2632    /// The `ss_*` symbols this module actually exports, read from its own source
2633    /// rather than from the generated header — the header is a build artifact,
2634    /// and a test that needs one built first is a test that gets skipped.
2635    fn exported_c_symbols(source: &str) -> std::collections::BTreeSet<std::string::String> {
2636        let mut out = std::collections::BTreeSet::new();
2637        for line in source.lines() {
2638            let line = line.trim_start();
2639            let Some(rest) = line.strip_prefix("pub ") else { continue };
2640            let rest = rest.strip_prefix("unsafe ").unwrap_or(rest);
2641            let Some(rest) = rest.strip_prefix("extern \"C\" fn ") else { continue };
2642            let name: std::string::String = rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
2643            if name.starts_with("ss_") {
2644                out.insert(name);
2645            }
2646        }
2647        out
2648    }
2649
2650    /// Every `ss_…`-looking identifier written in backticks. Backticks are the
2651    /// filter that matters: prose says "the `ss_resource_create_*` pair", and a
2652    /// trailing `*` or `_` is a wildcard rather than a name, so those are
2653    /// dropped instead of being reported as missing.
2654    fn backticked_ss_names(text: &str) -> std::vec::Vec<std::string::String> {
2655        let mut out = std::vec::Vec::new();
2656        for span in text.split('`').skip(1).step_by(2) {
2657            let span = span.trim();
2658            if !span.starts_with("ss_") {
2659                continue;
2660            }
2661            let name: std::string::String = span.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
2662            // A wildcard stem, not a symbol.
2663            if span.len() > name.len() && span.as_bytes()[name.len()] == b'*' {
2664                continue;
2665            }
2666            if name.ends_with('_') {
2667                continue;
2668            }
2669            out.push(name);
2670        }
2671        out
2672    }
2673
2674    fn walk_markdown(dir: &std::path::Path) -> std::vec::Vec<std::path::PathBuf> {
2675        let mut out = std::vec::Vec::new();
2676        let Ok(entries) = std::fs::read_dir(dir) else { return out };
2677        for entry in entries.flatten() {
2678            let path = entry.path();
2679            if path.is_dir() {
2680                out.extend(walk_markdown(&path));
2681            } else if path.extension().is_some_and(|e| e == "md") {
2682                out.push(path);
2683            }
2684        }
2685        out
2686    }
2687
2688    #[test]
2689    fn a_null_context_answers_without_dereferencing_it() {
2690        let null = core::ptr::null_mut();
2691        assert_eq!(unsafe { ss_runtime_get_last_error(null) }, 0);
2692        // 0 is "no error", and the message for it is empty rather than null, so
2693        // a caller can log the result without checking either.
2694        let msg = ss_runtime_error_message(0);
2695        assert!(!msg.is_null());
2696        assert_eq!(unsafe { CStr::from_ptr(msg) }.to_bytes(), b"");
2697    }
2698
2699    /// The `match code` in `ss_runtime_error_message` and the `match self` in
2700    /// `SSRuntimeError::as_str` are two tables for one mapping, so pin them to
2701    /// each other.
2702    #[test]
2703    fn error_message_matches_every_variant() {
2704        use crate::error::SSRuntimeError::*;
2705        let every_variant = [EmptyData, InvalidVersion { expected: 1, got: 2 }, AnimationNotFound, NotLoaded, InvalidParameter, MemoryError, MalformedEffect, Unknown];
2706        for e in every_variant {
2707            let via_abi = unsafe { CStr::from_ptr(ss_runtime_error_message(e.as_code())) };
2708            assert_eq!(via_abi.to_str().unwrap(), e.as_str(), "code {} disagrees with the variant", e.as_code());
2709            assert!(!e.as_str().is_empty(), "{:?} has no wording", e);
2710        }
2711        // An unknown code is not a panic and not a null.
2712        assert_eq!(unsafe { CStr::from_ptr(ss_runtime_error_message(12345)) }.to_bytes(), b"");
2713    }
2714
2715    /// The runtime says which `.ssab` version it reads, so a Player can report a
2716    /// mismatch in numbers instead of parsing them out of a sentence.
2717    #[test]
2718    fn the_runtime_publishes_the_schema_version_it_expects() {
2719        let expected = ss_runtime_ssab_schema_version();
2720        assert_ne!(expected, 0);
2721        // The pack built one version off is exactly what `InvalidVersion` is for.
2722        let ctx = ss_runtime_create();
2723        let ssab = ssab_with_wrong_version();
2724        assert!(!unsafe { ss_runtime_load_ssab_borrow(ctx, ssab.as_ptr(), ssab.len()) });
2725        assert_eq!(unsafe { ss_runtime_get_last_error(ctx) }, crate::error::SSRuntimeError::InvalidVersion { expected: 0, got: 0 }.as_code());
2726        unsafe { ss_runtime_destroy(ctx) };
2727    }
2728}