Skip to main content

ssplayer_wgpu/
ffi.rs

1//! The "ffi" face: the C ABI over the Rust API, for C/C++
2//! hosts on DX12 / Vulkan / Metal.
3//!
4//! **This module is a translation layer and nothing else.** Every entry point
5//! does the same three things: validate the C arguments, convert them to Rust
6//! types, and call [`NativeHost`] (the wgpu host) or [`SSPlayer`]
7//! (playback). No rendering or playback logic lives here — when something needs
8//! doing it belongs in `host.rs` or `player.rs`, where the Rust API gets it too.
9//!
10//! Raw window handles cannot cross the ABI as Rust traits, so the
11//! caller fills in a flat [`SsWindowHandle`] (HWND / NSView / CAMetalLayer /
12//! Xlib / Wayland) which `surface_target` turns into what wgpu wants.
13//!
14//! **Two handles, not one.** `ss_scene_t` is the window — surface, device,
15//! renderer, scene — and `ss_player_t` is one character drawn into it. Fusing
16//! them would make a second character in one window need a second surface, and
17//! the two would clear and present over each other.
18//!
19//! Conventions:
20//! * Status is `int32_t`: `SS_OK` (0), positive = an `ssruntime` error code
21//!   (same numbering as the SDK's C-API), negative = a player/host error.
22//!   [`ss_last_error`] carries the human-readable detail.
23//! * No entry point unwinds: the workspace builds with `panic = "abort"`.
24//! * Nothing here retains the window; the caller must keep it (and its layer)
25//!   alive until [`ss_scene_destroy`].
26
27use crate::events::{SignalValue, SsEvent};
28use crate::fit::{Align, Fit, Placement, Rect};
29use crate::host::{NativeHost, NativeHostConfig, PlayerId};
30use crate::player::{BlendOp, CrowdMember, MissingKind, OverridePriority, PlaybackDirection, PlaybackStyle, SSPlayer};
31use std::cell::RefCell;
32use std::ffi::{CStr, CString, c_char, c_void};
33use std::num::NonZeroIsize;
34use std::ptr::NonNull;
35use wgpu::rwh;
36
37// --- status codes ---------------------------------------------------------
38
39/// Success.
40pub const SS_OK: i32 = 0;
41/// A pointer argument was null, a string was not UTF-8, or a value was out of range.
42pub const SS_ERROR_INVALID_ARGUMENT: i32 = -1;
43/// wgpu could not provide what was asked for (no adapter/device, surface creation
44/// or presentation failed).
45pub const SS_ERROR_GPU: i32 = -2;
46
47// --- window handle kinds --------------------------------------------------
48
49/// Win32 `HWND` (+ optional `HINSTANCE` in `display`).
50pub const SS_WINDOW_WIN32: u32 = 0;
51/// macOS `NSView*`. wgpu attaches (or reuses) the view's `CAMetalLayer`; must be
52/// passed from the main thread.
53pub const SS_WINDOW_APPKIT: u32 = 1;
54/// macOS `CAMetalLayer*` directly. Apple targets only.
55pub const SS_WINDOW_METAL_LAYER: u32 = 2;
56/// X11 `Window` XID in `window`, `Display*` in `display`, screen in `screen`.
57pub const SS_WINDOW_XLIB: u32 = 3;
58/// Wayland `wl_surface*` in `window`, `wl_display*` in `display`.
59pub const SS_WINDOW_WAYLAND: u32 = 4;
60
61// --- backends -------------------------------------------------------------
62
63/// Let wgpu pick the platform's primary backend.
64pub const SS_BACKEND_AUTO: u32 = 0;
65/// Force Direct3D 12 (Windows).
66pub const SS_BACKEND_DX12: u32 = 1;
67/// Force Metal (macOS / iOS).
68pub const SS_BACKEND_METAL: u32 = 2;
69/// Force Vulkan (Linux / Windows / Android).
70pub const SS_BACKEND_VULKAN: u32 = 3;
71
72// --- C structs ------------------------------------------------------------
73
74/// A platform window, flattened for the ABI. Which fields are read depends on
75/// `kind` (`SS_WINDOW_*`); unused ones must be null/zero.
76#[repr(C)]
77#[derive(Clone, Copy)]
78pub struct SsWindowHandle {
79    /// One of the `SS_WINDOW_*` constants.
80    pub kind: u32,
81    /// X11 screen number. Ignored unless `kind` is `SS_WINDOW_XLIB`.
82    pub screen: i32,
83    /// Win32: `HWND`. AppKit: `NSView*`. Metal: `CAMetalLayer*`.
84    /// Xlib: the `Window` XID cast to a pointer. Wayland: `wl_surface*`.
85    pub window: *mut c_void,
86    /// Win32: `HINSTANCE` (may be null). Xlib: `Display*`. Wayland: `wl_display*`.
87    /// Unused otherwise.
88    pub display: *mut c_void,
89}
90
91/// Everything `ss_scene_create` needs: where to draw, how big, and how to clear.
92#[repr(C)]
93#[derive(Clone, Copy)]
94pub struct SsSceneDesc {
95    /// Target window/layer.
96    pub window: SsWindowHandle,
97    /// One of the `SS_BACKEND_*` constants; any other value makes
98    /// `ss_scene_create` fail.
99    pub backend: u32,
100    /// Drawable size in **pixels** (not points — scale by the display factor).
101    /// A size past the device's `max_texture_dimension_2d` draws at that limit.
102    pub width: u32,
103    /// See `width`.
104    pub height: u32,
105    /// Clear colour, straight RGBA in 0..1. The window stays opaque whatever the
106    /// alpha.
107    pub clear_color: [f32; 4],
108    /// Allocate a depth/stencil buffer so mask parts rasterise. With
109    /// `false` the scene runs without masking, exactly as if the host attached
110    /// no stencil.
111    pub enable_mask: bool,
112    /// Whether the render target is Y-down. A window's swapchain is not: pass
113    /// `false`, and `true` draws upside down. Player coordinates
114    /// (`ss_player_set_transform`) run downward either way.
115    pub y_down: bool,
116}
117
118/// What the last frame cost, flattened for the ABI.
119///
120/// `gpu_pass_time_ns` is 0 when the adapter has no timestamp query, or before
121/// the first measurement has come back — it is read without stalling the
122/// pipeline, so it lags a frame or two.
123#[repr(C)]
124#[derive(Clone, Copy, Default)]
125pub struct SsSceneStats {
126    /// Players that contributed geometry this frame.
127    pub players: u32,
128    /// Primitives in the frame: parts, shape fans and effect particles.
129    pub prims: u32,
130    /// Draw calls recorded. The gap from `prims` is draw-call merging headroom.
131    pub draw_calls: u32,
132    /// Players faded as one layer this frame (`ss_scene_set_group_alpha`), each
133    /// a render pass and a window-sized layer of its own.
134    pub group_layers: u32,
135    /// Bytes written to the frame's storage buffers.
136    pub uploaded_bytes: u64,
137    /// GPU time for the last timed render pass, in nanoseconds. 0 = no reading.
138    pub gpu_pass_time_ns: u64,
139}
140
141/// One copy of a player in a crowd: where it stands, in `ss_player_set_transform`
142/// terms and composed under that, and its alpha (0..1) and tint (`0xRRGGBB`),
143/// each multiplied into the player's own. `{0, 0, 1, 1, 0, 1, 0xFFFFFF}` stands
144/// where the player does, unchanged.
145#[repr(C)]
146#[derive(Clone, Copy)]
147pub struct SsCrowdMember {
148    pub x: f32,
149    /// Measured downward, as `ss_player_set_transform`'s is.
150    pub y: f32,
151    pub scale_x: f32,
152    pub scale_y: f32,
153    /// Radians.
154    pub rotation: f32,
155    pub alpha: f32,
156    pub tint: u32,
157}
158
159/// The most members `ss_player_set_crowd` takes.
160pub const SS_MAX_CROWD_MEMBERS: u32 = 4096;
161const _: () = assert!(SS_MAX_CROWD_MEMBERS as usize == crate::MAX_CROWD_MEMBERS);
162
163/// One atlas a pack asks for, flattened for the ABI. What
164/// `ss_player_texture_at` fills in.
165#[repr(C)]
166#[derive(Clone, Copy)]
167pub struct SsTextureRef {
168    /// The key `ss_scene_add_texture` / `ss_scene_add_texture_png` expects for
169    /// this image.
170    ///
171    /// An identity for the **image**, not for the cellmap that names it: some
172    /// tools name the atlas `spritemap1.png` in every project they export, so two packs
173    /// name their atlas alike, and a key made from the cellmap's hash alone would
174    /// let the second draw the first one's atlas. Two packs that really do share a
175    /// file still share this, and so still share one upload.
176    pub key: u32,
177    /// `true` when the image rides inside the `.ssab` (embedded mode): the pack
178    /// supplies it on the next `ss_scene_update` and the host loads nothing.
179    pub embedded: bool,
180    /// The image path the exporter wrote, **relative to the `.ssab`'s own
181    /// directory** — join it with the directory the file was read from.
182    ///
183    /// Owned by the scene and valid until the next `ss_player_texture_at` on it;
184    /// copy it if you need to keep it. Never null.
185    pub path: *const c_char,
186}
187
188/// Something a load needed and did not get, flattened for the ABI.
189/// What `ss_player_missing_at` fills in.
190#[repr(C)]
191#[derive(Clone, Copy)]
192pub struct SsMissingAsset {
193    /// `SS_MISSING_TEXTURE` or `SS_MISSING_PACK`.
194    pub kind: u32,
195    /// For a texture, the slot a draw batch will ask for — an id inside the
196    /// pack, not the key `ss_scene_add_texture` takes. Zero for a pack, whose
197    /// identity is its name. Match a missing atlas by `name`; this is for logs.
198    pub slot: u32,
199    /// The path asked for, or the pack's name.
200    ///
201    /// For a texture this is the path the exporter wrote, **relative to its
202    /// pack's directory** — the walk hands the loader bare names and never
203    /// builds a full path, so no full path exists to report. Join it
204    /// onto the directory of what you passed `ss_player_load` if you want one.
205    ///
206    /// Owned by the scene and valid until the next `ss_player_missing_at` on it;
207    /// copy it if you need to keep it. Never null.
208    pub name: *const c_char,
209}
210
211/// What kind of thing an `ss_event_data_t` is; read it before the payload.
212pub const SS_EVENT_USER_DATA: u32 = 0;
213/// See `SS_EVENT_USER_DATA`.
214pub const SS_EVENT_SIGNAL: u32 = 1;
215/// See `SS_EVENT_USER_DATA`.
216pub const SS_EVENT_AUDIO: u32 = 2;
217
218/// One timeline event, flattened for the ABI.
219///
220/// The three kinds share one struct rather than a real union, because a union
221/// across the ABI costs the caller a cast for no gain at this size. `kind` says
222/// which fields carry anything; the rest are zeroed.
223///
224/// `text` is owned by the scene and valid until the next `ss_player_event_at`
225/// on it — copy it if you need to keep it. Never null.
226#[repr(C)]
227#[derive(Clone, Copy)]
228pub struct SsEventData {
229    /// One of the `SS_EVENT_*` constants.
230    pub kind: u32,
231    /// Which part raised it.
232    pub part_index: u32,
233    /// The frame the key is **authored** on, which is not necessarily the frame
234    /// the tick landed on: one update can step across several frames and reports
235    /// every key in between, so this is the only way to tell them apart.
236    pub frame_no: u32,
237    /// The source on the track stack that fired it, as `ss_player_track_main_source`
238    /// and `ss_player_add_track_source` name it. By default only track 0's main
239    /// source fires; this tells events apart once another source has opted in
240    /// with `ss_player_set_source_event_threshold`.
241    pub source: u32,
242
243    /// UserData: whether the animator filled each optional field in. Unset is
244    /// not the same as zero, which is what these distinguish.
245    pub has_integer: bool,
246    pub has_rect: bool,
247    pub has_point: bool,
248    pub has_text: bool,
249    /// UserData, when `has_integer`.
250    pub integer: i32,
251    /// UserData, when `has_rect`: `[left, top, right, bottom]` — four edges, not origin+size.
252    pub rect: [f32; 4],
253    /// UserData, when `has_point`.
254    pub point: [f32; 2],
255
256    /// UserData's `str` (when `has_text`), Signal's `command_id`, or Audio's
257    /// `sound_name`. Empty for the kinds that have none.
258    pub text: *const c_char,
259
260    /// Signal: how many parameters `ss_player_event_signal_param_at` will serve.
261    pub param_count: u32,
262
263    /// Audio: addresses the `SoundList` and the `SoundFile` within it.
264    pub sound_list_name_hash: u32,
265    pub sound_name_hash: u32,
266    /// Audio: how many times to play. A count, never zero — SpriteStudio has no
267    /// infinite audio loop.
268    pub loop_num: i32,
269}
270
271/// Which field of an `ss_signal_param_data_t` carries the value.
272pub const SS_SIGNAL_VALUE_NONE: u32 = 0;
273/// See `SS_SIGNAL_VALUE_NONE`.
274pub const SS_SIGNAL_VALUE_BOOL: u32 = 1;
275/// A choice from a list, as its index. See `SS_SIGNAL_VALUE_NONE`.
276pub const SS_SIGNAL_VALUE_INDEX: u32 = 2;
277/// See `SS_SIGNAL_VALUE_NONE`.
278pub const SS_SIGNAL_VALUE_INTEGER: u32 = 3;
279/// See `SS_SIGNAL_VALUE_NONE`.
280pub const SS_SIGNAL_VALUE_FLOATING: u32 = 4;
281/// See `SS_SIGNAL_VALUE_NONE`.
282pub const SS_SIGNAL_VALUE_TEXT: u32 = 5;
283
284/// One signal parameter, flattened for the ABI. `value_type` says which field
285/// to read; `SS_SIGNAL_VALUE_NONE` means the parameter exists but was left
286/// unset.
287///
288/// `id` and `text` are owned by the scene and valid until the next
289/// `ss_player_event_signal_param_at` on it. Never null.
290#[repr(C)]
291#[derive(Clone, Copy)]
292pub struct SsSignalParamData {
293    pub id: *const c_char,
294    /// One of the `SS_SIGNAL_VALUE_*` constants.
295    pub value_type: u32,
296    /// When `value_type` is `BOOL`.
297    pub bool_value: bool,
298    /// When `value_type` is `INDEX` or `INTEGER`.
299    pub int_value: i32,
300    /// When `value_type` is `FLOATING`.
301    pub float_value: f32,
302    /// When `value_type` is `TEXT`.
303    pub text: *const c_char,
304}
305
306/// An atlas that did not load. The parts using it draw against the white
307/// fallback, so they appear as silhouettes.
308pub const SS_MISSING_TEXTURE: u32 = 0;
309/// An animation pack that did not load. The instance parts playing it do not appear.
310pub const SS_MISSING_PACK: u32 = 1;
311
312/// Scale the content box until it fits entirely inside the view.
313pub const SS_FIT_CONTAIN: u32 = 0;
314/// Scale until the content box covers the view. The spill is not clipped — the
315/// player has no scissor of its own.
316pub const SS_FIT_COVER: u32 = 1;
317/// No fit: scale 1, centred, and `scale` / `offset_x` / `offset_y` are the whole
318/// placement.
319pub const SS_FIT_NONE: u32 = 2;
320
321/// Which point of the content box lands on the matching point of the view. On
322/// the vertical axis, "top" is the top of the **screen**.
323pub const SS_ALIGN_CENTER: u32 = 0;
324pub const SS_ALIGN_TOP: u32 = 1;
325pub const SS_ALIGN_BOTTOM: u32 = 2;
326pub const SS_ALIGN_LEFT: u32 = 3;
327pub const SS_ALIGN_RIGHT: u32 = 4;
328pub const SS_ALIGN_TOP_LEFT: u32 = 5;
329pub const SS_ALIGN_TOP_RIGHT: u32 = 6;
330pub const SS_ALIGN_BOTTOM_LEFT: u32 = 7;
331pub const SS_ALIGN_BOTTOM_RIGHT: u32 = 8;
332
333/// A box in player-local units — the space `ss_player_part_transform` reports
334/// in, with `y` downward.
335#[repr(C)]
336#[derive(Clone, Copy, Default)]
337pub struct SsRect {
338    pub x: f32,
339    /// Low edge on y, which is the **top** edge on screen.
340    pub y: f32,
341    pub width: f32,
342    pub height: f32,
343}
344
345/// Everything `ss_player_fit_into` needs.
346///
347/// **Zero-initialising this is not the default placement** — it would ask for
348/// scale 0, which draws nothing. Call `ss_placement_default` first and change
349/// what you mean to change.
350#[repr(C)]
351#[derive(Clone, Copy)]
352pub struct SsPlacement {
353    /// One of the `SS_FIT_*` constants.
354    pub fit: u32,
355    /// One of the `SS_ALIGN_*` constants.
356    pub align: u32,
357    /// The box to fit. Read only when `has_frame` is true; otherwise the
358    /// animation's authored canvas is used (`ss_player_canvas_rect`).
359    pub frame: SsRect,
360    pub has_frame: bool,
361    /// Pixels from the aligned position, applied **after** the fit.
362    pub offset_x: f32,
363    /// See `offset_x`.
364    pub offset_y: f32,
365    /// A multiplier **on top of** the fit's scale, not a replacement for it.
366    pub scale: f32,
367    /// Mirror horizontally. The alignment follows the flip.
368    pub flip_x: bool,
369    /// Mirror vertically.
370    pub flip_y: bool,
371    /// Passed through to the placement untouched; rotation has no part in the
372    /// fit itself.
373    pub rotation: f32,
374}
375
376/// What `ss_player_fit_into` wrote, in `ss_player_set_transform` terms: pixels
377/// from the **view centre**, `y` downward.
378#[repr(C)]
379#[derive(Clone, Copy, Default)]
380pub struct SsPlaced {
381    pub x: f32,
382    pub y: f32,
383    pub scale_x: f32,
384    pub scale_y: f32,
385}
386
387/// Opaque scene handle: one window's [`NativeHost`], the player handles it has
388/// issued, and the buffers backing the strings its players hand back to C.
389pub struct SsScene {
390    host: NativeHost,
391    /// Every handle this scene created, alive until the scene is destroyed.
392    ///
393    /// `ss_player_destroy` deliberately does **not** free the box: a handle that
394    /// outlives its player then resolves to "no such player" instead of reading
395    /// freed memory, so a double destroy — the easy mistake — is a safe no-op.
396    handles: Vec<*mut SsPlayer>,
397    name_scratch: CString,
398    /// Backs `ss_player_cellmap_texture_name`, apart from `name_scratch` so a
399    /// caller holding an animation name can walk the replaceable names.
400    texture_name_scratch: CString,
401    /// Backs `ss_player_texture_at`'s `path`. Separate from `name_scratch` so the
402    /// two "valid until the next call" contracts do not invalidate each other:
403    /// walking a pack's textures and its animation names interleaved is normal.
404    path_scratch: CString,
405    /// Backs `ss_player_missing_at`'s `name`, for the same reason `path_scratch`
406    /// is separate: a caller walking the missing list while reading texture paths
407    /// must not have one invalidate the other.
408    missing_scratch: CString,
409    /// Backs `ss_player_event_at`'s `text`, and the two below back
410    /// `ss_player_event_signal_param_at`. Three separate slots for the same
411    /// reason the ones above are separate: reading an event's payload must not
412    /// invalidate the parameter a caller is part-way through walking.
413    ///
414    /// [`CScratch`] rather than `CString`, unlike the three above: these three
415    /// are on the frame path — a host drains the event list every tick — and the
416    /// ones above are walked once, after a load.
417    event_text_scratch: CScratch,
418    param_id_scratch: CScratch,
419    param_text_scratch: CScratch,
420    /// Back `ss_player_current_animation`, `ss_player_part_name`,
421    /// `ss_player_cellmap_name` and `ss_player_cell_name`, one each: a caller
422    /// hands a cellmap name straight back to `ss_player_cell_name` while walking
423    /// its cells, and a shared buffer would free that argument under it.
424    current_scratch: CString,
425    part_name_scratch: CString,
426    cellmap_name_scratch: CString,
427    cell_name_scratch: CString,
428}
429
430/// A NUL-terminated string handed back to C, refilled in place.
431///
432/// `CString` cannot be refilled: assigning a new one frees the old buffer and
433/// allocates another, which is an allocation per call on a path called once per
434/// event per frame. The bytes live in a `Vec` that keeps its capacity instead,
435/// so a steady stream of events reuses one buffer.
436#[derive(Default)]
437struct CScratch(Vec<u8>);
438
439impl CScratch {
440    /// Refill with `s`, and return a pointer good until the next call on this
441    /// slot — the same contract the `CString` fields carry.
442    ///
443    /// A string with an interior NUL comes back empty: C cannot be handed the
444    /// tail past a NUL, and quietly delivering only the head would be a different
445    /// string wearing the right name.
446    fn set(&mut self, s: &str) -> *const c_char {
447        self.0.clear();
448        if !s.as_bytes().contains(&0) {
449            self.0.extend_from_slice(s.as_bytes());
450        }
451        self.0.push(0);
452        self.0.as_ptr().cast()
453    }
454}
455
456/// Opaque player handle: which scene, and which player within it.
457///
458/// Not a pointer into the scene's player list. That list moves as it grows, and
459/// slots are reused, so the id carries a generation and every call re-resolves it.
460pub struct SsPlayer {
461    scene: *mut SsScene,
462    id: PlayerId,
463}
464
465// --- last error -----------------------------------------------------------
466
467thread_local! {
468    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::default());
469}
470
471fn set_last_error(msg: impl Into<Vec<u8>>) {
472    let msg = CString::new(msg).unwrap_or_default();
473    LAST_ERROR.with(|slot| *slot.borrow_mut() = msg);
474}
475
476fn fail(code: i32, msg: impl Into<Vec<u8>>) -> i32 {
477    set_last_error(msg);
478    code
479}
480
481/// The message for the most recent failure **on this thread**.
482///
483/// The returned string is owned by the library and stays valid until the next
484/// failing call on the same thread. Never null; empty when nothing has failed.
485///
486/// # Safety
487/// The caller must not free the pointer or use it past the next library call.
488#[unsafe(no_mangle)]
489pub unsafe extern "C" fn ss_last_error() -> *const c_char {
490    LAST_ERROR.with(|slot| slot.borrow().as_ptr())
491}
492
493/// This library's version.
494///
495/// The string is static and owned by the library. Never null.
496#[unsafe(no_mangle)]
497pub extern "C" fn ss_version() -> *const c_char {
498    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr().cast()
499}
500
501/// The SpriteStudio-SDK version whose runtime this library links, written as
502/// its release tag (`v7.0.0`), or `local` from a plain `cargo build`. The
503/// release zips carry the same string in `lib/VERSION`.
504///
505/// The string is static and owned by the library. Never null.
506#[unsafe(no_mangle)]
507pub extern "C" fn ss_sdk_version() -> *const c_char {
508    concat!(env!("SSPLAYER_SDK_VERSION"), "\0").as_ptr().cast()
509}
510
511// --- argument conversion --------------------------------------------------
512
513/// Borrow the scene behind a caller-supplied player handle.
514///
515/// # Safety
516/// `handle` must be null or a handle from `ss_scene_create_player` whose scene
517/// is still alive.
518unsafe fn scene_of<'a>(handle: *mut SsPlayer) -> Option<(&'a mut SsScene, PlayerId)> {
519    let handle = unsafe { handle.as_mut() }?;
520    let scene = unsafe { handle.scene.as_mut() }?;
521    Some((scene, handle.id))
522}
523
524/// Borrow the player behind a caller-supplied handle, or `None` if it has been
525/// destroyed (a stale handle resolves, it does not dangle).
526///
527/// # Safety
528/// As [`scene_of`].
529unsafe fn player<'a>(handle: *mut SsPlayer) -> Option<&'a mut SSPlayer> {
530    let (scene, id) = unsafe { scene_of(handle) }?;
531    scene.host.player_mut(id)
532}
533
534/// Borrow a NUL-terminated UTF-8 string argument.
535///
536/// # Safety
537/// `s` must be null or point at a NUL-terminated string.
538unsafe fn c_str<'a>(s: *const c_char) -> Option<&'a str> {
539    if s.is_null() {
540        return None;
541    }
542    unsafe { CStr::from_ptr(s) }.to_str().ok()
543}
544
545/// Borrow an *optional* string argument, where null means "the default" rather
546/// than a mistake — so a bad encoding is still reported instead of silently
547/// becoming the default.
548///
549/// # Safety
550/// As [`c_str`].
551unsafe fn optional_c_str<'a>(s: *const c_char) -> Result<Option<&'a str>, &'static str> {
552    if s.is_null() {
553        return Ok(None);
554    }
555    unsafe { c_str(s) }.map(Some).ok_or("string is not UTF-8")
556}
557
558fn backend_bits(backend: u32) -> Option<wgpu::Backends> {
559    match backend {
560        SS_BACKEND_AUTO => Some(wgpu::Backends::PRIMARY),
561        SS_BACKEND_DX12 => Some(wgpu::Backends::DX12),
562        SS_BACKEND_METAL => Some(wgpu::Backends::METAL),
563        SS_BACKEND_VULKAN => Some(wgpu::Backends::VULKAN),
564        _ => None,
565    }
566}
567
568/// Turn the flat C window handle into the surface target wgpu takes.
569///
570/// # Safety
571/// `handle` must describe a live window/layer of the advertised `kind`, which
572/// must outlive the surface built from the returned target.
573unsafe fn surface_target(handle: &SsWindowHandle) -> Result<wgpu::SurfaceTargetUnsafe, String> {
574    // A CAMetalLayer has no raw-window-handle representation, so it takes wgpu's
575    // dedicated target instead of the RawHandle pair below.
576    #[cfg(target_vendor = "apple")]
577    if handle.kind == SS_WINDOW_METAL_LAYER {
578        if handle.window.is_null() {
579            return Err("CAMetalLayer* is null".into());
580        }
581        return Ok(wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(handle.window));
582    }
583
584    let window_ptr = NonNull::new(handle.window).ok_or("window handle is null")?;
585
586    let (display, window) = match handle.kind {
587        SS_WINDOW_WIN32 => {
588            let hwnd = NonZeroIsize::new(handle.window as isize).ok_or("HWND is null")?;
589            let mut win = rwh::Win32WindowHandle::new(hwnd);
590            win.hinstance = NonZeroIsize::new(handle.display as isize);
591            (rwh::RawDisplayHandle::Windows(rwh::WindowsDisplayHandle::new()), rwh::RawWindowHandle::Win32(win))
592        }
593        SS_WINDOW_APPKIT => (rwh::RawDisplayHandle::AppKit(rwh::AppKitDisplayHandle::new()), rwh::RawWindowHandle::AppKit(rwh::AppKitWindowHandle::new(window_ptr))),
594        SS_WINDOW_XLIB => {
595            let display = NonNull::new(handle.display);
596            (rwh::RawDisplayHandle::Xlib(rwh::XlibDisplayHandle::new(display, handle.screen)), rwh::RawWindowHandle::Xlib(rwh::XlibWindowHandle::new(handle.window as usize as _)))
597        }
598        SS_WINDOW_WAYLAND => {
599            let display = NonNull::new(handle.display).ok_or("wl_display* is null")?;
600            (rwh::RawDisplayHandle::Wayland(rwh::WaylandDisplayHandle::new(display)), rwh::RawWindowHandle::Wayland(rwh::WaylandWindowHandle::new(window_ptr)))
601        }
602        other => return Err(format!("window kind {other} is not supported on this platform (see SS_WINDOW_*)")),
603    };
604    Ok(wgpu::SurfaceTargetUnsafe::RawHandle { raw_display_handle: Some(display), raw_window_handle: window })
605}
606
607// --- lifecycle ------------------------------------------------------------
608
609/// Create a scene that renders into the window described by `desc`.
610///
611/// Returns null on failure; call `ss_last_error` for the reason. The window (and
612/// its layer, on macOS) must stay alive until `ss_scene_destroy`.
613///
614/// A scene holds no player of its own — add them with `ss_scene_create_player`,
615/// as many as the window should show.
616///
617/// # Safety
618/// `desc` must point at a valid `ss_scene_desc_t` whose window handle is live
619/// and matches its `kind`. On macOS this must be called from the main thread.
620#[unsafe(no_mangle)]
621pub unsafe extern "C" fn ss_scene_create(desc: *const SsSceneDesc) -> *mut SsScene {
622    let Some(desc) = (unsafe { desc.as_ref() }) else {
623        set_last_error("desc is null");
624        return std::ptr::null_mut();
625    };
626    let target = match unsafe { surface_target(&desc.window) } {
627        Ok(target) => target,
628        Err(msg) => {
629            set_last_error(msg);
630            return std::ptr::null_mut();
631        }
632    };
633    let Some(backends) = backend_bits(desc.backend) else {
634        set_last_error(format!("backend {} is not an SS_BACKEND_* value", desc.backend));
635        return std::ptr::null_mut();
636    };
637    let config = NativeHostConfig { backends, width: desc.width, height: desc.height, clear_color: desc.clear_color, enable_mask: desc.enable_mask, y_down: desc.y_down };
638
639    // SAFETY: forwarded from this function's contract — the caller keeps the
640    // window alive until `ss_scene_destroy`.
641    match unsafe { NativeHost::new(target, &config) } {
642        Ok(host) => Box::into_raw(Box::new(SsScene {
643            host,
644            handles: Vec::new(),
645            name_scratch: CString::default(),
646            texture_name_scratch: CString::default(),
647            path_scratch: CString::default(),
648            missing_scratch: CString::default(),
649            event_text_scratch: CScratch::default(),
650            param_id_scratch: CScratch::default(),
651            param_text_scratch: CScratch::default(),
652            current_scratch: CString::default(),
653            part_name_scratch: CString::default(),
654            cellmap_name_scratch: CString::default(),
655            cell_name_scratch: CString::default(),
656        })),
657        Err(msg) => {
658            set_last_error(msg);
659            std::ptr::null_mut()
660        }
661    }
662}
663
664/// Destroy a scene, its players and its wgpu resources. Null is a no-op.
665///
666/// **Every `ss_player_t` this scene issued becomes invalid**, including handles
667/// the caller still holds — using one afterwards reads freed memory. Drop them
668/// with the scene.
669///
670/// # Safety
671/// `handle` must come from `ss_scene_create` and must not be used afterwards,
672/// nor must any player handle it created.
673#[unsafe(no_mangle)]
674pub unsafe extern "C" fn ss_scene_destroy(handle: *mut SsScene) {
675    if handle.is_null() {
676        return;
677    }
678    let scene = unsafe { Box::from_raw(handle) };
679    for player in &scene.handles {
680        drop(unsafe { Box::from_raw(*player) });
681    }
682    drop(scene);
683}
684
685/// Add a player to `scene` and return its handle, or null if `scene` is null.
686///
687/// One scene draws any number of players, in ascending `ss_player_set_order`.
688/// They share the window's device, renderer and atlas textures, so the second
689/// character of a pack costs no upload and no extra pipeline.
690///
691/// The handle stays valid until `ss_player_destroy` or `ss_scene_destroy`.
692///
693/// # Safety
694/// `scene` must be a live handle or null.
695#[unsafe(no_mangle)]
696pub unsafe extern "C" fn ss_scene_create_player(scene: *mut SsScene) -> *mut SsPlayer {
697    let Some(scene_ref) = (unsafe { scene.as_mut() }) else {
698        set_last_error("scene is null");
699        return std::ptr::null_mut();
700    };
701    let id = scene_ref.host.create_player();
702    let handle = Box::into_raw(Box::new(SsPlayer { scene, id }));
703    scene_ref.handles.push(handle);
704    handle
705}
706
707/// Remove a player from its scene. Null, or a handle already destroyed, is a
708/// safe no-op — the handle itself stays allocated until the scene goes.
709///
710/// # Safety
711/// `handle` must be null or come from `ss_scene_create_player` on a scene that
712/// is still alive.
713#[unsafe(no_mangle)]
714pub unsafe extern "C" fn ss_player_destroy(handle: *mut SsPlayer) {
715    if let Some((scene, id)) = unsafe { scene_of(handle) } {
716        scene.host.destroy_player(id);
717    }
718}
719
720/// How many players `scene` currently holds.
721///
722/// # Safety
723/// `scene` must be a live handle or null.
724#[unsafe(no_mangle)]
725pub unsafe extern "C" fn ss_scene_player_count(scene: *mut SsScene) -> u32 {
726    unsafe { scene.as_ref() }.map(|s| s.host.player_count() as u32).unwrap_or(0)
727}
728
729// --- resources ------------------------------------------------------------
730
731/// Load a `.ssab` from `path` **and everything it depends on**, then select it.
732///
733/// The whole of loading in one call: the pack, both of its texture tables in
734/// either export mode, and the sibling packs its instance parts play from,
735/// transitively. Nothing is left for the caller to discover — no
736/// `ss_player_texture_at` loop, no `ss_scene_add_texture_png` per atlas.
737///
738/// ```c
739/// ss_player_load(player, "assets/Instance.ssab");
740/// ss_player_set_animation(player, "anime_1");
741/// ss_player_play(player);
742/// ```
743///
744/// Everything the pack names is resolved against **the `.ssab`'s own directory**,
745/// which is what the exporter wrote those paths relative to. Atlases reach the
746/// GPU on the next `ss_scene_update`, the same moment an embedded pack's do.
747///
748/// A host whose assets are not files — a pack file, an archive, a platform asset
749/// manager — keeps using `ss_player_load_ssab` plus `ss_scene_add_texture_png`,
750/// which is why those remain.
751///
752/// # Safety
753/// `path` must be a NUL-terminated UTF-8 string. It is not retained beyond the call.
754#[unsafe(no_mangle)]
755pub unsafe extern "C" fn ss_player_load(handle: *mut SsPlayer, path: *const c_char) -> i32 {
756    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
757    let Some(path) = (unsafe { c_str(path) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "path is null or not UTF-8") };
758    match player.load(path) {
759        Ok(()) => SS_OK,
760        Err(e) => fail(e.as_code(), format!("{path}: {e}")),
761    }
762}
763
764/// Register an `.ssab` pack under `pack_name` without changing what plays.
765///
766/// Every pack an animation can reference must be registered before
767/// `ss_player_set_animation`, since external instance parts resolve by pack
768/// name. Embedded-mode packs also carry their atlases; those are decoded and
769/// uploaded on the next `ss_scene_update`.
770///
771/// # Safety
772/// `pack_name` must be a NUL-terminated UTF-8 string and `data` must point at
773/// `len` readable bytes. Neither is retained beyond the call.
774#[unsafe(no_mangle)]
775pub unsafe extern "C" fn ss_player_add_ssab(handle: *mut SsPlayer, pack_name: *const c_char, data: *const u8, len: usize) -> i32 {
776    unsafe { load_pack(handle, pack_name, data, len, false) }
777}
778
779/// Register `pack_name` and make it the pack `ss_player_set_animation` selects from.
780///
781/// # Safety
782/// As `ss_player_add_ssab`.
783#[unsafe(no_mangle)]
784pub unsafe extern "C" fn ss_player_load_ssab(handle: *mut SsPlayer, pack_name: *const c_char, data: *const u8, len: usize) -> i32 {
785    unsafe { load_pack(handle, pack_name, data, len, true) }
786}
787
788/// Shared body of `ss_player_add_ssab` / `ss_player_load_ssab`.
789///
790/// # Safety
791/// As `ss_player_add_ssab`.
792unsafe fn load_pack(handle: *mut SsPlayer, pack_name: *const c_char, data: *const u8, len: usize, main: bool) -> i32 {
793    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
794    let Some(pack) = (unsafe { c_str(pack_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "pack_name is null or not UTF-8") };
795    if data.is_null() || len == 0 {
796        return fail(SS_ERROR_INVALID_ARGUMENT, "ssab data is empty");
797    }
798    let bytes = unsafe { std::slice::from_raw_parts(data, len) };
799    let result = if main { player.load_ssab(pack, bytes) } else { player.add_ssab(pack, bytes) };
800    match result {
801        Ok(()) => SS_OK,
802        Err(e) => fail(e.as_code(), format!("{pack}: {e}")),
803    }
804}
805
806/// Supply a texture for a reference-mode pack under `ss_texture_ref_t.key` — what
807/// `ss_player_texture_at` reports for the atlas. It identifies the image, not the
808/// cell map hash in `DrawBatch.texture_hash`. `rgba` is
809/// straight-alpha RGBA8, `width * height * 4` bytes; it is premultiplied on the
810/// way to the GPU.
811///
812/// Registered on the **scene**, because the texture map is device-scoped: every
813/// player in the window sees it, and a pack shown five times is uploaded once.
814/// Embedded-mode packs need no call — their atlases load with the
815/// pack.
816///
817/// Fails with `SS_ERROR_INVALID_ARGUMENT`, uploading nothing, when the device
818/// cannot hold the texture: wider or taller than its `max_texture_dimension_2d`
819/// (8192 on the device this library asks for), or empty.
820///
821/// # Safety
822/// `rgba` must point at `width * height * 4` readable bytes. It is not retained.
823#[unsafe(no_mangle)]
824pub unsafe extern "C" fn ss_scene_add_texture(scene: *mut SsScene, key: u32, rgba: *const u8, width: u32, height: u32) -> i32 {
825    let Some(scene) = (unsafe { scene.as_mut() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "scene is null") };
826    if rgba.is_null() {
827        return fail(SS_ERROR_INVALID_ARGUMENT, "texture is empty");
828    }
829    if let Some(why) = scene.host.texture_extent_error(width, height) {
830        return fail(SS_ERROR_INVALID_ARGUMENT, why);
831    }
832    // Inside the device's limit, so the product cannot overflow.
833    let len = (width as usize) * (height as usize) * 4;
834    scene.host.upload_texture(key, unsafe { std::slice::from_raw_parts(rgba, len) }, width, height);
835    SS_OK
836}
837
838/// `ss_scene_add_texture` from **encoded** image bytes (PNG) instead of raw RGBA:
839/// the library decodes, premultiplies and uploads.
840///
841/// It carries a PNG decoder for embedded packs anyway, so a C host
842/// showing a reference-mode `.ssab` does not have to bring ImageIO / WIC /
843/// libpng along just to hand the pixels over. Reading the file is still the
844/// host's job — nothing here opens one.
845///
846/// Fails with `SS_ERROR_INVALID_ARGUMENT` when the bytes do not decode, or
847/// decode to an image the device cannot hold (see `ss_scene_add_texture`).
848///
849/// # Safety
850/// `data` must point at `len` readable bytes. It is not retained.
851#[unsafe(no_mangle)]
852pub unsafe extern "C" fn ss_scene_add_texture_png(scene: *mut SsScene, key: u32, data: *const u8, len: usize) -> i32 {
853    let Some(scene) = (unsafe { scene.as_mut() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "scene is null") };
854    if data.is_null() || len == 0 {
855        return fail(SS_ERROR_INVALID_ARGUMENT, "image is empty");
856    }
857    match scene.host.upload_texture_encoded(key, unsafe { std::slice::from_raw_parts(data, len) }) {
858        Ok(()) => SS_OK,
859        Err(msg) => fail(SS_ERROR_INVALID_ARGUMENT, msg),
860    }
861}
862
863/// How many atlases a registered pack asks for. `pack_name` null
864/// selects the main pack; 0 means nothing is registered under that name.
865///
866/// # Safety
867/// `pack_name` must be null or a NUL-terminated UTF-8 string.
868#[unsafe(no_mangle)]
869pub unsafe extern "C" fn ss_player_texture_count(handle: *mut SsPlayer, pack_name: *const c_char) -> u32 {
870    let Some(player) = (unsafe { player(handle) }) else {
871        set_last_error("player handle is null or destroyed");
872        return 0;
873    };
874    let pack = match unsafe { optional_c_str(pack_name) } {
875        Ok(pack) => pack,
876        Err(msg) => {
877            set_last_error(msg);
878            return 0;
879        }
880    };
881    player.textures(pack).map(|textures| textures.len() as u32).unwrap_or(0)
882}
883
884/// Describe the `index`-th atlas of a registered pack, so a reference-mode host
885/// knows *what* to load and *where the exporter put it*.
886///
887/// This is the half of texture supply only the `.ssab` can answer, and it is the
888/// same shape the sibling players expose: register the pack, walk this list, and
889/// for every entry whose `embedded` is false read
890/// `<directory the .ssab came from>/<path>` and hand it to
891/// `ss_scene_add_texture_png`. Embedded entries need no call at all.
892///
893/// `pack_name` null selects the main pack. Writes `out` and returns `SS_OK`, or
894/// leaves it untouched and reports the reason.
895///
896/// # Safety
897/// `pack_name` must be null or a NUL-terminated UTF-8 string, and `out` must
898/// point at a writable `ss_texture_ref_t`.
899#[unsafe(no_mangle)]
900pub unsafe extern "C" fn ss_player_texture_at(handle: *mut SsPlayer, pack_name: *const c_char, index: u32, out: *mut SsTextureRef) -> i32 {
901    if out.is_null() {
902        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
903    }
904    let Some((scene, id)) = (unsafe { scene_of(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
905    let pack = match unsafe { optional_c_str(pack_name) } {
906        Ok(pack) => pack,
907        Err(msg) => return fail(SS_ERROR_INVALID_ARGUMENT, msg),
908    };
909
910    // Copied out before the scratch is touched: the borrow of the player ends
911    // here, and `scene` is needed mutably to own the string handed back.
912    let Some((texture, key)) = scene.host.player_mut(id).and_then(|player| {
913        let texture = player.textures(pack)?.get(index as usize).cloned()?;
914        let key = player.texture_key(pack, texture.slot);
915        Some((texture, key))
916    }) else {
917        return fail(SS_ERROR_INVALID_ARGUMENT, format!("no texture at index {index}"));
918    };
919    let Ok(path) = CString::new(texture.path) else {
920        return fail(SS_ERROR_INVALID_ARGUMENT, "image path contains an interior NUL");
921    };
922    scene.path_scratch = path;
923    unsafe { out.write(SsTextureRef { key, embedded: texture.embedded, path: scene.path_scratch.as_ptr() }) };
924    SS_OK
925}
926
927/// Replace the texture a cellmap binds, on one player, from straight-alpha RGBA8
928/// pixels — a costume change or dynamic expression, driven from the program
929/// rather than the authoring data.
930///
931/// `pack_name` null selects the main pack. `cellmap_name` is a cellmap name or a
932/// TextureChange target — one of the strings `ss_player_cellmap_texture_name`
933/// lists. `rgba` is `width * height * 4` bytes and is premultiplied on the way to
934/// the GPU; **passing `rgba` null restores** the cellmap to its original atlas
935/// (`width` / `height` are then ignored). The swap is per player — another player
936/// of the same pack is unaffected — and reaches the GPU on the next scene update.
937///
938/// The replacement should match the original atlas's size and cell layout: the
939/// runtime's UVs stay in the original cellmap's pixel space, so a different
940/// resolution samples a different region. One the device cannot hold fails
941/// with `SS_ERROR_INVALID_ARGUMENT` and leaves the cellmap as it was (see
942/// `ss_scene_add_texture`), as does a `cellmap_name` the pack does not list or a
943/// `pack_name` the player does not hold. Restoring a cellmap that carries no
944/// override succeeds and changes nothing.
945///
946/// # Safety
947/// `pack_name` must be null or NUL-terminated UTF-8; `cellmap_name` must be
948/// NUL-terminated UTF-8. When `rgba` is non-null it must point at
949/// `width * height * 4` readable bytes; it is not retained.
950#[unsafe(no_mangle)]
951pub unsafe extern "C" fn ss_player_set_cellmap_texture(handle: *mut SsPlayer, pack_name: *const c_char, cellmap_name: *const c_char, rgba: *const u8, width: u32, height: u32) -> i32 {
952    let Some((scene, id)) = (unsafe { scene_of(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
953    // Asked of the scene before the player is borrowed out of it: the pixels
954    // reach the device only on the next update, where a refusal has no caller.
955    let too_large = (!rgba.is_null()).then(|| scene.host.texture_extent_error(width, height)).flatten();
956    let Some(player) = scene.host.player_mut(id) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
957    let pack = match unsafe { optional_c_str(pack_name) } {
958        Ok(pack) => pack,
959        Err(msg) => return fail(SS_ERROR_INVALID_ARGUMENT, msg),
960    };
961    let Some(name) = (unsafe { c_str(cellmap_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "cellmap_name is null or not UTF-8") };
962
963    // A live override is restorable even after a load dropped its pack.
964    if !player.can_replace(pack, name) && !(rgba.is_null() && player.is_cellmap_overridden(pack, name)) {
965        return fail(SS_ERROR_INVALID_ARGUMENT, format!("{name}: the pack is not registered, or names no cellmap or texture by that name"));
966    }
967    if rgba.is_null() {
968        player.restore_cellmap_texture(pack, name);
969        return SS_OK;
970    }
971    if let Some(why) = too_large {
972        return fail(SS_ERROR_INVALID_ARGUMENT, format!("{name}: {why}"));
973    }
974    // Inside the device's limit, so the product cannot overflow.
975    let len = (width as usize) * (height as usize) * 4;
976    match player.set_cellmap_texture(pack, name, unsafe { std::slice::from_raw_parts(rgba, len) }, width, height) {
977        Ok(()) => SS_OK,
978        Err(e) => fail(e.as_code(), format!("{name}: {e}")),
979    }
980}
981
982/// Whether a cellmap currently carries a runtime override on this player.
983/// `pack_name` null selects the main pack; a null/destroyed handle reads false.
984///
985/// # Safety
986/// `pack_name` must be null or NUL-terminated UTF-8; `cellmap_name` must be
987/// NUL-terminated UTF-8.
988#[unsafe(no_mangle)]
989pub unsafe extern "C" fn ss_player_is_cellmap_overridden(handle: *mut SsPlayer, pack_name: *const c_char, cellmap_name: *const c_char) -> bool {
990    let Some(player) = (unsafe { player(handle) }) else { return false };
991    let Ok(pack) = (unsafe { optional_c_str(pack_name) }) else { return false };
992    let Some(name) = (unsafe { c_str(cellmap_name) }) else { return false };
993    player.is_cellmap_overridden(pack, name)
994}
995
996/// How many cellmap and TextureChange-target names a pack offers for replacement.
997/// `pack_name` null selects the main pack; 0 if nothing is loaded.
998///
999/// # Safety
1000/// `pack_name` must be null or a NUL-terminated UTF-8 string.
1001#[unsafe(no_mangle)]
1002pub unsafe extern "C" fn ss_player_cellmap_texture_count(handle: *mut SsPlayer, pack_name: *const c_char) -> u32 {
1003    let Some(player) = (unsafe { player(handle) }) else {
1004        set_last_error("player handle is null or destroyed");
1005        return 0;
1006    };
1007    let pack = match unsafe { optional_c_str(pack_name) } {
1008        Ok(pack) => pack,
1009        Err(msg) => {
1010            set_last_error(msg);
1011            return 0;
1012        }
1013    };
1014    player.replaceable_cellmap_names(pack).map(|names| names.len() as u32).unwrap_or(0)
1015}
1016
1017/// The `index`-th replaceable name of a pack — what to pass
1018/// `ss_player_set_cellmap_texture`. `pack_name` null selects the main pack.
1019///
1020/// The string is owned by the scene and stays valid until the next call to this
1021/// function on the same scene. Copy it if you need to keep it. Null if out of
1022/// range.
1023///
1024/// # Safety
1025/// `pack_name` must be null or a NUL-terminated UTF-8 string.
1026#[unsafe(no_mangle)]
1027pub unsafe extern "C" fn ss_player_cellmap_texture_name(handle: *mut SsPlayer, pack_name: *const c_char, index: u32) -> *const c_char {
1028    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
1029        set_last_error("player handle is null or destroyed");
1030        return std::ptr::null();
1031    };
1032    let pack = match unsafe { optional_c_str(pack_name) } {
1033        Ok(pack) => pack,
1034        Err(msg) => {
1035            set_last_error(msg);
1036            return std::ptr::null();
1037        }
1038    };
1039    let Some(name) = scene.host.player_mut(id).and_then(|p| p.replaceable_cellmap_names(pack)).and_then(|names| names.into_iter().nth(index as usize)) else {
1040        set_last_error(format!("no replaceable texture at index {index}"));
1041        return std::ptr::null();
1042    };
1043    lend_name(&mut scene.texture_name_scratch, name, "texture name")
1044}
1045
1046// The example below uses line comments: cbindgen renders these docs into a C
1047// block comment, which a `*/` would close early.
1048/// How many things the player's last load could not get.
1049///
1050/// `ss_player_load` reports an error only when the `.ssab` itself is unreadable —
1051/// one missing atlas must not cost you the character — so this is how a caller
1052/// tells a complete load from one that played anyway:
1053///
1054/// ```c
1055/// if (ss_player_load(player, path) != SS_OK) {
1056/// // the .ssab itself
1057/// } else if (ss_player_missing_count(player) > 0) {
1058/// // it plays, but something is a silhouette or absent
1059/// }
1060/// ```
1061///
1062/// Describes the most recent load, not the player's history. Zero for a null or
1063/// destroyed handle, which is indistinguishable from success — check the load's
1064/// own return value for that.
1065///
1066/// # Safety
1067/// `handle` must be a live handle or null.
1068#[unsafe(no_mangle)]
1069pub unsafe extern "C" fn ss_player_missing_count(handle: *mut SsPlayer) -> u32 {
1070    unsafe { player(handle) }.map(|p| p.missing_assets().len() as u32).unwrap_or(0)
1071}
1072
1073/// Detail of one entry in the list `ss_player_missing_count` sizes.
1074///
1075/// Writes `out` and returns `SS_OK`, or leaves it untouched and reports why.
1076///
1077/// # Safety
1078/// `out` must point at a writable `ss_missing_asset_t`.
1079#[unsafe(no_mangle)]
1080pub unsafe extern "C" fn ss_player_missing_at(handle: *mut SsPlayer, index: u32, out: *mut SsMissingAsset) -> i32 {
1081    if out.is_null() {
1082        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
1083    }
1084    let Some((scene, id)) = (unsafe { scene_of(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1085
1086    // Copied out before the scratch is touched: the borrow of the player ends
1087    // here, and `scene` is needed mutably to own the string handed back.
1088    let Some(missing) = scene.host.player_mut(id).and_then(|p| p.missing_assets().get(index as usize)).cloned() else {
1089        return fail(SS_ERROR_INVALID_ARGUMENT, format!("nothing missing at index {index}"));
1090    };
1091    let kind = match missing.kind {
1092        MissingKind::Texture => SS_MISSING_TEXTURE,
1093        MissingKind::Pack => SS_MISSING_PACK,
1094    };
1095    let Ok(name) = CString::new(missing.name) else {
1096        return fail(SS_ERROR_INVALID_ARGUMENT, "name contains an interior NUL");
1097    };
1098    scene.missing_scratch = name;
1099    unsafe { out.write(SsMissingAsset { kind, slot: missing.slot, name: scene.missing_scratch.as_ptr() }) };
1100    SS_OK
1101}
1102
1103// --- playback control -----------------------------------------------------
1104
1105/// Select the animation to play, rebuilding the instance tree. It is left at its
1106/// start frame and not playing — call `ss_player_play` to start it.
1107///
1108/// This is where playback allocates (contexts, slots), so `ss_player_play` and
1109/// the other transport calls stay allocation-free.
1110///
1111/// # Safety
1112/// `anim_name` must be a NUL-terminated UTF-8 string.
1113#[unsafe(no_mangle)]
1114pub unsafe extern "C" fn ss_player_set_animation(handle: *mut SsPlayer, anim_name: *const c_char) -> i32 {
1115    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1116    let Some(name) = (unsafe { c_str(anim_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "anim_name is null or not UTF-8") };
1117    match player.set_animation(name) {
1118        Ok(()) => SS_OK,
1119        Err(e) => fail(e.as_code(), format!("{name}: {e}")),
1120    }
1121}
1122
1123/// Start the selected animation from the head of its section, re-arming the loop
1124/// count. Not a resume: it rewinds, so lifting a `ss_player_pause` is
1125/// `ss_player_resume`'s job.
1126/// Does nothing until `ss_player_set_animation` has succeeded.
1127///
1128/// # Safety
1129/// `handle` must be a live handle or null.
1130#[unsafe(no_mangle)]
1131pub unsafe extern "C" fn ss_player_play(handle: *mut SsPlayer) {
1132    if let Some(player) = unsafe { player(handle) } {
1133        player.play();
1134    }
1135}
1136
1137/// `ss_player_play` from `start_frame` rather than the head of the section. The
1138/// family spells this `play(startFrame)`; C has no overloads, so it is a second
1139/// entry point here. Re-arms the loop count exactly as `ss_player_play` does. A
1140/// frame outside the section is brought inside it, as `ss_player_seek` does.
1141///
1142/// # Safety
1143/// `handle` must be a live handle or null.
1144#[unsafe(no_mangle)]
1145pub unsafe extern "C" fn ss_player_play_from(handle: *mut SsPlayer, start_frame: f32) {
1146    if let Some(player) = unsafe { player(handle) } {
1147        player.play_from(start_frame);
1148    }
1149}
1150
1151/// Hold playback on the current frame. Idempotent, and ignored while nothing is
1152/// playing. Lift it with `ss_player_resume`.
1153///
1154/// # Safety
1155/// `handle` must be a live handle or null.
1156#[unsafe(no_mangle)]
1157pub unsafe extern "C" fn ss_player_pause(handle: *mut SsPlayer) {
1158    if let Some(player) = unsafe { player(handle) } {
1159        player.pause();
1160    }
1161}
1162
1163/// Lift a `ss_player_pause`, carrying on from the same frame. Idempotent, and a
1164/// no-op on a stopped animation — starting one is `ss_player_play`'s job.
1165///
1166/// # Safety
1167/// `handle` must be a live handle or null.
1168#[unsafe(no_mangle)]
1169pub unsafe extern "C" fn ss_player_resume(handle: *mut SsPlayer) {
1170    if let Some(player) = unsafe { player(handle) } {
1171        player.resume();
1172    }
1173}
1174
1175/// Stop playback. The playhead stays where it stands; nothing rewinds.
1176///
1177/// # Safety
1178/// `handle` must be a live handle or null.
1179#[unsafe(no_mangle)]
1180pub unsafe extern "C" fn ss_player_stop(handle: *mut SsPlayer) {
1181    if let Some(player) = unsafe { player(handle) } {
1182        player.stop();
1183    }
1184}
1185
1186/// Scale playback speed; 1.0 is the authored speed.
1187///
1188/// Zero and negative values **stop** the playhead where it stands. To play
1189/// backwards use `ss_player_set_playback_direction`, which is the separate
1190/// setting that controls direction.
1191///
1192/// # Safety
1193/// `handle` must be a live handle or null.
1194#[unsafe(no_mangle)]
1195pub unsafe extern "C" fn ss_player_set_speed_scale(handle: *mut SsPlayer, speed: f32) {
1196    if let Some(player) = unsafe { player(handle) } {
1197        player.set_speed_scale(speed);
1198    }
1199}
1200
1201/// The speed in effect, as a multiple of the frame rate: `0` for a speed that
1202/// was set to zero or below, since that is the stop it became.
1203///
1204/// # Safety
1205/// `handle` must be a live handle or null.
1206#[unsafe(no_mangle)]
1207pub unsafe extern "C" fn ss_player_speed_scale(handle: *mut SsPlayer) -> f32 {
1208    unsafe { player(handle) }.map(|p| p.speed_scale()).unwrap_or(1.0)
1209}
1210
1211/// Whether an animation has been started and has neither stopped nor finished.
1212/// `ss_player_pause` leaves it true; `ss_player_is_pausing` says whether it is
1213/// held.
1214///
1215/// # Safety
1216/// `handle` must be a live handle or null.
1217#[unsafe(no_mangle)]
1218pub unsafe extern "C" fn ss_player_is_playing(handle: *mut SsPlayer) -> bool {
1219    unsafe { player(handle) }.map(|p| p.is_playing()).unwrap_or(false)
1220}
1221
1222/// Whether playback is held in place. `ss_player_is_playing` stays true.
1223///
1224/// # Safety
1225/// `handle` must be a live handle or null.
1226#[unsafe(no_mangle)]
1227pub unsafe extern "C" fn ss_player_is_pausing(handle: *mut SsPlayer) -> bool {
1228    unsafe { player(handle) }.map(|p| p.is_pausing()).unwrap_or(false)
1229}
1230
1231/// Which way the playhead is actually travelling — not the heading
1232/// `ss_player_set_playback_direction` configured, which `ss_player_playback_direction`
1233/// reports. Under ping-pong the return leg runs backward while the configured
1234/// heading still reads forward. Gate audio on this: SpriteStudio has no reverse
1235/// audio. True with no animation set up.
1236///
1237/// # Safety
1238/// `handle` must be a live handle or null.
1239#[unsafe(no_mangle)]
1240pub unsafe extern "C" fn ss_player_is_playing_forward(handle: *mut SsPlayer) -> bool {
1241    unsafe { player(handle) }.map(|p| p.is_playing_forward()).unwrap_or(true)
1242}
1243
1244/// Whether every configured loop has played. Sticky until the next play or
1245/// `ss_player_set_animation`, and never true under an infinite loop.
1246///
1247/// # Safety
1248/// `handle` must be a live handle or null.
1249#[unsafe(no_mangle)]
1250pub unsafe extern "C" fn ss_player_is_finished(handle: *mut SsPlayer) -> bool {
1251    unsafe { player(handle) }.map(|p| p.is_finished()).unwrap_or(false)
1252}
1253
1254/// Whether the last `ss_scene_update` crossed a loop boundary. An edge: true
1255/// only inside the update that crossed.
1256///
1257/// # Safety
1258/// `handle` must be a live handle or null.
1259#[unsafe(no_mangle)]
1260pub unsafe extern "C" fn ss_player_just_looped(handle: *mut SsPlayer) -> bool {
1261    unsafe { player(handle) }.map(|p| p.just_looped()).unwrap_or(false)
1262}
1263
1264/// Jump to `frame`. Fractional values are honoured.
1265///
1266/// # Safety
1267/// `handle` must be a live handle or null.
1268#[unsafe(no_mangle)]
1269pub unsafe extern "C" fn ss_player_seek(handle: *mut SsPlayer, frame: f32) {
1270    if let Some(player) = unsafe { player(handle) } {
1271        player.seek(frame);
1272    }
1273}
1274
1275/// Current playhead position, fractional. 0 when nothing is loaded.
1276///
1277/// # Safety
1278/// `handle` must be a live handle or null.
1279#[unsafe(no_mangle)]
1280pub unsafe extern "C" fn ss_player_frame_no(handle: *mut SsPlayer) -> f32 {
1281    unsafe { player(handle) }.map(|p| p.frame_no()).unwrap_or(0.0)
1282}
1283
1284/// First frame of the range being played; follows
1285/// `ss_player_set_animation_section`.
1286///
1287/// # Safety
1288/// `handle` must be a live handle or null.
1289#[unsafe(no_mangle)]
1290pub unsafe extern "C" fn ss_player_start_frame(handle: *mut SsPlayer) -> i32 {
1291    unsafe { player(handle) }.map(|p| p.start_frame()).unwrap_or(0)
1292}
1293
1294/// Last frame of that range.
1295///
1296/// # Safety
1297/// `handle` must be a live handle or null.
1298#[unsafe(no_mangle)]
1299pub unsafe extern "C" fn ss_player_end_frame(handle: *mut SsPlayer) -> i32 {
1300    unsafe { player(handle) }.map(|p| p.end_frame()).unwrap_or(0)
1301}
1302
1303/// Length of that range, both ends inclusive.
1304///
1305/// # Safety
1306/// `handle` must be a live handle or null.
1307#[unsafe(no_mangle)]
1308pub unsafe extern "C" fn ss_player_total_frames(handle: *mut SsPlayer) -> i32 {
1309    unsafe { player(handle) }.map(|p| p.total_frames()).unwrap_or(0)
1310}
1311
1312/// `count` cycles then stop; `-1` (or `0`) loops forever. Under ping-pong one
1313/// cycle is a full round trip.
1314///
1315/// # Safety
1316/// `handle` must be a live handle or null.
1317#[unsafe(no_mangle)]
1318pub unsafe extern "C" fn ss_player_set_loop_count(handle: *mut SsPlayer, count: i32) {
1319    if let Some(player) = unsafe { player(handle) } {
1320        player.set_loop_count(count);
1321    }
1322}
1323
1324/// The configured loop count — before an animation is set up, the one
1325/// `ss_player_set_loop_count` is holding for it, or 0 when none was set.
1326///
1327/// # Safety
1328/// `handle` must be a live handle or null.
1329#[unsafe(no_mangle)]
1330pub unsafe extern "C" fn ss_player_loop_count(handle: *mut SsPlayer) -> i32 {
1331    unsafe { player(handle) }.map(|p| p.loop_count()).unwrap_or(0)
1332}
1333
1334/// How many cycles of the loop count are left; 0 with no animation.
1335///
1336/// # Safety
1337/// `handle` must be a live handle or null.
1338#[unsafe(no_mangle)]
1339pub unsafe extern "C" fn ss_player_remaining_loops(handle: *mut SsPlayer) -> i32 {
1340    unsafe { player(handle) }.map(|p| p.remaining_loops()).unwrap_or(0)
1341}
1342
1343/// Override the advance rate in fps. Prefer `ss_player_set_speed_scale`, which scales
1344/// playback without replacing the authored rate.
1345///
1346/// # Safety
1347/// `handle` must be a live handle or null.
1348#[unsafe(no_mangle)]
1349pub unsafe extern "C" fn ss_player_set_frame_rate(handle: *mut SsPlayer, fps: i32) {
1350    if let Some(player) = unsafe { player(handle) } {
1351        player.set_frame_rate(fps);
1352    }
1353}
1354
1355/// The rate the animation advances at. 0 when nothing is loaded.
1356///
1357/// # Safety
1358/// `handle` must be a live handle or null.
1359#[unsafe(no_mangle)]
1360pub unsafe extern "C" fn ss_player_frame_rate(handle: *mut SsPlayer) -> i32 {
1361    unsafe { player(handle) }.map(|p| p.frame_rate()).unwrap_or(0)
1362}
1363
1364/// Restrict playback to `start..=end` of the current animation, so looping and
1365/// ping-pong turn around inside that range. Both ends are included; an end
1366/// outside the animation (`-1`, say) stands for the animation's edge on that
1367/// side. An end before the start, both inside the animation, is refused with
1368/// the runtime's invalid-parameter code, and the section and the playhead stay
1369/// as they were.
1370///
1371/// Call it **after** `ss_player_set_animation`: frame numbers only mean
1372/// something inside the animation they were measured in, and setting an
1373/// animation rebuilds the tree and takes the section with it.
1374///
1375/// # Safety
1376/// `handle` must be a live handle or null.
1377#[unsafe(no_mangle)]
1378pub unsafe extern "C" fn ss_player_set_animation_section(handle: *mut SsPlayer, start: i32, end: i32) -> i32 {
1379    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1380    match player.set_animation_section(start, end) {
1381        Ok(()) => SS_OK,
1382        Err(e) => fail(e.as_code(), format!("section {start}..={end}: {e}")),
1383    }
1384}
1385
1386/// `direction`: 0 forward, 1 backward. `style`: 0 normal, 1 ping-pong. Set as a
1387/// pair — pass the current value for whichever you are not changing.
1388///
1389/// # Safety
1390/// `handle` must be a live handle or null.
1391#[unsafe(no_mangle)]
1392pub unsafe extern "C" fn ss_player_set_playback_direction(handle: *mut SsPlayer, direction: i32, style: i32) {
1393    if let Some(player) = unsafe { player(handle) } {
1394        player.set_playback_direction(PlaybackDirection::from_wire(direction), PlaybackStyle::from_wire(style));
1395    }
1396}
1397
1398/// 0 forward, 1 backward.
1399///
1400/// # Safety
1401/// `handle` must be a live handle or null.
1402#[unsafe(no_mangle)]
1403pub unsafe extern "C" fn ss_player_playback_direction(handle: *mut SsPlayer) -> i32 {
1404    unsafe { player(handle) }.map(|p| p.playback_direction().as_wire()).unwrap_or(0)
1405}
1406
1407/// 0 normal, 1 ping-pong.
1408///
1409/// # Safety
1410/// `handle` must be a live handle or null.
1411#[unsafe(no_mangle)]
1412pub unsafe extern "C" fn ss_player_playback_style(handle: *mut SsPlayer) -> i32 {
1413    unsafe { player(handle) }.map(|p| p.playback_style().as_wire()).unwrap_or(0)
1414}
1415
1416/// True (the default) draws between authored frames; false floors the frame that
1417/// is drawn, pinning playback to whole ones.
1418///
1419/// The playhead keeps its fraction either way — `ss_player_frame_no` reports it
1420/// unrounded — and so does the stepping of instance and effect children. This
1421/// affects only what is drawn.
1422///
1423/// # Safety
1424/// `handle` must be a live handle or null.
1425#[unsafe(no_mangle)]
1426pub unsafe extern "C" fn ss_player_set_sub_frame_enabled(handle: *mut SsPlayer, enabled: bool) {
1427    if let Some(player) = unsafe { player(handle) } {
1428        player.set_sub_frame_enabled(enabled);
1429    }
1430}
1431
1432/// See `ss_player_set_sub_frame_enabled`.
1433///
1434/// # Safety
1435/// `handle` must be a live handle or null.
1436#[unsafe(no_mangle)]
1437pub unsafe extern "C" fn ss_player_sub_frame_enabled(handle: *mut SsPlayer) -> bool {
1438    unsafe { player(handle) }.map(|p| p.sub_frame_enabled()).unwrap_or(true)
1439}
1440
1441/// True (the default) keeps playback on the wall clock by dropping frames under
1442/// load; false advances exactly one frame per `ss_scene_update`.
1443///
1444/// # Safety
1445/// `handle` must be a live handle or null.
1446#[unsafe(no_mangle)]
1447pub unsafe extern "C" fn ss_player_set_frame_skip_enabled(handle: *mut SsPlayer, skip: bool) {
1448    if let Some(player) = unsafe { player(handle) } {
1449        player.set_frame_skip_enabled(skip);
1450    }
1451}
1452
1453/// See `ss_player_set_frame_skip_enabled`.
1454///
1455/// # Safety
1456/// `handle` must be a live handle or null.
1457#[unsafe(no_mangle)]
1458pub unsafe extern "C" fn ss_player_frame_skip_enabled(handle: *mut SsPlayer) -> bool {
1459    unsafe { player(handle) }.map(|p| p.frame_skip_enabled()).unwrap_or(true)
1460}
1461
1462// --- Per-part overrides ---
1463//
1464// Indices address the root animation and are stable within one pack, so resolve
1465// a name once with `ss_player_find_part_index` and keep the index. Overrides do
1466// not reach inside an instance part — its child runs as its own context. Call
1467// them only after `ss_player_set_animation`, which sizes the runtime's override
1468// table and clears everything but a permanent override.
1469
1470/// Resolve a part name to its index in the current animation, or -1 when the
1471/// name is unknown, `name` is not valid UTF-8, or no animation is set up.
1472///
1473/// Unlike the calls below this returns an index rather than a status, so it does
1474/// not touch `ss_last_error`.
1475///
1476/// # Safety
1477/// `handle` must be a live handle or null; `name` must be a valid
1478/// null-terminated C string.
1479#[unsafe(no_mangle)]
1480pub unsafe extern "C" fn ss_player_find_part_index(handle: *mut SsPlayer, name: *const c_char) -> i32 {
1481    let Some(player) = (unsafe { player(handle) }) else { return -1 };
1482    let Some(name) = (unsafe { c_str(name) }) else { return -1 };
1483    player.find_part_index(name).map(|i| i as i32).unwrap_or(-1)
1484}
1485
1486/// Force-hide a part (`hide` true) or revert it to the animation. `cascade`
1487/// propagates a force-hide to the part's descendants — a keyframe hide never
1488/// cascades, so this is the only way to hide a sub-tree.
1489///
1490/// # Safety
1491/// `handle` must be a live handle or null.
1492#[unsafe(no_mangle)]
1493pub unsafe extern "C" fn ss_player_set_part_visibility_override_by_index(handle: *mut SsPlayer, part: u32, hide: bool, cascade: bool) -> i32 {
1494    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1495    match player.set_part_visibility_override_by_index(part, hide, cascade) {
1496        Ok(()) => SS_OK,
1497        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1498    }
1499}
1500
1501// --- overrides, by part name ------------------------------------------
1502//
1503// The unsuffixed form takes a NAME; `_by_index` is the optimisation for a caller
1504// that cached one. Each of these resolves
1505// the name and forwards to its sibling, so the two cannot drift apart, and an
1506// unknown name fails with SS_ERROR_INVALID_ARGUMENT rather than doing nothing.
1507//
1508// Written out rather than generated by a macro: cbindgen does not expand macros,
1509// and a C entry point that never reaches the header cannot be called.
1510
1511/// Force-hide a part (`hide` true) or revert it to the animation, by part name.
1512///
1513/// # Safety
1514/// `handle` must be a live handle or null; `part` must be a valid
1515/// null-terminated C string.
1516#[unsafe(no_mangle)]
1517pub unsafe extern "C" fn ss_player_set_part_visibility_override(handle: *mut SsPlayer, part: *const c_char, hide: bool, cascade: bool) -> i32 {
1518    let Some(name) = (unsafe { c_str(part) }) else {
1519        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1520    };
1521    let index = {
1522        let Some(player) = (unsafe { player(handle) }) else {
1523            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1524        };
1525        match player.find_part_index(name) {
1526            Some(i) => i,
1527            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1528        }
1529    };
1530    unsafe { ss_player_set_part_visibility_override_by_index(handle, index, hide, cascade) }
1531}
1532
1533/// Revert a part to the animation's own visibility, by part name.
1534///
1535/// # Safety
1536/// `handle` must be a live handle or null; `part` must be a valid
1537/// null-terminated C string.
1538#[unsafe(no_mangle)]
1539pub unsafe extern "C" fn ss_player_clear_part_visibility_override(handle: *mut SsPlayer, part: *const c_char) -> i32 {
1540    let Some(name) = (unsafe { c_str(part) }) else {
1541        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1542    };
1543    let index = {
1544        let Some(player) = (unsafe { player(handle) }) else {
1545            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1546        };
1547        match player.find_part_index(name) {
1548            Some(i) => i,
1549            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1550        }
1551    };
1552    unsafe { ss_player_clear_part_visibility_override_by_index(handle, index) }
1553}
1554
1555/// Override a part's colour, by part name. Arguments as the `_by_index` sibling.
1556///
1557/// # Safety
1558/// `handle` must be a live handle or null; `part` must be a valid
1559/// null-terminated C string.
1560#[unsafe(no_mangle)]
1561pub unsafe extern "C" fn ss_player_set_part_color_override(handle: *mut SsPlayer, part: *const c_char, rgba: u32, blend_op: u8, priority: u8) -> i32 {
1562    let Some(name) = (unsafe { c_str(part) }) else {
1563        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1564    };
1565    let index = {
1566        let Some(player) = (unsafe { player(handle) }) else {
1567            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1568        };
1569        match player.find_part_index(name) {
1570            Some(i) => i,
1571            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1572        }
1573    };
1574    unsafe { ss_player_set_part_color_override_by_index(handle, index, rgba, blend_op, priority) }
1575}
1576
1577/// Four-corner colour override, by part name. Arguments as the `_by_index` sibling.
1578///
1579/// # Safety
1580/// `handle` must be a live handle or null; `part` must be a valid
1581/// null-terminated C string.
1582#[unsafe(no_mangle)]
1583pub unsafe extern "C" fn ss_player_set_part_color_override_corners(handle: *mut SsPlayer, part: *const c_char, corners: *const u8, blend_op: u8, priority: u8) -> i32 {
1584    let Some(name) = (unsafe { c_str(part) }) else {
1585        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1586    };
1587    let index = {
1588        let Some(player) = (unsafe { player(handle) }) else {
1589            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1590        };
1591        match player.find_part_index(name) {
1592            Some(i) => i,
1593            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1594        }
1595    };
1596    unsafe { ss_player_set_part_color_override_corners_by_index(handle, index, corners, blend_op, priority) }
1597}
1598
1599/// Revert a part to the animation's own colour, by part name.
1600///
1601/// # Safety
1602/// `handle` must be a live handle or null; `part` must be a valid
1603/// null-terminated C string.
1604#[unsafe(no_mangle)]
1605pub unsafe extern "C" fn ss_player_clear_part_color_override(handle: *mut SsPlayer, part: *const c_char) -> i32 {
1606    let Some(name) = (unsafe { c_str(part) }) else {
1607        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1608    };
1609    let index = {
1610        let Some(player) = (unsafe { player(handle) }) else {
1611            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1612        };
1613        match player.find_part_index(name) {
1614            Some(i) => i,
1615            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1616        }
1617    };
1618    unsafe { ss_player_clear_part_color_override_by_index(handle, index) }
1619}
1620
1621/// Make a part draw a different cell, by part name.
1622///
1623/// # Safety
1624/// `handle` must be a live handle or null; `part` must be a valid
1625/// null-terminated C string.
1626#[unsafe(no_mangle)]
1627pub unsafe extern "C" fn ss_player_set_part_cell_override(handle: *mut SsPlayer, part: *const c_char, cellmap_name: *const c_char, cell_name: *const c_char, priority: u8) -> i32 {
1628    let Some(name) = (unsafe { c_str(part) }) else {
1629        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1630    };
1631    let index = {
1632        let Some(player) = (unsafe { player(handle) }) else {
1633            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1634        };
1635        match player.find_part_index(name) {
1636            Some(i) => i,
1637            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1638        }
1639    };
1640    unsafe { ss_player_set_part_cell_override_by_index(handle, index, cellmap_name, cell_name, priority) }
1641}
1642
1643/// Revert a part to the animation's own cell, by part name.
1644///
1645/// # Safety
1646/// `handle` must be a live handle or null; `part` must be a valid
1647/// null-terminated C string.
1648#[unsafe(no_mangle)]
1649pub unsafe extern "C" fn ss_player_clear_part_cell_override(handle: *mut SsPlayer, part: *const c_char) -> i32 {
1650    let Some(name) = (unsafe { c_str(part) }) else {
1651        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1652    };
1653    let index = {
1654        let Some(player) = (unsafe { player(handle) }) else {
1655            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1656        };
1657        match player.find_part_index(name) {
1658            Some(i) => i,
1659            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1660        }
1661    };
1662    unsafe { ss_player_clear_part_cell_override_by_index(handle, index) }
1663}
1664
1665/// Write a part's current-frame transform into `out`, by part name.
1666///
1667/// # Safety
1668/// `handle` must be a live handle or null; `part` must be a valid
1669/// null-terminated C string.
1670#[unsafe(no_mangle)]
1671pub unsafe extern "C" fn ss_player_part_transform(handle: *mut SsPlayer, part: *const c_char, out: *mut f32) -> i32 {
1672    let Some(name) = (unsafe { c_str(part) }) else {
1673        return fail(SS_ERROR_INVALID_ARGUMENT, "part name is null or not UTF-8");
1674    };
1675    let index = {
1676        let Some(player) = (unsafe { player(handle) }) else {
1677            return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
1678        };
1679        match player.find_part_index(name) {
1680            Some(i) => i,
1681            None => return fail(SS_ERROR_INVALID_ARGUMENT, format!("no part called '{name}'")),
1682        }
1683    };
1684    unsafe { ss_player_part_transform_by_index(handle, index, out) }
1685}
1686
1687/// Revert a part to the animation's own visibility.
1688///
1689/// # Safety
1690/// `handle` must be a live handle or null.
1691#[unsafe(no_mangle)]
1692pub unsafe extern "C" fn ss_player_clear_part_visibility_override_by_index(handle: *mut SsPlayer, part: u32) -> i32 {
1693    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1694    match player.clear_part_visibility_override_by_index(part) {
1695        Ok(()) => SS_OK,
1696        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1697    }
1698}
1699
1700/// Override a part's colour. `blend_op`: 0 mix, 1 mul, 2 add, 3 sub. `rgba` is
1701/// packed `0xRRGGBBAA` in the authored 8-bit sRGB space — do not pre-multiply
1702/// it. `priority`: 0 until the next keyframe, 1 until the next animation, 2
1703/// permanent. Normal parts only; other kinds ignore it and still return `SS_OK`.
1704///
1705/// # Safety
1706/// `handle` must be a live handle or null.
1707#[unsafe(no_mangle)]
1708pub unsafe extern "C" fn ss_player_set_part_color_override_by_index(handle: *mut SsPlayer, part: u32, rgba: u32, blend_op: u8, priority: u8) -> i32 {
1709    let Some(blend_op) = BlendOp::from_wire(blend_op) else { return fail(SS_ERROR_INVALID_ARGUMENT, "blend_op must be 0..=3") };
1710    let Some(priority) = OverridePriority::from_wire(priority) else { return fail(SS_ERROR_INVALID_ARGUMENT, "priority must be 0..=2") };
1711    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1712    match player.set_part_color_override_by_index(part, rgba, blend_op, priority) {
1713        Ok(()) => SS_OK,
1714        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1715    }
1716}
1717
1718/// Four-corner colour override, for a gradient. `corners` points at 16 bytes in
1719/// the runtime's order — left-top, right-top, left-bottom, right-bottom, each
1720/// `[r, g, b, a]`. Otherwise as `ss_player_set_part_color_override`.
1721///
1722/// # Safety
1723/// `handle` must be a live handle or null; `corners` must point at 16 readable
1724/// bytes.
1725#[unsafe(no_mangle)]
1726pub unsafe extern "C" fn ss_player_set_part_color_override_corners_by_index(handle: *mut SsPlayer, part: u32, corners: *const u8, blend_op: u8, priority: u8) -> i32 {
1727    let Some(blend_op) = BlendOp::from_wire(blend_op) else { return fail(SS_ERROR_INVALID_ARGUMENT, "blend_op must be 0..=3") };
1728    let Some(priority) = OverridePriority::from_wire(priority) else { return fail(SS_ERROR_INVALID_ARGUMENT, "priority must be 0..=2") };
1729    if corners.is_null() {
1730        return fail(SS_ERROR_INVALID_ARGUMENT, "corners is null");
1731    }
1732    let mut rgba = [[0u8; 4]; 4];
1733    let bytes = unsafe { std::slice::from_raw_parts(corners, 16) };
1734    for (corner, chunk) in rgba.iter_mut().zip(bytes.as_chunks::<4>().0) {
1735        corner.copy_from_slice(chunk);
1736    }
1737    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1738    match player.set_part_color_override_corners_by_index(part, rgba, blend_op, priority) {
1739        Ok(()) => SS_OK,
1740        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1741    }
1742}
1743
1744/// Revert a part to the animation's own colour.
1745///
1746/// # Safety
1747/// `handle` must be a live handle or null.
1748#[unsafe(no_mangle)]
1749pub unsafe extern "C" fn ss_player_clear_part_color_override_by_index(handle: *mut SsPlayer, part: u32) -> i32 {
1750    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1751    match player.clear_part_color_override_by_index(part) {
1752        Ok(()) => SS_OK,
1753        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1754    }
1755}
1756
1757/// Make a part draw a different cell. `cellmap_name` is written without the
1758/// `.ssce` extension. Normal and Mask parts only; fails when the cell cannot be
1759/// resolved against the loaded pack.
1760///
1761/// # Safety
1762/// `handle` must be a live handle or null; both names must be valid
1763/// null-terminated C strings.
1764#[unsafe(no_mangle)]
1765pub unsafe extern "C" fn ss_player_set_part_cell_override_by_index(handle: *mut SsPlayer, part: u32, cellmap_name: *const c_char, cell_name: *const c_char, priority: u8) -> i32 {
1766    let Some(priority) = OverridePriority::from_wire(priority) else { return fail(SS_ERROR_INVALID_ARGUMENT, "priority must be 0..=2") };
1767    let Some(cellmap_name) = (unsafe { c_str(cellmap_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "cellmap_name is null or not UTF-8") };
1768    let Some(cell_name) = (unsafe { c_str(cell_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "cell_name is null or not UTF-8") };
1769    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1770    match player.set_part_cell_override_by_index(part, cellmap_name, cell_name, priority) {
1771        Ok(()) => SS_OK,
1772        Err(e) => fail(e.as_code(), format!("part {part} -> {cellmap_name}/{cell_name}: {e}")),
1773    }
1774}
1775
1776/// Revert a part to the animation's own cell.
1777///
1778/// # Safety
1779/// `handle` must be a live handle or null.
1780#[unsafe(no_mangle)]
1781pub unsafe extern "C" fn ss_player_clear_part_cell_override_by_index(handle: *mut SsPlayer, part: u32) -> i32 {
1782    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1783    match player.clear_part_cell_override_by_index(part) {
1784        Ok(()) => SS_OK,
1785        Err(e) => fail(e.as_code(), format!("part {part}: {e}")),
1786    }
1787}
1788
1789/// Drop every override on the root animation at once.
1790///
1791/// # Safety
1792/// `handle` must be a live handle or null.
1793#[unsafe(no_mangle)]
1794pub unsafe extern "C" fn ss_player_clear_all_part_overrides(handle: *mut SsPlayer) {
1795    if let Some(player) = unsafe { player(handle) } {
1796        player.clear_all_part_overrides();
1797    }
1798}
1799
1800/// How many parts the root animation has; 0 before one is set up.
1801///
1802/// # Safety
1803/// `handle` must be a live handle or null.
1804#[unsafe(no_mangle)]
1805pub unsafe extern "C" fn ss_player_part_count(handle: *mut SsPlayer) -> u32 {
1806    unsafe { player(handle) }.map(|p| p.part_count() as u32).unwrap_or(0)
1807}
1808
1809/// Whether `part` is a **skinned** mesh — a mesh part whose vertices are drawn
1810/// by bone skinning: `1` if it is, `0` if it is not (a rigid deform-only mesh,
1811/// or any non-mesh part — all good follow targets), or `-1` when the name is
1812/// unknown, `part` is not valid UTF-8, or no pack is bound.
1813///
1814/// A skinned mesh cannot be followed with `ss_player_part_transform`: its node
1815/// stays at the setup position (near the character root) while the bones move
1816/// the visible vertices, so a follower snaps to the root rather than onto the
1817/// art. Use this to warn in a "follow this part" picker, or to steer the choice
1818/// to a null / bone part, which carries its transform. Like
1819/// `ss_player_find_part_index` this returns a value rather than a status, so it
1820/// does not touch `ss_last_error`.
1821///
1822/// # Safety
1823/// `handle` must be a live handle or null; `part` must be a valid
1824/// null-terminated C string.
1825#[unsafe(no_mangle)]
1826pub unsafe extern "C" fn ss_player_is_part_skinned_mesh(handle: *mut SsPlayer, part: *const c_char) -> i32 {
1827    let Some(player) = (unsafe { player(handle) }) else { return -1 };
1828    let Some(part) = (unsafe { c_str(part) }) else { return -1 };
1829    match player.is_part_skinned_mesh(part) {
1830        Some(true) => 1,
1831        Some(false) => 0,
1832        None => -1,
1833    }
1834}
1835
1836/// Index form of `ss_player_is_part_skinned_mesh`: `1` skinned, `0` not, `-1`
1837/// when `part` is out of range or no pack is bound.
1838///
1839/// # Safety
1840/// `handle` must be a live handle or null.
1841#[unsafe(no_mangle)]
1842pub unsafe extern "C" fn ss_player_is_part_skinned_mesh_by_index(handle: *mut SsPlayer, part: u32) -> i32 {
1843    let Some(player) = (unsafe { player(handle) }) else { return -1 };
1844    match player.is_part_skinned_mesh_by_index(part) {
1845        Some(true) => 1,
1846        Some(false) => 0,
1847        None => -1,
1848    }
1849}
1850
1851/// Whether `part` is hidden on the frame the last `ss_scene_update` built: `1`
1852/// hidden, `0` shown or no frame built yet, or `-1` when the name is unknown,
1853/// `part` is not valid UTF-8, or no animation is set up. An override shows from
1854/// the next update.
1855///
1856/// The companion to `ss_player_part_transform`, which reports where a part
1857/// *would* be whether or not it is drawn: a host following a part needs both.
1858/// Like `ss_player_is_part_skinned_mesh` it returns a value rather than a
1859/// status, so it does not touch `ss_last_error`.
1860///
1861/// # Safety
1862/// `handle` must be a live handle or null; `part` must be a valid
1863/// null-terminated C string.
1864#[unsafe(no_mangle)]
1865pub unsafe extern "C" fn ss_player_is_part_hidden(handle: *mut SsPlayer, part: *const c_char) -> i32 {
1866    let Some(player) = (unsafe { player(handle) }) else { return -1 };
1867    let Some(part) = (unsafe { c_str(part) }) else { return -1 };
1868    match player.is_part_hidden(part) {
1869        Some(true) => 1,
1870        Some(false) => 0,
1871        None => -1,
1872    }
1873}
1874
1875/// Index form of `ss_player_is_part_hidden`: `1` hidden, `0` shown, `-1` when
1876/// `part` is out of range or no animation is set up.
1877///
1878/// # Safety
1879/// `handle` must be a live handle or null.
1880#[unsafe(no_mangle)]
1881pub unsafe extern "C" fn ss_player_is_part_hidden_by_index(handle: *mut SsPlayer, part: u32) -> i32 {
1882    let Some(player) = (unsafe { player(handle) }) else { return -1 };
1883    match player.is_part_hidden_by_index(part) {
1884        Some(true) => 1,
1885        Some(false) => 0,
1886        None => -1,
1887    }
1888}
1889
1890// --- Motion blending: tracks and sources ---
1891//
1892// The track stack over `SSPlayer`'s track API: tracks fold onto the setup pose
1893// in ascending order, track 0 being what `ss_player_set_animation` establishes.
1894// A track's alpha is its strength; a source's weight only sets proportions
1895// among the animations sharing one track.
1896//
1897// Reads follow this face's convention rather than the SDK C-API's NaN: a read
1898// of a track or source that does not exist answers 0, so check
1899// `ss_player_track_count` first. Two reads cannot use 0 and say so:
1900// `ss_player_track_fade_progress` (-1 when not fading, since 0 is a fade just
1901// started) and `ss_player_track_main_source` (`SS_INVALID_SOURCE`, since 0 is a
1902// handle).
1903
1904/// `ss_player_set_track_blend`: lerp toward the track's pose.
1905pub const SS_TRACK_BLEND_MIX: u32 = 0;
1906/// `ss_player_set_track_blend`: add the track's offset from the setup pose.
1907pub const SS_TRACK_BLEND_ADDITIVE: u32 = 1;
1908/// `ss_player_set_track_sync`: an animation laid on the track starts from its head.
1909pub const SS_TRACK_SYNC_FREE: u32 = 0;
1910/// `ss_player_set_track_sync`: it starts at the phase track 0 stands at.
1911pub const SS_TRACK_SYNC_START: u32 = 1;
1912/// `ss_player_track_main_source` on a track with no animation.
1913pub const SS_INVALID_SOURCE: u32 = u32::MAX;
1914
1915/// Map a track or source call onto the status convention.
1916fn track_status(result: Result<(), crate::SSRuntimeError>, what: std::fmt::Arguments<'_>) -> i32 {
1917    match result {
1918        Ok(()) => SS_OK,
1919        Err(e) => fail(e.as_code(), format!("{what}: {e}")),
1920    }
1921}
1922
1923/// Put `anim_name` on `track`, replacing what it was playing. Track 0 is better
1924/// set with `ss_player_set_animation`, which rebuilds the instance tree; this is
1925/// for the overlay tracks above it. On track 0 it still makes `anim_name` the
1926/// current animation.
1927///
1928/// # Safety
1929/// `handle` must be a live handle or null; `anim_name` a NUL-terminated UTF-8 string.
1930#[unsafe(no_mangle)]
1931pub unsafe extern "C" fn ss_player_set_track_animation(handle: *mut SsPlayer, track: u32, anim_name: *const c_char) -> i32 {
1932    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1933    let Some(name) = (unsafe { c_str(anim_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "anim_name is null or not UTF-8") };
1934    track_status(player.set_track_animation(track, name), format_args!("track {track}, {name}"))
1935}
1936
1937/// Number of tracks, empty ones included; 0 before an animation is set up.
1938///
1939/// # Safety
1940/// `handle` must be a live handle or null.
1941#[unsafe(no_mangle)]
1942pub unsafe extern "C" fn ss_player_track_count(handle: *mut SsPlayer) -> u32 {
1943    unsafe { player(handle) }.map(|p| p.track_count()).unwrap_or(0)
1944}
1945
1946/// Silence a track. Track 0 is refused — fade it to alpha 0 instead.
1947///
1948/// # Safety
1949/// `handle` must be a live handle or null.
1950#[unsafe(no_mangle)]
1951pub unsafe extern "C" fn ss_player_clear_track(handle: *mut SsPlayer, track: u32) -> i32 {
1952    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1953    track_status(player.clear_track(track), format_args!("track {track}"))
1954}
1955
1956/// How much of `track` survives onto the pose the tracks below produced. Not
1957/// clamped: above 1 extrapolates, 0 or below contributes nothing.
1958///
1959/// # Safety
1960/// `handle` must be a live handle or null.
1961#[unsafe(no_mangle)]
1962pub unsafe extern "C" fn ss_player_set_track_alpha(handle: *mut SsPlayer, track: u32, alpha: f32) -> i32 {
1963    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1964    track_status(player.set_track_alpha(track, alpha), format_args!("track {track}"))
1965}
1966
1967/// `track`'s alpha; 0 for a track that does not exist.
1968///
1969/// # Safety
1970/// `handle` must be a live handle or null.
1971#[unsafe(no_mangle)]
1972pub unsafe extern "C" fn ss_player_track_alpha(handle: *mut SsPlayer, track: u32) -> f32 {
1973    unsafe { player(handle) }.and_then(|p| p.track_alpha(track)).unwrap_or(0.0)
1974}
1975
1976/// `blend` is one of `SS_TRACK_BLEND_*`.
1977///
1978/// # Safety
1979/// `handle` must be a live handle or null.
1980#[unsafe(no_mangle)]
1981pub unsafe extern "C" fn ss_player_set_track_blend(handle: *mut SsPlayer, track: u32, blend: u32) -> i32 {
1982    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
1983    let blend = match blend {
1984        SS_TRACK_BLEND_MIX => crate::TrackBlend::Mix,
1985        SS_TRACK_BLEND_ADDITIVE => crate::TrackBlend::Additive,
1986        _ => return fail(SS_ERROR_INVALID_ARGUMENT, format!("blend {blend} is not one of SS_TRACK_BLEND_*")),
1987    };
1988    track_status(player.set_track_blend(track, blend), format_args!("track {track}"))
1989}
1990
1991/// One of `SS_TRACK_BLEND_*`; `SS_TRACK_BLEND_MIX` for a track that does not exist.
1992///
1993/// # Safety
1994/// `handle` must be a live handle or null.
1995#[unsafe(no_mangle)]
1996pub unsafe extern "C" fn ss_player_track_blend(handle: *mut SsPlayer, track: u32) -> u32 {
1997    match unsafe { player(handle) }.and_then(|p| p.track_blend(track)) {
1998        Some(crate::TrackBlend::Additive) => SS_TRACK_BLEND_ADDITIVE,
1999        _ => SS_TRACK_BLEND_MIX,
2000    }
2001}
2002
2003/// `sync` is one of `SS_TRACK_SYNC_*`: where the animations laid on `track` from
2004/// now on start. Set it before laying; a track with nothing on it yet is created
2005/// for it, and `ss_player_set_animation` resets every track to `FREE`.
2006///
2007/// # Safety
2008/// `handle` must be a live handle or null.
2009#[unsafe(no_mangle)]
2010pub unsafe extern "C" fn ss_player_set_track_sync(handle: *mut SsPlayer, track: u32, sync: u32) -> i32 {
2011    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2012    let sync = match sync {
2013        SS_TRACK_SYNC_FREE => crate::TrackSync::Free,
2014        SS_TRACK_SYNC_START => crate::TrackSync::Start,
2015        _ => return fail(SS_ERROR_INVALID_ARGUMENT, format!("sync {sync} is not one of SS_TRACK_SYNC_*")),
2016    };
2017    track_status(player.set_track_sync(track, sync), format_args!("track {track}"))
2018}
2019
2020/// One of `SS_TRACK_SYNC_*`; `SS_TRACK_SYNC_FREE` for a track that does not exist.
2021///
2022/// # Safety
2023/// `handle` must be a live handle or null.
2024#[unsafe(no_mangle)]
2025pub unsafe extern "C" fn ss_player_track_sync(handle: *mut SsPlayer, track: u32) -> u32 {
2026    match unsafe { player(handle) }.and_then(|p| p.track_sync(track)) {
2027        Some(crate::TrackSync::Start) => SS_TRACK_SYNC_START,
2028        _ => SS_TRACK_SYNC_FREE,
2029    }
2030}
2031
2032/// Fade `track` to `anim_name` over `duration_ms`, starting from whatever it is
2033/// playing. Advanced by `ss_scene_update`. On track 0, `anim_name` takes over
2034/// from the call on: it is the current animation, its state is what
2035/// `ss_player_is_finished` reports, and it plays with the speed, direction and
2036/// loop count the host set. The instance tree is not rebuilt; the instance and
2037/// effect parts belong to the pack, so the running children carry on.
2038///
2039/// # Safety
2040/// `handle` must be a live handle or null; `anim_name` a NUL-terminated UTF-8 string.
2041#[unsafe(no_mangle)]
2042pub unsafe extern "C" fn ss_player_crossfade(handle: *mut SsPlayer, track: u32, anim_name: *const c_char, duration_ms: f32) -> i32 {
2043    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2044    let Some(name) = (unsafe { c_str(anim_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "anim_name is null or not UTF-8") };
2045    track_status(player.crossfade(track, name, duration_ms), format_args!("track {track}, {name}"))
2046}
2047
2048/// Drive `track`'s alpha to `target` over `duration_ms`. Fading track 0 to 0
2049/// settles the character onto the setup pose.
2050///
2051/// # Safety
2052/// `handle` must be a live handle or null.
2053#[unsafe(no_mangle)]
2054pub unsafe extern "C" fn ss_player_fade_track(handle: *mut SsPlayer, track: u32, target: f32, duration_ms: f32) -> i32 {
2055    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2056    track_status(player.fade_track(track, target, duration_ms), format_args!("track {track}"))
2057}
2058
2059/// How far the fade on `track` has got, 0 to 1; **-1** when it is not fading,
2060/// since 0 is a fade that has just started.
2061///
2062/// # Safety
2063/// `handle` must be a live handle or null.
2064#[unsafe(no_mangle)]
2065pub unsafe extern "C" fn ss_player_track_fade_progress(handle: *mut SsPlayer, track: u32) -> f32 {
2066    unsafe { player(handle) }.and_then(|p| p.track_fade_progress(track)).unwrap_or(-1.0)
2067}
2068
2069/// Stop the fade on `track`, leaving alpha and weights where they stand.
2070///
2071/// # Safety
2072/// `handle` must be a live handle or null.
2073#[unsafe(no_mangle)]
2074pub unsafe extern "C" fn ss_player_cancel_track_fade(handle: *mut SsPlayer, track: u32) -> i32 {
2075    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2076    track_status(player.cancel_track_fade(track), format_args!("track {track}"))
2077}
2078
2079/// Seek `track`'s animation — how a continuous-control axis is driven.
2080///
2081/// # Safety
2082/// `handle` must be a live handle or null.
2083#[unsafe(no_mangle)]
2084pub unsafe extern "C" fn ss_player_set_track_frame(handle: *mut SsPlayer, track: u32, frame: f32) -> i32 {
2085    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2086    track_status(player.set_track_frame(track, frame), format_args!("track {track}"))
2087}
2088
2089/// `track`'s playhead; 0 for a track with no animation.
2090///
2091/// # Safety
2092/// `handle` must be a live handle or null.
2093#[unsafe(no_mangle)]
2094pub unsafe extern "C" fn ss_player_track_frame(handle: *mut SsPlayer, track: u32) -> f32 {
2095    unsafe { player(handle) }.and_then(|p| p.track_frame(track)).unwrap_or(0.0)
2096}
2097
2098/// `track`'s own playback speed; 0 parks it, which is how a scrubbed axis stays
2099/// where `ss_player_set_track_frame` puts it.
2100///
2101/// # Safety
2102/// `handle` must be a live handle or null.
2103#[unsafe(no_mangle)]
2104pub unsafe extern "C" fn ss_player_set_track_speed(handle: *mut SsPlayer, track: u32, speed: f32) -> i32 {
2105    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2106    track_status(player.set_track_speed(track, speed), format_args!("track {track}"))
2107}
2108
2109// A track's playback settings are the track's, not its animation's: they reach
2110// every animation on it now, both sides of a crossfade included, and every one
2111// laid on it later. Track 0's are the transport calls above
2112// (`ss_player_set_speed_scale` and the rest). The loop count is the exception:
2113// it belongs to the animation, and laying another one starts it looping
2114// forever again.
2115
2116/// What `ss_player_set_track_speed` stored; 0 for a track that does not exist.
2117///
2118/// # Safety
2119/// `handle` must be a live handle or null.
2120#[unsafe(no_mangle)]
2121pub unsafe extern "C" fn ss_player_track_speed(handle: *mut SsPlayer, track: u32) -> f32 {
2122    unsafe { player(handle) }.and_then(|p| p.track_speed(track)).unwrap_or(0.0)
2123}
2124
2125/// `ss_player_set_frame_rate` for one track.
2126///
2127/// # Safety
2128/// `handle` must be a live handle or null.
2129#[unsafe(no_mangle)]
2130pub unsafe extern "C" fn ss_player_set_track_frame_rate(handle: *mut SsPlayer, track: u32, fps: i32) -> i32 {
2131    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2132    track_status(player.set_track_frame_rate(track, fps), format_args!("track {track}"))
2133}
2134
2135/// The rate `track`'s animation plays at, the override or the authored rate; 0
2136/// for a track with neither, or that does not exist.
2137///
2138/// # Safety
2139/// `handle` must be a live handle or null.
2140#[unsafe(no_mangle)]
2141pub unsafe extern "C" fn ss_player_track_frame_rate(handle: *mut SsPlayer, track: u32) -> i32 {
2142    unsafe { player(handle) }.and_then(|p| p.track_frame_rate(track)).unwrap_or(0)
2143}
2144
2145/// `ss_player_set_frame_skip_enabled` for one track.
2146///
2147/// # Safety
2148/// `handle` must be a live handle or null.
2149#[unsafe(no_mangle)]
2150pub unsafe extern "C" fn ss_player_set_track_frame_skip_enabled(handle: *mut SsPlayer, track: u32, skip: bool) -> i32 {
2151    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2152    track_status(player.set_track_frame_skip_enabled(track, skip), format_args!("track {track}"))
2153}
2154
2155/// `false` for a track that does not exist.
2156///
2157/// # Safety
2158/// `handle` must be a live handle or null.
2159#[unsafe(no_mangle)]
2160pub unsafe extern "C" fn ss_player_track_frame_skip_enabled(handle: *mut SsPlayer, track: u32) -> bool {
2161    unsafe { player(handle) }.and_then(|p| p.track_frame_skip_enabled(track)).unwrap_or(false)
2162}
2163
2164/// `ss_player_set_playback_direction` for one track: `direction` and `style`
2165/// take the same `0` / `1` values.
2166///
2167/// # Safety
2168/// `handle` must be a live handle or null.
2169#[unsafe(no_mangle)]
2170pub unsafe extern "C" fn ss_player_set_track_playback_direction(handle: *mut SsPlayer, track: u32, direction: i32, style: i32) -> i32 {
2171    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2172    track_status(player.set_track_playback_direction(track, PlaybackDirection::from_wire(direction), PlaybackStyle::from_wire(style)), format_args!("track {track}"))
2173}
2174
2175/// `0` forward, `1` backward; 0 for a track that does not exist.
2176///
2177/// # Safety
2178/// `handle` must be a live handle or null.
2179#[unsafe(no_mangle)]
2180pub unsafe extern "C" fn ss_player_track_playback_direction(handle: *mut SsPlayer, track: u32) -> i32 {
2181    unsafe { player(handle) }.and_then(|p| p.track_playback_direction(track)).map(PlaybackDirection::as_wire).unwrap_or(0)
2182}
2183
2184/// `0` normal, `1` ping-pong; 0 for a track that does not exist.
2185///
2186/// # Safety
2187/// `handle` must be a live handle or null.
2188#[unsafe(no_mangle)]
2189pub unsafe extern "C" fn ss_player_track_playback_style(handle: *mut SsPlayer, track: u32) -> i32 {
2190    unsafe { player(handle) }.and_then(|p| p.track_playback_style(track)).map(PlaybackStyle::as_wire).unwrap_or(0)
2191}
2192
2193/// How many times `track`'s animation plays before it holds its last frame;
2194/// `-1` (or `0`) loops forever. Set it after laying the animation: one is laid
2195/// looping forever. On track 0 this is `ss_player_set_loop_count`, and the
2196/// player keeps the count for every animation laid there.
2197///
2198/// # Safety
2199/// `handle` must be a live handle or null.
2200#[unsafe(no_mangle)]
2201pub unsafe extern "C" fn ss_player_set_track_loop_count(handle: *mut SsPlayer, track: u32, count: i32) -> i32 {
2202    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2203    track_status(player.set_track_loop_count(track, count), format_args!("track {track}"))
2204}
2205
2206/// `-1` for a track that loops forever; 0 for one with no animation, a count
2207/// no animation reads back as.
2208///
2209/// # Safety
2210/// `handle` must be a live handle or null.
2211#[unsafe(no_mangle)]
2212pub unsafe extern "C" fn ss_player_track_loop_count(handle: *mut SsPlayer, track: u32) -> i32 {
2213    unsafe { player(handle) }.and_then(|p| p.track_loop_count(track)).unwrap_or(0)
2214}
2215
2216/// Whether `track`'s animation has played its loop count out and holds its last
2217/// frame. A state, as `ss_player_is_finished` is for track 0; there is no edge.
2218///
2219/// # Safety
2220/// `handle` must be a live handle or null.
2221#[unsafe(no_mangle)]
2222pub unsafe extern "C" fn ss_player_is_track_finished(handle: *mut SsPlayer, track: u32) -> bool {
2223    unsafe { player(handle) }.is_some_and(|p| p.is_track_finished(track))
2224}
2225
2226/// Whether the last `ss_scene_update` wrapped `track`'s animation back to its
2227/// start, as `ss_player_just_looped` is for track 0.
2228///
2229/// # Safety
2230/// `handle` must be a live handle or null.
2231#[unsafe(no_mangle)]
2232pub unsafe extern "C" fn ss_player_track_just_looped(handle: *mut SsPlayer, track: u32) -> bool {
2233    unsafe { player(handle) }.is_some_and(|p| p.track_just_looped(track))
2234}
2235
2236/// How far into a crossfade on `track` the outgoing animation keeps firing
2237/// events: while its share of the track, `1 - progress`, is at least
2238/// `threshold`. The default, infinity, silences it from the moment the fade
2239/// begins; `0.5` keeps it firing for the first half. Kept by the track. The
2240/// update that completes the fade has already released the outgoing animation,
2241/// so it fires nothing there, even at 0.
2242///
2243/// # Safety
2244/// `handle` must be a live handle or null.
2245#[unsafe(no_mangle)]
2246pub unsafe extern "C" fn ss_player_set_track_outgoing_event_threshold(handle: *mut SsPlayer, track: u32, threshold: f32) -> i32 {
2247    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2248    track_status(player.set_track_outgoing_event_threshold(track, threshold), format_args!("track {track}"))
2249}
2250
2251/// The track's outgoing event threshold (infinity by default); 0 for a track
2252/// that does not exist.
2253///
2254/// # Safety
2255/// `handle` must be a live handle or null.
2256#[unsafe(no_mangle)]
2257pub unsafe extern "C" fn ss_player_track_outgoing_event_threshold(handle: *mut SsPlayer, track: u32) -> f32 {
2258    unsafe { player(handle) }.and_then(|p| p.track_outgoing_event_threshold(track)).unwrap_or(0.0)
2259}
2260
2261/// The source carrying `track`'s animation; `SS_INVALID_SOURCE` when the track
2262/// has none, since 0 is a handle.
2263///
2264/// # Safety
2265/// `handle` must be a live handle or null.
2266#[unsafe(no_mangle)]
2267pub unsafe extern "C" fn ss_player_track_main_source(handle: *mut SsPlayer, track: u32) -> u32 {
2268    unsafe { player(handle) }.and_then(|p| p.track_main_source(track)).unwrap_or(SS_INVALID_SOURCE)
2269}
2270
2271/// Lay `anim_name` on `track` beside what it already carries, at `weight`, and
2272/// write its handle to `out_source`. On an empty track it becomes the main
2273/// source. `out_source` is untouched on failure.
2274///
2275/// # Safety
2276/// `handle` must be a live handle or null; `anim_name` a NUL-terminated UTF-8
2277/// string; `out_source` a writable `uint32_t`.
2278#[unsafe(no_mangle)]
2279pub unsafe extern "C" fn ss_player_add_track_source(handle: *mut SsPlayer, track: u32, anim_name: *const c_char, weight: f32, out_source: *mut u32) -> i32 {
2280    if out_source.is_null() {
2281        return fail(SS_ERROR_INVALID_ARGUMENT, "out_source is null");
2282    }
2283    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2284    let Some(name) = (unsafe { c_str(anim_name) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "anim_name is null or not UTF-8") };
2285    match player.add_track_source(track, name, weight) {
2286        Ok(source) => {
2287            unsafe { *out_source = source };
2288            SS_OK
2289        }
2290        Err(e) => fail(e.as_code(), format!("track {track}, {name}: {e}")),
2291    }
2292}
2293
2294/// A source's share **within its track**; weights are ratios.
2295///
2296/// # Safety
2297/// `handle` must be a live handle or null.
2298#[unsafe(no_mangle)]
2299pub unsafe extern "C" fn ss_player_set_source_weight(handle: *mut SsPlayer, source: u32, weight: f32) -> i32 {
2300    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2301    track_status(player.set_source_weight(source, weight), format_args!("source {source}"))
2302}
2303
2304/// A source's weight; 0 for a handle that names nothing.
2305///
2306/// # Safety
2307/// `handle` must be a live handle or null.
2308#[unsafe(no_mangle)]
2309pub unsafe extern "C" fn ss_player_source_weight(handle: *mut SsPlayer, source: u32) -> f32 {
2310    unsafe { player(handle) }.and_then(|p| p.source_weight(source)).unwrap_or(0.0)
2311}
2312
2313/// Seek one source — how a host keeps sources of different lengths in step.
2314///
2315/// # Safety
2316/// `handle` must be a live handle or null.
2317#[unsafe(no_mangle)]
2318pub unsafe extern "C" fn ss_player_set_source_frame(handle: *mut SsPlayer, source: u32, frame: f32) -> i32 {
2319    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2320    track_status(player.set_source_frame(source, frame), format_args!("source {source}"))
2321}
2322
2323/// A source's playhead; 0 for a handle that names nothing.
2324///
2325/// # Safety
2326/// `handle` must be a live handle or null.
2327#[unsafe(no_mangle)]
2328pub unsafe extern "C" fn ss_player_source_frame(handle: *mut SsPlayer, source: u32) -> f32 {
2329    unsafe { player(handle) }.and_then(|p| p.source_frame(source)).unwrap_or(0.0)
2330}
2331
2332/// The weight at or above which `source` fires its events. Only track 0's main
2333/// source fires by default (the default threshold is infinity); lower this to
2334/// the source's weight or below to have it fire too.
2335///
2336/// # Safety
2337/// `handle` must be a live handle or null.
2338#[unsafe(no_mangle)]
2339pub unsafe extern "C" fn ss_player_set_source_event_threshold(handle: *mut SsPlayer, source: u32, threshold: f32) -> i32 {
2340    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2341    track_status(player.set_source_event_threshold(source, threshold), format_args!("source {source}"))
2342}
2343
2344/// A source's event threshold (infinity by default); 0 for a handle that names
2345/// nothing.
2346///
2347/// # Safety
2348/// `handle` must be a live handle or null.
2349#[unsafe(no_mangle)]
2350pub unsafe extern "C" fn ss_player_source_event_threshold(handle: *mut SsPlayer, source: u32) -> f32 {
2351    unsafe { player(handle) }.and_then(|p| p.source_event_threshold(source)).unwrap_or(0.0)
2352}
2353
2354// --- Events ---
2355//
2356// Polled after `ss_scene_update`, which is what advanced the clock. Everything
2357// below describes that tick and is replaced by the next one, so a host that
2358// wants to keep a payload copies it before updating again.
2359//
2360// Each string a reader below returns stays valid until that reader's next call,
2361// as its own doc says.
2362
2363/// Whether the last `ss_scene_update` was the first to run after an
2364/// `ss_player_play` / `ss_player_play_from`: true for exactly one update. Not
2365/// raised by `ss_player_resume`, which carries on rather than starting.
2366///
2367/// # Safety
2368/// `handle` must be a live handle or null.
2369#[unsafe(no_mangle)]
2370pub unsafe extern "C" fn ss_player_just_started(handle: *mut SsPlayer) -> bool {
2371    unsafe { player(handle) }.map(|p| p.just_started()).unwrap_or(false)
2372}
2373
2374/// Whether the last `ss_scene_update` **completed** playback: true for exactly
2375/// one update, unlike the sticky `ss_player_is_finished`. Never true under an
2376/// infinite loop, and not raised by `ss_player_stop`.
2377///
2378/// # Safety
2379/// `handle` must be a live handle or null.
2380#[unsafe(no_mangle)]
2381pub unsafe extern "C" fn ss_player_just_finished(handle: *mut SsPlayer) -> bool {
2382    unsafe { player(handle) }.map(|p| p.just_finished()).unwrap_or(false)
2383}
2384
2385/// How many timeline events the last `ss_scene_update` crossed.
2386///
2387/// **Frames skipped over are included**: a long tick reports every frame it
2388/// stepped through, not just the one it landed on.
2389///
2390/// # Safety
2391/// `handle` must be a live handle or null.
2392#[unsafe(no_mangle)]
2393pub unsafe extern "C" fn ss_player_event_count(handle: *mut SsPlayer) -> u32 {
2394    unsafe { player(handle) }.map(|p| p.events().len() as u32).unwrap_or(0)
2395}
2396
2397/// Fill `out` with the `index`-th event of the last update.
2398///
2399/// Read `kind` first: it says which of the payload fields carry anything.
2400///
2401/// Returns `SS_OK`, or `SS_ERROR_INVALID_ARGUMENT` when the handle or `out` is
2402/// null or `index` is out of range, leaving `out` untouched.
2403///
2404/// # Safety
2405/// `handle` must be a live handle or null; `out` must point at a writable
2406/// `ss_event_data_t`.
2407#[unsafe(no_mangle)]
2408pub unsafe extern "C" fn ss_player_event_at(handle: *mut SsPlayer, index: u32, out: *mut SsEventData) -> i32 {
2409    if out.is_null() {
2410        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
2411    }
2412    let Some((scene, id)) = (unsafe { scene_of(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2413    // Split into the two fields this needs rather than borrowing the scene whole:
2414    // the event is read straight out of the player and the string is copied into
2415    // the scratch beside it, so nothing is cloned to end a borrow. Cloning the
2416    // event to get there duplicated every string it carried — and a signal's
2417    // whole parameter list — once per event per frame.
2418    let SsScene { host, event_text_scratch, .. } = scene;
2419    let Some(event) = host.player_mut(id).and_then(|p| p.events().get(index as usize)) else {
2420        return fail(SS_ERROR_INVALID_ARGUMENT, format!("event {index} is out of range"));
2421    };
2422
2423    let mut data = SsEventData {
2424        kind: 0,
2425        part_index: event.part_index(),
2426        frame_no: event.frame_no(),
2427        source: event.source(),
2428        has_integer: false,
2429        has_rect: false,
2430        has_point: false,
2431        has_text: false,
2432        integer: 0,
2433        rect: [0.0; 4],
2434        point: [0.0; 2],
2435        text: std::ptr::null(),
2436        param_count: 0,
2437        sound_list_name_hash: 0,
2438        sound_name_hash: 0,
2439        loop_num: 0,
2440    };
2441    let text: &str = match event {
2442        SsEvent::UserData(u) => {
2443            data.kind = SS_EVENT_USER_DATA;
2444            data.has_integer = u.integer.is_some();
2445            data.has_rect = u.rect.is_some();
2446            data.has_point = u.point.is_some();
2447            data.has_text = u.text.is_some();
2448            data.integer = u.integer.unwrap_or(0);
2449            data.rect = u.rect.unwrap_or([0.0; 4]);
2450            data.point = u.point.unwrap_or([0.0; 2]);
2451            u.text.as_deref().unwrap_or_default()
2452        }
2453        SsEvent::Signal(sig) => {
2454            data.kind = SS_EVENT_SIGNAL;
2455            data.param_count = sig.params.len() as u32;
2456            &sig.command_id
2457        }
2458        SsEvent::Audio(a) => {
2459            data.kind = SS_EVENT_AUDIO;
2460            data.sound_list_name_hash = a.sound_list_name_hash;
2461            data.sound_name_hash = a.sound_name_hash;
2462            data.loop_num = a.loop_num;
2463            &a.sound_name
2464        }
2465    };
2466
2467    data.text = event_text_scratch.set(text);
2468    unsafe { out.write(data) };
2469    SS_OK
2470}
2471
2472/// How many parameters the `index`-th event carries, or 0 when it is not a
2473/// signal.
2474///
2475/// # Safety
2476/// `handle` must be a live handle or null.
2477#[unsafe(no_mangle)]
2478pub unsafe extern "C" fn ss_player_event_signal_param_count(handle: *mut SsPlayer, index: u32) -> u32 {
2479    let Some(player) = (unsafe { player(handle) }) else { return 0 };
2480    match player.events().get(index as usize) {
2481        Some(SsEvent::Signal(s)) => s.params.len() as u32,
2482        _ => 0,
2483    }
2484}
2485
2486/// Fill `out` with parameter `param` of the `index`-th event, which must be a
2487/// signal.
2488///
2489/// Returns `SS_OK`, or `SS_ERROR_INVALID_ARGUMENT` when either index is out of
2490/// range or the event is not a signal, leaving `out` untouched.
2491///
2492/// # Safety
2493/// `handle` must be a live handle or null; `out` must point at a writable
2494/// `ss_signal_param_data_t`.
2495#[unsafe(no_mangle)]
2496pub unsafe extern "C" fn ss_player_event_signal_param_at(handle: *mut SsPlayer, index: u32, param: u32, out: *mut SsSignalParamData) -> i32 {
2497    if out.is_null() {
2498        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
2499    }
2500    let Some((scene, id)) = (unsafe { scene_of(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2501    // Two scratch slots and the host, borrowed apart — see `ss_player_event_at`.
2502    let SsScene { host, param_id_scratch, param_text_scratch, .. } = scene;
2503    let found = host.player_mut(id).and_then(|p| match p.events().get(index as usize) {
2504        Some(SsEvent::Signal(s)) => s.params.get(param as usize),
2505        _ => None,
2506    });
2507    let Some(p) = found else {
2508        return fail(SS_ERROR_INVALID_ARGUMENT, format!("event {index} parameter {param} is out of range, or the event is not a signal"));
2509    };
2510
2511    let mut data = SsSignalParamData { id: std::ptr::null(), value_type: SS_SIGNAL_VALUE_NONE, bool_value: false, int_value: 0, float_value: 0.0, text: std::ptr::null() };
2512    let mut text = "";
2513    match &p.value {
2514        SignalValue::Bool(b) => {
2515            data.value_type = SS_SIGNAL_VALUE_BOOL;
2516            data.bool_value = *b;
2517        }
2518        SignalValue::Index(i) => {
2519            data.value_type = SS_SIGNAL_VALUE_INDEX;
2520            data.int_value = *i;
2521        }
2522        SignalValue::Integer(i) => {
2523            data.value_type = SS_SIGNAL_VALUE_INTEGER;
2524            data.int_value = *i;
2525        }
2526        SignalValue::Floating(f) => {
2527            data.value_type = SS_SIGNAL_VALUE_FLOATING;
2528            data.float_value = *f;
2529        }
2530        SignalValue::Text(t) => {
2531            data.value_type = SS_SIGNAL_VALUE_TEXT;
2532            text = t;
2533        }
2534        SignalValue::None => {}
2535    }
2536
2537    data.id = param_id_scratch.set(&p.id);
2538    data.text = param_text_scratch.set(text);
2539    unsafe { out.write(data) };
2540    SS_OK
2541}
2542
2543/// Write the part's current-frame transform into `out` as the 2D affine
2544/// `[m00, m01, m10, m11, tx, ty]`, in animation-local (Y-down) space with
2545/// neither `ss_player_set_transform` nor the scene's projection applied. A point
2546/// maps as `x' = m00*x + m01*y + tx`, `y' = m10*x + m11*y + ty`.
2547///
2548/// Returns `SS_OK`, or `SS_ERROR_INVALID_ARGUMENT` when the handle or `out` is
2549/// null, no animation is set up, or `part` is out of range — `out` is untouched
2550/// in that case.
2551///
2552/// Call it after `ss_scene_update`: it describes the frame that produced. The
2553/// matrix exists for every part whether or not it is hidden, so a hidden part
2554/// still reports where it would have been.
2555///
2556/// # Safety
2557/// `handle` must be a live handle or null; `out` must point at 6 writable
2558/// `float`s.
2559#[unsafe(no_mangle)]
2560pub unsafe extern "C" fn ss_player_part_transform_by_index(handle: *mut SsPlayer, part: u32, out: *mut f32) -> i32 {
2561    if out.is_null() {
2562        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
2563    }
2564    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2565    let Some(m) = player.part_transform_by_index(part) else {
2566        return fail(SS_ERROR_INVALID_ARGUMENT, format!("part {part} is out of range, or no animation is set up"));
2567    };
2568    unsafe { std::ptr::copy_nonoverlapping(m.as_ptr(), out, 6) };
2569    SS_OK
2570}
2571
2572/// How many animations the main pack holds (0 if nothing is loaded).
2573///
2574/// # Safety
2575/// `handle` must be a live handle or null.
2576#[unsafe(no_mangle)]
2577pub unsafe extern "C" fn ss_player_animation_count(handle: *mut SsPlayer) -> u32 {
2578    unsafe { player(handle) }.and_then(|p| p.animation_names()).map(|names| names.len() as u32).unwrap_or(0)
2579}
2580
2581/// The `index`-th animation name of the main pack, or null if out of range.
2582///
2583/// The string is owned by the scene and stays valid until the next call to this
2584/// function on the same scene. Copy it if you need to keep it.
2585///
2586/// # Safety
2587/// `handle` must be a live handle or null.
2588#[unsafe(no_mangle)]
2589pub unsafe extern "C" fn ss_player_animation_name(handle: *mut SsPlayer, index: u32) -> *const c_char {
2590    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
2591        set_last_error("player handle is null or destroyed");
2592        return std::ptr::null();
2593    };
2594    let Some(name) = scene.host.player_mut(id).and_then(|p| p.animation_names()).and_then(|names| names.into_iter().nth(index as usize)) else {
2595        set_last_error(format!("no animation at index {index}"));
2596        return std::ptr::null();
2597    };
2598    lend_name(&mut scene.name_scratch, name, "animation name")
2599}
2600
2601/// Hand `name` to C through `scratch`, which owns it until the next call that
2602/// refills the same buffer. Null, with `ss_last_error` set, when the name holds
2603/// an interior NUL — no C string can carry one.
2604fn lend_name(scratch: &mut CString, name: String, what: &str) -> *const c_char {
2605    match CString::new(name) {
2606        Ok(name) => {
2607            *scratch = name;
2608            scratch.as_ptr()
2609        }
2610        Err(_) => {
2611            set_last_error(format!("{what} contains an interior NUL"));
2612            std::ptr::null()
2613        }
2614    }
2615}
2616
2617/// The animation currently set up, or null before the first
2618/// `ss_player_set_animation` and again after a load replaced the pack. No
2619/// animation is not a failure, so that null leaves `ss_last_error` alone.
2620///
2621/// The string stays valid until the next call to this function on the same
2622/// scene. Copy it if you need to keep it.
2623///
2624/// # Safety
2625/// `handle` must be a live handle or null.
2626#[unsafe(no_mangle)]
2627pub unsafe extern "C" fn ss_player_current_animation(handle: *mut SsPlayer) -> *const c_char {
2628    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
2629        set_last_error("player handle is null or destroyed");
2630        return std::ptr::null();
2631    };
2632    let Some(name) = scene.host.player_mut(id).and_then(|p| p.current_animation().map(str::to_owned)) else {
2633        return std::ptr::null();
2634    };
2635    lend_name(&mut scene.current_scratch, name, "animation name")
2636}
2637
2638/// The name of part `index`, in part-index order — what turns the `part_index`
2639/// an event carries back into something a human reads. An unnamed part reads
2640/// as an empty string; null past the last part or with no pack bound.
2641///
2642/// Readable as soon as a pack is bound, while `ss_player_part_count` reads 0
2643/// until an animation is set up: walk it until it returns null. The string
2644/// stays valid until the next call to this function on the same scene.
2645///
2646/// # Safety
2647/// `handle` must be a live handle or null.
2648#[unsafe(no_mangle)]
2649pub unsafe extern "C" fn ss_player_part_name(handle: *mut SsPlayer, index: u32) -> *const c_char {
2650    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
2651        set_last_error("player handle is null or destroyed");
2652        return std::ptr::null();
2653    };
2654    let Some(name) = scene.host.player_mut(id).and_then(|p| p.part_names()).and_then(|names| names.into_iter().nth(index as usize)) else {
2655        set_last_error(format!("no part at index {index}"));
2656        return std::ptr::null();
2657    };
2658    lend_name(&mut scene.part_name_scratch, name, "part name")
2659}
2660
2661/// How many cellmaps the main pack holds (0 if nothing is loaded).
2662///
2663/// # Safety
2664/// `handle` must be a live handle or null.
2665#[unsafe(no_mangle)]
2666pub unsafe extern "C" fn ss_player_cellmap_count(handle: *mut SsPlayer) -> u32 {
2667    unsafe { player(handle) }.and_then(|p| p.cellmap_names()).map(|names| names.len() as u32).unwrap_or(0)
2668}
2669
2670/// The `index`-th cellmap name of the main pack, without the `.ssce`
2671/// extension — the namespace `ss_player_set_part_cell_override` takes. Null if
2672/// out of range.
2673///
2674/// The string stays valid until the next call to this function on the same
2675/// scene, so it can be handed straight to `ss_player_cell_name`.
2676///
2677/// # Safety
2678/// `handle` must be a live handle or null.
2679#[unsafe(no_mangle)]
2680pub unsafe extern "C" fn ss_player_cellmap_name(handle: *mut SsPlayer, index: u32) -> *const c_char {
2681    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
2682        set_last_error("player handle is null or destroyed");
2683        return std::ptr::null();
2684    };
2685    let Some(name) = scene.host.player_mut(id).and_then(|p| p.cellmap_names()).and_then(|names| names.into_iter().nth(index as usize)) else {
2686        set_last_error(format!("no cellmap at index {index}"));
2687        return std::ptr::null();
2688    };
2689    lend_name(&mut scene.cellmap_name_scratch, name, "cellmap name")
2690}
2691
2692/// How many cells `cellmap` holds: 0 when no pack is bound, the cellmap is not
2693/// in it, or `cellmap` is not valid UTF-8.
2694///
2695/// # Safety
2696/// `handle` must be a live handle or null; `cellmap` must be a valid
2697/// null-terminated C string.
2698#[unsafe(no_mangle)]
2699pub unsafe extern "C" fn ss_player_cell_count(handle: *mut SsPlayer, cellmap: *const c_char) -> u32 {
2700    let Some(player) = (unsafe { player(handle) }) else { return 0 };
2701    let Some(cellmap) = (unsafe { c_str(cellmap) }) else { return 0 };
2702    player.cell_names(cellmap).map(|names| names.len() as u32).unwrap_or(0)
2703}
2704
2705/// The `index`-th cell name inside `cellmap` — the other half of what
2706/// `ss_player_set_part_cell_override` takes. Null if out of range, or when the
2707/// cellmap is not in the main pack.
2708///
2709/// The string stays valid until the next call to this function on the same
2710/// scene. Copy it if you need to keep it.
2711///
2712/// # Safety
2713/// `handle` must be a live handle or null; `cellmap` must be a valid
2714/// null-terminated C string.
2715#[unsafe(no_mangle)]
2716pub unsafe extern "C" fn ss_player_cell_name(handle: *mut SsPlayer, cellmap: *const c_char, index: u32) -> *const c_char {
2717    let Some((scene, id)) = (unsafe { scene_of(handle) }) else {
2718        set_last_error("player handle is null or destroyed");
2719        return std::ptr::null();
2720    };
2721    let Some(cellmap) = (unsafe { c_str(cellmap) }) else {
2722        set_last_error("cellmap is null or not valid UTF-8");
2723        return std::ptr::null();
2724    };
2725    let Some(name) = scene.host.player_mut(id).and_then(|p| p.cell_names(cellmap)).and_then(|names| names.into_iter().nth(index as usize)) else {
2726        set_last_error(format!("no cell at index {index} in cellmap {cellmap:?}"));
2727        return std::ptr::null();
2728    };
2729    lend_name(&mut scene.cell_name_scratch, name, "cell name")
2730}
2731
2732// --- placement ------------------------------------------------
2733
2734/// Place this player in its scene: translation in pixels from the centre, scale,
2735/// then rotation in radians.
2736///
2737/// `y` is measured **downward** from the centre, matching the Y-down space the
2738/// players and `ss_player_part_transform` live in.
2739///
2740/// Without this every player sits at the origin, on top of the others.
2741///
2742/// # Safety
2743/// `handle` must be a live handle or null.
2744#[unsafe(no_mangle)]
2745pub unsafe extern "C" fn ss_player_set_transform(handle: *mut SsPlayer, x: f32, y: f32, scale_x: f32, scale_y: f32, rotation: f32) {
2746    if let Some(player) = unsafe { player(handle) } {
2747        player.set_transform(x, y, scale_x, scale_y, rotation);
2748    }
2749}
2750
2751/// Back to the identity placement: centred, unscaled, unrotated.
2752///
2753/// # Safety
2754/// `handle` must be a live handle or null.
2755#[unsafe(no_mangle)]
2756pub unsafe extern "C" fn ss_player_reset_transform(handle: *mut SsPlayer) {
2757    if let Some(player) = unsafe { player(handle) } {
2758        player.reset_transform();
2759    }
2760}
2761
2762/// Fill `out` with the default placement: contain, centred, unscaled,
2763/// unflipped, unrotated, and the animation's own canvas as the box.
2764///
2765/// Start every `ss_placement_t` here. A zeroed struct asks for `scale = 0`, which
2766/// is a placement that draws nothing.
2767///
2768/// # Safety
2769/// `out` must point at a writable `ss_placement_t`.
2770#[unsafe(no_mangle)]
2771pub unsafe extern "C" fn ss_placement_default(out: *mut SsPlacement) -> i32 {
2772    if out.is_null() {
2773        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
2774    }
2775    let default = Placement::default();
2776    unsafe {
2777        out.write(SsPlacement {
2778            fit: SS_FIT_CONTAIN,
2779            align: SS_ALIGN_CENTER,
2780            frame: SsRect::default(),
2781            has_frame: false,
2782            offset_x: default.offset.0,
2783            offset_y: default.offset.1,
2784            scale: default.scale,
2785            flip_x: default.flip_x,
2786            flip_y: default.flip_y,
2787            rotation: default.rotation,
2788        })
2789    };
2790    SS_OK
2791}
2792
2793/// Write the authored canvas of the animation now playing into `out`, as a box
2794/// in player-local units — what `ss_player_fit_into` fits when `has_frame` is
2795/// false.
2796///
2797/// Returns `SS_OK`, or `SS_ERROR_INVALID_ARGUMENT` when the handle or `out` is
2798/// null or no animation is set up — `out` is untouched in that case.
2799///
2800/// The box is the frame the artist composed in, placed against the origin by the
2801/// animation's pivot, not a measured bounding box: it costs nothing to read and
2802/// does not change when the animation does.
2803///
2804/// # Safety
2805/// `handle` must be a live handle or null; `out` must point at a writable
2806/// `ss_rect_t`.
2807#[unsafe(no_mangle)]
2808pub unsafe extern "C" fn ss_player_canvas_rect(handle: *mut SsPlayer, out: *mut SsRect) -> i32 {
2809    if out.is_null() {
2810        return fail(SS_ERROR_INVALID_ARGUMENT, "out is null");
2811    }
2812    let Some(player) = (unsafe { player(handle) }) else {
2813        return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
2814    };
2815    let Some(rect) = player.canvas_rect() else {
2816        return fail(SS_ERROR_INVALID_ARGUMENT, "no animation is set up");
2817    };
2818    unsafe { out.write(SsRect { x: rect.x, y: rect.y, width: rect.width, height: rect.height }) };
2819    SS_OK
2820}
2821
2822/// Fit the animation into a `width` x `height` box and place it there, as
2823/// `ss_player_set_transform` would.
2824///
2825/// `out` may be null; when it is not, it receives the transform that was
2826/// written, so a host can read back the scale it got.
2827///
2828/// Returns `SS_OK`, or `SS_ERROR_INVALID_ARGUMENT` when the handle or
2829/// `placement` is null or `fit` / `align` is not one of the constants. A
2830/// collapsed box and an animation that is not set up are **not** errors: both
2831/// place the player centred and unscaled, which is what a host laying out a box
2832/// that has not been measured yet should get.
2833///
2834/// The size is in pixels of the render target, so call this again when that box
2835/// changes — on a resize, and after `ss_player_set_animation` when the canvas
2836/// differs.
2837///
2838/// # Safety
2839/// `handle` must be a live handle or null; `placement` must point at a readable
2840/// `ss_placement_t`; `out` must be null or point at a writable `ss_placed_t`.
2841#[unsafe(no_mangle)]
2842pub unsafe extern "C" fn ss_player_fit_into(handle: *mut SsPlayer, width: f32, height: f32, placement: *const SsPlacement, out: *mut SsPlaced) -> i32 {
2843    if placement.is_null() {
2844        return fail(SS_ERROR_INVALID_ARGUMENT, "placement is null");
2845    }
2846    let desc = unsafe { *placement };
2847    let Some(fit) = fit_from_wire(desc.fit) else {
2848        return fail(SS_ERROR_INVALID_ARGUMENT, format!("fit {} is not an SS_FIT_* value", desc.fit));
2849    };
2850    let Some(align) = align_from_wire(desc.align) else {
2851        return fail(SS_ERROR_INVALID_ARGUMENT, format!("align {} is not an SS_ALIGN_* value", desc.align));
2852    };
2853    let Some(player) = (unsafe { player(handle) }) else {
2854        return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed");
2855    };
2856    let frame = desc.has_frame.then_some(Rect { x: desc.frame.x, y: desc.frame.y, width: desc.frame.width, height: desc.frame.height });
2857    let placed = player.fit_into(width, height, &Placement { fit, align, frame, offset: (desc.offset_x, desc.offset_y), scale: desc.scale, flip_x: desc.flip_x, flip_y: desc.flip_y, rotation: desc.rotation });
2858    if !out.is_null() {
2859        unsafe { out.write(SsPlaced { x: placed.x, y: placed.y, scale_x: placed.scale_x, scale_y: placed.scale_y }) };
2860    }
2861    SS_OK
2862}
2863
2864/// `SS_FIT_*` to the Rust enum. `None` for anything else, which the caller turns
2865/// into `SS_ERROR_INVALID_ARGUMENT` rather than guessing at a default.
2866fn fit_from_wire(fit: u32) -> Option<Fit> {
2867    match fit {
2868        SS_FIT_CONTAIN => Some(Fit::Contain),
2869        SS_FIT_COVER => Some(Fit::Cover),
2870        SS_FIT_NONE => Some(Fit::None),
2871        _ => None,
2872    }
2873}
2874
2875/// `SS_ALIGN_*` to the Rust enum. See [`fit_from_wire`] on the `None`.
2876fn align_from_wire(align: u32) -> Option<Align> {
2877    match align {
2878        SS_ALIGN_CENTER => Some(Align::Center),
2879        SS_ALIGN_TOP => Some(Align::Top),
2880        SS_ALIGN_BOTTOM => Some(Align::Bottom),
2881        SS_ALIGN_LEFT => Some(Align::Left),
2882        SS_ALIGN_RIGHT => Some(Align::Right),
2883        SS_ALIGN_TOP_LEFT => Some(Align::TopLeft),
2884        SS_ALIGN_TOP_RIGHT => Some(Align::TopRight),
2885        SS_ALIGN_BOTTOM_LEFT => Some(Align::BottomLeft),
2886        SS_ALIGN_BOTTOM_RIGHT => Some(Align::BottomRight),
2887        _ => None,
2888    }
2889}
2890
2891/// Draw order within the scene; lower draws first. The order among equal values
2892/// is not guaranteed, so give players that overlap distinct orders.
2893///
2894/// # Safety
2895/// `handle` must be a live handle or null.
2896#[unsafe(no_mangle)]
2897pub unsafe extern "C" fn ss_player_set_order(handle: *mut SsPlayer, order: i32) {
2898    if let Some(player) = unsafe { player(handle) } {
2899        player.set_order(order);
2900    }
2901}
2902
2903/// The draw order `ss_player_set_order` set; `0` for a null handle.
2904///
2905/// # Safety
2906/// `handle` must be a live handle or null.
2907#[unsafe(no_mangle)]
2908pub unsafe extern "C" fn ss_player_order(handle: *mut SsPlayer) -> i32 {
2909    unsafe { player(handle) }.map(|p| p.order()).unwrap_or(0)
2910}
2911
2912/// Draw nothing when `false`, while the timeline keeps running: the playhead
2913/// advances and events are reported, so hiding a character for a moment does not
2914/// slow it down. Use `ss_player_set_culled` to stop paying for a player that
2915/// cannot be seen at all.
2916///
2917/// # Safety
2918/// `handle` must be a live handle or null.
2919#[unsafe(no_mangle)]
2920pub unsafe extern "C" fn ss_player_set_visible(handle: *mut SsPlayer, visible: bool) {
2921    if let Some(player) = unsafe { player(handle) } {
2922        player.set_visible(visible);
2923    }
2924}
2925
2926/// Whether the player draws, as `ss_player_set_visible` set it; `true` for a
2927/// null handle.
2928///
2929/// # Safety
2930/// `handle` must be a live handle or null.
2931#[unsafe(no_mangle)]
2932pub unsafe extern "C" fn ss_player_is_visible(handle: *mut SsPlayer) -> bool {
2933    unsafe { player(handle) }.map(|p| p.is_visible()).unwrap_or(true)
2934}
2935
2936/// Skip this player entirely when `true`: its timeline does not advance and it
2937/// produces no geometry, and the time spent culled is dropped. For a player the
2938/// caller knows cannot be seen; use `ss_player_set_visible(false)` to hide one
2939/// that should keep playing.
2940///
2941/// # Safety
2942/// `handle` must be a live handle or null.
2943#[unsafe(no_mangle)]
2944pub unsafe extern "C" fn ss_player_set_culled(handle: *mut SsPlayer, culled: bool) {
2945    if let Some(player) = unsafe { player(handle) } {
2946        player.set_culled(culled);
2947    }
2948}
2949
2950/// Whether the player is culled, as `ss_player_set_culled` set it; `false` for a
2951/// null handle.
2952///
2953/// # Safety
2954/// `handle` must be a live handle or null.
2955#[unsafe(no_mangle)]
2956pub unsafe extern "C" fn ss_player_is_culled(handle: *mut SsPlayer) -> bool {
2957    unsafe { player(handle) }.map(|p| p.is_culled()).unwrap_or(false)
2958}
2959
2960/// Player-level fade, clamped to 0..1. Mask coverage is unaffected: a faded
2961/// player clips exactly as it would at full opacity.
2962///
2963/// Part by part, so overlapping parts read more opaque than `alpha`, unless the
2964/// scene fades each player as one layer (`ss_scene_set_group_alpha`).
2965///
2966/// # Safety
2967/// `handle` must be a live handle or null.
2968#[unsafe(no_mangle)]
2969pub unsafe extern "C" fn ss_player_set_alpha(handle: *mut SsPlayer, alpha: f32) {
2970    if let Some(player) = unsafe { player(handle) } {
2971        player.set_alpha(alpha);
2972    }
2973}
2974
2975/// Draw this one playhead `count` times, once at each member's placement: a crowd
2976/// that costs one player's evaluation and draw calls, however large. `count` 0
2977/// draws the player once again, where `ss_player_set_transform` put it. The
2978/// members are copied; `members` may be null when `count` is 0.
2979///
2980/// Everything else is shared: the frame, the events (reported once), the masks
2981/// and the effects. Each draw is issued for every member in turn, so where two
2982/// members overlap their parts interleave, and this face's stencil masks clip
2983/// correctly only where members do not overlap.
2984///
2985/// `SS_ERROR_INVALID_ARGUMENT` for a null or destroyed handle, a null `members`
2986/// with a `count`, or a `count` past `SS_MAX_CROWD_MEMBERS`; the crowd is left
2987/// as it was.
2988///
2989/// # Safety
2990/// `members` must be null or point at `count` readable `ss_crowd_member_t`s.
2991#[unsafe(no_mangle)]
2992pub unsafe extern "C" fn ss_player_set_crowd(handle: *mut SsPlayer, members: *const SsCrowdMember, count: u32) -> i32 {
2993    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
2994    if count > SS_MAX_CROWD_MEMBERS {
2995        return fail(SS_ERROR_INVALID_ARGUMENT, format!("a crowd of {count} is past SS_MAX_CROWD_MEMBERS ({SS_MAX_CROWD_MEMBERS})"));
2996    }
2997    let members = match (members.is_null(), count) {
2998        (_, 0) => &[][..],
2999        (true, _) => return fail(SS_ERROR_INVALID_ARGUMENT, "members is null"),
3000        (false, _) => unsafe { std::slice::from_raw_parts(members, count as usize) },
3001    };
3002    player.set_crowd_from(members.iter().map(|m| CrowdMember { x: m.x, y: m.y, scale_x: m.scale_x, scale_y: m.scale_y, rotation: m.rotation, alpha: m.alpha, tint: m.tint }));
3003    SS_OK
3004}
3005
3006/// How many members `ss_player_set_crowd` last gave the player; 0 when it draws
3007/// once, and for a null handle.
3008///
3009/// # Safety
3010/// `handle` must be a live handle or null.
3011#[unsafe(no_mangle)]
3012pub unsafe extern "C" fn ss_player_crowd_count(handle: *mut SsPlayer) -> u32 {
3013    unsafe { player(handle) }.map(|p| p.crowd().len() as u32).unwrap_or(0)
3014}
3015
3016/// The player-level fade in effect, after `ss_player_set_alpha` clamped it to
3017/// 0..1; `1` for a null handle.
3018///
3019/// # Safety
3020/// `handle` must be a live handle or null.
3021#[unsafe(no_mangle)]
3022pub unsafe extern "C" fn ss_player_alpha(handle: *mut SsPlayer) -> f32 {
3023    unsafe { player(handle) }.map(|p| p.alpha()).unwrap_or(1.0)
3024}
3025
3026/// Player-level tint, `0xRRGGBB`, multiplied into every part after the PartColor
3027/// blend. `0xFFFFFF` — the default — leaves colours untouched. Mask coverage is
3028/// unaffected, as with `ss_player_set_alpha`.
3029///
3030/// # Safety
3031/// `handle` must be a live handle or null.
3032#[unsafe(no_mangle)]
3033pub unsafe extern "C" fn ss_player_set_tint(handle: *mut SsPlayer, rgb: u32) {
3034    if let Some(player) = unsafe { player(handle) } {
3035        player.set_tint(rgb);
3036    }
3037}
3038
3039/// The player-level tint as `0xRRGGBB`; `0xFFFFFF` for a null handle.
3040///
3041/// # Safety
3042/// `handle` must be a live handle or null.
3043#[unsafe(no_mangle)]
3044pub unsafe extern "C" fn ss_player_tint(handle: *mut SsPlayer) -> u32 {
3045    unsafe { player(handle) }.map(|p| p.tint()).unwrap_or(0x00FF_FFFF)
3046}
3047
3048/// Canvas size of the animation currently playing. Either out-pointer may be null.
3049///
3050/// # Safety
3051/// `width` / `height` must be null or point at writable `float`s.
3052#[unsafe(no_mangle)]
3053pub unsafe extern "C" fn ss_player_canvas_size(handle: *mut SsPlayer, width: *mut f32, height: *mut f32) -> i32 {
3054    let Some(player) = (unsafe { player(handle) }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "player handle is null or destroyed") };
3055    let Some((w, h)) = player.canvas_size() else { return fail(SS_ERROR_INVALID_ARGUMENT, "no animation is playing") };
3056    if let Some(out) = unsafe { width.as_mut() } {
3057        *out = w;
3058    }
3059    if let Some(out) = unsafe { height.as_mut() } {
3060        *out = h;
3061    }
3062    SS_OK
3063}
3064
3065// --- per frame ------------------------------------------------------------
3066
3067/// Advance every player in the scene by `delta_seconds` and build this frame's
3068/// GPU buffers. Call once per frame, before `ss_scene_render`.
3069///
3070/// # Safety
3071/// `scene` must be a live handle or null.
3072#[unsafe(no_mangle)]
3073pub unsafe extern "C" fn ss_scene_update(scene: *mut SsScene, delta_seconds: f32) {
3074    if let Some(scene) = unsafe { scene.as_mut() } {
3075        scene.host.update(delta_seconds);
3076    }
3077}
3078
3079/// Acquire the swapchain image, draw the prepared frame into it, and present.
3080///
3081/// One pass covers every player, in ascending `ss_player_set_order`.
3082///
3083/// A lost/outdated surface is absorbed by reconfiguring: the call
3084/// returns `SS_OK` having skipped one frame.
3085///
3086/// # Safety
3087/// `scene` must be a live handle or null.
3088#[unsafe(no_mangle)]
3089pub unsafe extern "C" fn ss_scene_render(scene: *mut SsScene) -> i32 {
3090    let Some(scene) = (unsafe { scene.as_mut() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "scene is null") };
3091    match scene.host.render() {
3092        Ok(()) => SS_OK,
3093        Err(msg) => fail(SS_ERROR_GPU, msg),
3094    }
3095}
3096
3097/// What the last frame cost. Writes `out` and returns
3098/// `SS_OK`, or leaves it untouched and reports the reason.
3099///
3100/// # Safety
3101/// `out` must point at a writable `ss_scene_stats_t`.
3102#[unsafe(no_mangle)]
3103pub unsafe extern "C" fn ss_scene_stats(scene: *mut SsScene, out: *mut SsSceneStats) -> i32 {
3104    let Some(scene) = (unsafe { scene.as_ref() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "scene is null") };
3105    let Some(out) = (unsafe { out.as_mut() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "out is null") };
3106    let stats = scene.host.stats();
3107    *out = SsSceneStats { players: stats.players, prims: stats.prims, draw_calls: stats.draw_calls, group_layers: stats.group_layers, uploaded_bytes: stats.uploaded_bytes, gpu_pass_time_ns: stats.gpu_pass_time_ns.unwrap_or(0) };
3108    SS_OK
3109}
3110
3111/// Fade each player whose alpha is below 1 as one layer, composited at its
3112/// alpha, rather than part by part — so overlapping parts of a half-faded
3113/// character read half, not three quarters. Off by default.
3114///
3115/// Each player faded at once costs a render pass per frame and a layer the size
3116/// of the window (about 8 MiB at 1920x1080), counted in
3117/// `ss_scene_stats_t::group_layers`; turning it off frees them. Inside a layer
3118/// the parts blend against transparency rather than the window: Add, Mul and
3119/// Screen parts composite with the player's own parts alone. Kept across
3120/// `ss_scene_restore_device`.
3121///
3122/// # Safety
3123/// `scene` must be a live handle or null.
3124#[unsafe(no_mangle)]
3125pub unsafe extern "C" fn ss_scene_set_group_alpha(scene: *mut SsScene, on: bool) {
3126    if let Some(scene) = unsafe { scene.as_mut() } {
3127        scene.host.set_group_alpha(on);
3128    }
3129}
3130
3131/// Whether `ss_scene_set_group_alpha` is on; `false` for a null scene.
3132///
3133/// # Safety
3134/// `scene` must be a live handle or null.
3135#[unsafe(no_mangle)]
3136pub unsafe extern "C" fn ss_scene_group_alpha(scene: *mut SsScene) -> bool {
3137    unsafe { scene.as_ref() }.is_some_and(|s| s.host.group_alpha())
3138}
3139
3140/// Resize the swapchain, the depth/stencil buffer and the projection to a new
3141/// drawable size in **pixels**. Zero in either dimension is ignored, and a size
3142/// past the device's `max_texture_dimension_2d` draws at that limit.
3143///
3144/// # Safety
3145/// `scene` must be a live handle or null.
3146#[unsafe(no_mangle)]
3147pub unsafe extern "C" fn ss_scene_resize(scene: *mut SsScene, width: u32, height: u32) {
3148    if let Some(scene) = unsafe { scene.as_mut() } {
3149        scene.host.resize(width, height);
3150    }
3151}
3152
3153/// Whether the driver has taken the GPU device away. False for a null
3154/// scene. While this is true `ss_scene_update` / `ss_scene_render` do nothing and
3155/// `ss_scene_resize` only records the size.
3156///
3157/// # Safety
3158/// `scene` must be a live handle or null.
3159#[unsafe(no_mangle)]
3160pub unsafe extern "C" fn ss_scene_is_device_lost(scene: *mut SsScene) -> bool {
3161    unsafe { scene.as_ref() }.is_some_and(|s| s.host.is_device_lost())
3162}
3163
3164/// Rebuild the GPU stack after a device loss and restore every player drawing into
3165/// this window, resuming playback where it was interrupted.
3166///
3167/// `SS_ERROR_GPU` means the window has to be rebuilt from `ss_scene_create`.
3168///
3169/// # Safety
3170/// `scene` must be a live handle or null.
3171#[unsafe(no_mangle)]
3172pub unsafe extern "C" fn ss_scene_restore_device(scene: *mut SsScene) -> i32 {
3173    let Some(scene) = (unsafe { scene.as_mut() }) else { return fail(SS_ERROR_INVALID_ARGUMENT, "scene is null") };
3174    match scene.host.restore_device() {
3175        Ok(()) => SS_OK,
3176        Err(msg) => fail(SS_ERROR_GPU, msg),
3177    }
3178}
3179
3180#[cfg(test)]
3181mod tests {
3182    use super::*;
3183
3184    #[test]
3185    fn the_version_strings_are_the_crate_constants_as_c_strings() {
3186        // SAFETY: both return a pointer to a static, NUL-terminated string.
3187        let (version, sdk) = unsafe { (CStr::from_ptr(ss_version()), CStr::from_ptr(ss_sdk_version())) };
3188        assert_eq!(version.to_str(), Ok(crate::VERSION));
3189        assert_eq!(sdk.to_str(), Ok(crate::SDK_VERSION));
3190    }
3191
3192    /// The string slots hand C a pointer rather than a copy, so what is behind it
3193    /// has to be NUL-terminated and has to stay put until the next call on that
3194    /// slot. Neither half is visible from the C side until something reads past
3195    /// the end, and the reuse is what keeps `ss_player_event_at` from allocating
3196    /// once per event per frame — a `CString` field cannot be refilled, only
3197    /// replaced.
3198    ///
3199    /// Everything else in this module needs a window and a device, so this is the
3200    /// one thing here a test can reach.
3201    #[test]
3202    fn a_refilled_slot_stays_a_valid_c_string() {
3203        let mut slot = CScratch::default();
3204
3205        assert_eq!(unsafe { CStr::from_ptr(slot.set("OnFootstep")) }.to_str().unwrap(), "OnFootstep");
3206        assert_eq!(unsafe { CStr::from_ptr(slot.set("")) }.to_bytes(), b"");
3207
3208        // An interior NUL comes back empty: the tail past a NUL cannot reach C,
3209        // and handing over the head alone would be a different string wearing the
3210        // right name.
3211        assert_eq!(unsafe { CStr::from_ptr(slot.set("bad\0tail")) }.to_bytes(), b"");
3212
3213        // A shorter refill reuses the buffer instead of allocating a new one,
3214        // which is the whole reason this type exists rather than a `CString`.
3215        let long = slot.set("a-command-id-considerably-longer-than-the-next-one");
3216        let short = slot.set("x");
3217        assert_eq!(long.addr(), short.addr(), "the slot was reallocated instead of refilled");
3218        assert_eq!(unsafe { CStr::from_ptr(short) }.to_str().unwrap(), "x");
3219    }
3220
3221    /// A null handle reads as a freshly created player, so a caller that skips
3222    /// the null check sees the defaults rather than a value that hides something.
3223    #[test]
3224    fn placement_reads_on_a_null_handle_are_the_defaults() {
3225        let null = std::ptr::null_mut();
3226        let fresh = crate::SSPlayer::new();
3227        unsafe {
3228            assert_eq!(ss_player_is_visible(null), fresh.is_visible());
3229            assert_eq!(ss_player_is_culled(null), fresh.is_culled());
3230            assert_eq!(ss_player_alpha(null), fresh.alpha());
3231            assert_eq!(ss_player_order(null), fresh.order());
3232            assert_eq!(ss_player_tint(null), fresh.tint());
3233            assert_eq!(ss_player_crowd_count(null), fresh.crowd().len() as u32);
3234            assert!(!ss_scene_group_alpha(std::ptr::null_mut()), "a fresh scene fades part by part");
3235            // Setting one fails rather than doing nothing, as the track commands do.
3236            assert_eq!(ss_player_set_crowd(null, std::ptr::null(), 0), SS_ERROR_INVALID_ARGUMENT);
3237        }
3238    }
3239
3240    /// A track or source read that has nothing to read answers what the section
3241    /// comment promises: 0, except the two reads where 0 is a real answer. A
3242    /// command fails rather than doing nothing.
3243    #[test]
3244    fn track_reads_with_nothing_to_read_answer_the_documented_values() {
3245        let null = std::ptr::null_mut();
3246        let name = c"walk";
3247        unsafe {
3248            assert_eq!(ss_player_track_count(null), 0);
3249            assert_eq!(ss_player_track_alpha(null, 0), 0.0);
3250            assert_eq!(ss_player_track_frame(null, 0), 0.0);
3251            assert_eq!(ss_player_track_blend(null, 0), SS_TRACK_BLEND_MIX);
3252            assert_eq!(ss_player_track_sync(null, 0), SS_TRACK_SYNC_FREE);
3253            assert_eq!(ss_player_track_fade_progress(null, 0), -1.0, "0 would read as a fade just started");
3254            assert_eq!(ss_player_track_main_source(null, 0), SS_INVALID_SOURCE, "0 would read as a handle");
3255            assert_eq!(ss_player_source_weight(null, 0), 0.0);
3256            assert_eq!(ss_player_source_frame(null, 0), 0.0);
3257            assert_eq!(ss_player_source_event_threshold(null, 0), 0.0);
3258            assert_eq!(ss_player_track_speed(null, 0), 0.0);
3259            assert_eq!(ss_player_track_frame_rate(null, 0), 0);
3260            assert!(!ss_player_track_frame_skip_enabled(null, 0));
3261            assert_eq!((ss_player_track_playback_direction(null, 0), ss_player_track_playback_style(null, 0)), (0, 0));
3262            assert_eq!(ss_player_track_loop_count(null, 0), 0, "no animation reads back a count of 0");
3263            assert!(!ss_player_is_track_finished(null, 0) && !ss_player_track_just_looped(null, 0));
3264            assert_eq!(ss_player_track_outgoing_event_threshold(null, 0), 0.0);
3265
3266            assert_eq!(ss_player_set_track_frame_rate(null, 0, 24), SS_ERROR_INVALID_ARGUMENT);
3267            assert_eq!(ss_player_set_track_frame_skip_enabled(null, 0, false), SS_ERROR_INVALID_ARGUMENT);
3268            assert_eq!(ss_player_set_track_playback_direction(null, 0, 1, 1), SS_ERROR_INVALID_ARGUMENT);
3269            assert_eq!(ss_player_set_track_loop_count(null, 0, 1), SS_ERROR_INVALID_ARGUMENT);
3270            assert_eq!(ss_player_set_track_outgoing_event_threshold(null, 0, 0.5), SS_ERROR_INVALID_ARGUMENT);
3271            assert_eq!(ss_player_set_track_animation(null, 1, name.as_ptr()), SS_ERROR_INVALID_ARGUMENT);
3272            assert_eq!(ss_player_crossfade(null, 0, name.as_ptr(), 100.0), SS_ERROR_INVALID_ARGUMENT);
3273            assert_eq!(ss_player_set_track_sync(null, 0, SS_TRACK_SYNC_START), SS_ERROR_INVALID_ARGUMENT);
3274            let mut source = 7;
3275            assert_eq!(ss_player_add_track_source(null, 0, name.as_ptr(), 1.0, &mut source), SS_ERROR_INVALID_ARGUMENT);
3276            assert_eq!(source, 7, "out_source is untouched on failure");
3277            assert_eq!(ss_player_add_track_source(null, 0, name.as_ptr(), 1.0, std::ptr::null_mut()), SS_ERROR_INVALID_ARGUMENT);
3278        }
3279    }
3280}