Skip to main content

ssplayer_wgpu/
web.rs

1//! The "js" face: a `wasm-bindgen` wrapper that renders SpriteStudio
2//! animations to HTML canvases via **WebGPU**.
3//!
4//! This module is the host: it owns the wgpu stack (instance / adapter / device
5//! / queue / surfaces) and lends device and queue to [`SSScene`] and
6//! [`SSPlayer`] each frame, driven by JS `requestAnimationFrame`.
7//!
8//! Three objects, one per resource scope:
9//!
10//! ```text
11//! SsContextWeb one per page device + queue + SSRenderer (pipelines, atlases)
12//! SsSurfaceWeb one per canvas wgpu::Surface + SSScene (projection, arena)
13//! SsPlayerWeb any number SSPlayer (playback tree only)
14//! ```
15//!
16//! **The device is asked for once and every canvas shares it.** Requesting one
17//! per canvas would build N `GPUDevice`s for a page of N elements and re-upload
18//! the same atlas into each, since nothing is shared across devices.
19//!
20//! Everything lives in one `Rc<RefCell<WebContext>>` and the exported types are
21//! generation-tagged handles into it ([`crate::roster`]), for the reason the C
22//! face has the same design: JS cannot hold a Rust `&mut`, and a
23//! stale handle must resolve to "destroyed" rather than to its successor. One
24//! cell rather than one per object means no borrow can be held across another.
25//!
26//! Embedded ssab is the natural web form: the atlas PNGs ride inside
27//! the `.ssab`, so a single fetched file needs no sibling image files. **The
28//! decoding of those PNGs is the browser's job here, not the player's** — the
29//! `web` feature carries no image decoder, because one is already installed on
30//! every page. [`SsPlayerWeb::embedded_textures`] hands out the encoded bytes and
31//! [`SsContextWeb::add_texture_from_bytes`] runs them through `createImageBitmap`.
32
33use crate::events::{SignalValue, SsEvent};
34use crate::fit::{Align, Fit, Placement, Rect};
35use crate::pack::SSPack;
36use crate::player::{AssetLoader, BlendOp, CrowdMember, MAX_CROWD_MEMBERS, MissingKind, OverridePriority, PlaybackDirection, PlaybackStyle, SSPlayer};
37use crate::renderer::{AlphaMode, Retention, SSRenderer, texture_extent_error};
38use crate::roster::{Roster, Slot, SlotId};
39use crate::scene::{MaskBackend, SSScene, SceneConfig};
40use crate::surface::{STENCIL_FORMAT, Swapchain};
41use std::cell::{Cell, RefCell};
42use std::collections::HashMap;
43use std::rc::Rc;
44use std::sync::Arc;
45use std::sync::atomic::{AtomicBool, Ordering};
46use wasm_bindgen::prelude::*;
47
48/// Why a texture-override call on `player` names nothing it can replace.
49fn unreplaceable(player: &SSPlayer, pack: Option<&str>, name: &str) -> JsValue {
50    if player.replaceable_cellmap_names(None).is_none() {
51        return js_error("no pack is loaded");
52    }
53    let pack = pack.map_or_else(|| "the selected pack".to_string(), |pack| format!("pack \"{pack}\""));
54    js_error(format!("{pack} has no cellmap or texture named \"{name}\""))
55}
56
57/// A JS `Error` carrying `message`, which is what every rejection and throw of
58/// this face is, so a page's `catch` gets a stack and `e.message`.
59fn js_error(message: impl AsRef<str>) -> JsValue {
60    js_sys::Error::new(message.as_ref()).into()
61}
62
63/// Map a runtime error into a JS `Error`, worded for a person.
64fn js_err<E: core::fmt::Display>(e: E) -> JsValue {
65    js_error(e.to_string())
66}
67
68/// The error a handle raises once the thing it names is gone. Not a panic: JS
69/// keeps references alive in closures and event listeners, so a call arriving
70/// after `destroy()` is ordinary rather than exceptional.
71fn gone(what: &str) -> JsValue {
72    js_error(format!("this {what} has been destroyed"))
73}
74
75/// How a canvas composites with the page behind it.
76///
77/// **Premultiplied, always.** A canvas on a page is a box in a layout, not a
78/// window: the transparent parts of a frame have to let the page through, or an
79/// element dropped onto a coloured card is a black rectangle over it. Nothing is
80/// converted for this — the whole pipeline already produces premultiplied pixels,
81/// which is also why `createImageBitmap` is asked for premultiplied bitmaps.
82///
83/// Not read off `SurfaceCapabilities`: wgpu's WebGPU backend reports `[Opaque]`
84/// there and accepts `PreMultiplied` in `configure` anyway, mapping it onto the
85/// canvas context's `alphaMode: "premultiplied"`, so picking the first reported
86/// mode would make every element an opaque box.
87const PAGE_ALPHA_MODE: wgpu::CompositeAlphaMode = wgpu::CompositeAlphaMode::PreMultiplied;
88
89/// Decode encoded image bytes (PNG) with **the browser's** decoder.
90///
91/// `createImageBitmap` decodes off the main thread and premultiplies on the way,
92/// which is why the web face ships no decoder of its own: `image` would cost wasm
93/// size to do the same job worse, on the main thread. The premultiply matters as
94/// much as the decode — the whole pipeline composites premultiplied,
95/// and this is the WebGPU equivalent of the WebGL player's
96/// `UNPACK_PREMULTIPLY_ALPHA_WEBGL` (`SSWebGLResourceManager.createTextureFromSource`).
97async fn decode_image(bytes: &[u8]) -> Result<web_sys::ImageBitmap, JsValue> {
98    let window = web_sys::window().ok_or_else(|| js_error("no `window` (this face needs a document)"))?;
99    let parts = js_sys::Array::new();
100    parts.push(&js_sys::Uint8Array::from(bytes));
101    let blob = web_sys::Blob::new_with_u8_array_sequence(parts.as_ref())?;
102
103    let options = web_sys::ImageBitmapOptions::new();
104    options.set_premultiply_alpha(web_sys::PremultiplyAlpha::Premultiply);
105    let promise = window.create_image_bitmap_with_blob_and_image_bitmap_options(&blob, &options)?;
106
107    wasm_bindgen_futures::JsFuture::from(promise).await?.dyn_into::<web_sys::ImageBitmap>().map_err(|_| js_error("createImageBitmap did not return an ImageBitmap"))
108}
109
110/// Report a recoverable problem: one missing atlas or sub-pack should cost you
111/// that one thing, not the character.
112fn warn(message: &str) {
113    web_sys::console::warn_1(&JsValue::from_str(message));
114}
115
116/// The absolute URL relative references are resolved against: whatever base is in
117/// force, or the document's base URL (`document.baseURI`, which honours a
118/// `<base href>`) when there is none.
119///
120/// A base is resolved against the page because it may itself be relative — a host
121/// calling `loadSsab(bytes, null, 'assets/overall/')` is giving a page-relative
122/// directory, and `URL(relative, base)` requires an absolute base.
123///
124/// An absolute base is taken **without consulting the document**, so a host that
125/// supplied a full URL is served even where there is no document to resolve
126/// against. Only a relative one needs the page, and only then is its absence a
127/// reason to give up — which is what the caller's warning goes on to say.
128fn resolved_base(base_url: Option<&str>) -> Option<String> {
129    let document = || web_sys::window()?.document()?.base_uri().ok().flatten();
130    match base_url {
131        Some(base) => match web_sys::Url::new(base) {
132            Ok(url) => Some(url.href()),
133            Err(_) => Some(web_sys::Url::new_with_base(base, &document()?).ok()?.href()),
134        },
135        None => document(),
136    }
137}
138
139/// `url` resolved against the base in force, into something `fetch` can take.
140fn absolute_url(url: &str, base_url: Option<&str>) -> Option<String> {
141    Some(web_sys::Url::new_with_base(url, &resolved_base(base_url)?).ok()?.href())
142}
143
144/// Fetch every path **once**, in parallel, resolved against `base_url` (or the
145/// document's URL).
146///
147/// Used for both of the things a pack asks the host to go and get: its atlases
148/// and the sibling `.ssab`s its instance parts play from.
149///
150/// One request per path rather than per requester: `external_textures()` can
151/// name an image a cellmap already named, under a different hash, and two packs
152/// can reference a third — neither must become two downloads. `allSettled`
153/// rather than `all` so a single 404 costs one file instead of every file.
154async fn fetch_files(paths: &[String], base_url: Option<&str>) -> HashMap<String, Rc<[u8]>> {
155    let mut out = HashMap::new();
156    let Some(window) = web_sys::window() else {
157        warn("[ssplayer-wgpu] no `window`: nothing can be fetched");
158        return out;
159    };
160    let base = resolved_base(base_url);
161
162    let requests = js_sys::Array::new();
163    let mut ordered: Vec<&String> = Vec::new();
164    for path in paths {
165        let url = match base.as_deref().and_then(|base| web_sys::Url::new_with_base(path, base).ok()) {
166            Some(url) => url.href(),
167            None => {
168                warn(&format!("[ssplayer-wgpu] {path}: cannot resolve against a base URL; pass `baseUrl` to loadSsab"));
169                continue;
170            }
171        };
172        requests.push(&window.fetch_with_str(&url));
173        ordered.push(path);
174    }
175    if ordered.is_empty() {
176        return out;
177    }
178
179    let settled = match wasm_bindgen_futures::JsFuture::from(js_sys::Promise::all_settled(&requests)).await {
180        Ok(value) => js_sys::Array::from(&value),
181        Err(e) => {
182            warn(&format!("[ssplayer-wgpu] fetch failed: {e:?}"));
183            return out;
184        }
185    };
186
187    // Second round: the bodies. `Response` resolving says nothing about the body
188    // having arrived, and `allSettled` again so one truncated response is one
189    // missing atlas.
190    let bodies = js_sys::Array::new();
191    let mut with_body: Vec<&String> = Vec::new();
192    for (i, path) in ordered.iter().enumerate() {
193        let entry = settled.get(i as u32);
194        let value = js_sys::Reflect::get(&entry, &JsValue::from_str("value")).unwrap_or(JsValue::UNDEFINED);
195        let Ok(response) = value.dyn_into::<web_sys::Response>() else {
196            warn(&format!("[ssplayer-wgpu] {path}: fetch rejected"));
197            continue;
198        };
199        if !response.ok() {
200            warn(&format!("[ssplayer-wgpu] {path}: HTTP {}", response.status()));
201            continue;
202        }
203        match response.array_buffer() {
204            Ok(promise) => {
205                bodies.push(&promise);
206                with_body.push(path);
207            }
208            Err(e) => warn(&format!("[ssplayer-wgpu] {path}: {e:?}")),
209        }
210    }
211    if with_body.is_empty() {
212        return out;
213    }
214
215    let settled = match wasm_bindgen_futures::JsFuture::from(js_sys::Promise::all_settled(&bodies)).await {
216        Ok(value) => js_sys::Array::from(&value),
217        Err(e) => {
218            warn(&format!("[ssplayer-wgpu] body read failed: {e:?}"));
219            return out;
220        }
221    };
222    for (i, path) in with_body.iter().enumerate() {
223        let entry = settled.get(i as u32);
224        let value = js_sys::Reflect::get(&entry, &JsValue::from_str("value")).unwrap_or(JsValue::UNDEFINED);
225        match value.dyn_into::<js_sys::ArrayBuffer>() {
226            Ok(buffer) => {
227                out.insert((*path).clone(), Rc::from(js_sys::Uint8Array::new(&buffer).to_vec()));
228            }
229            Err(_) => warn(&format!("[ssplayer-wgpu] {path}: body could not be read")),
230        }
231    }
232    out
233}
234
235#[wasm_bindgen(typescript_custom_section)]
236const ASSET_READER_TS: &str = r#"
237/** One file, as a host reader hands it over: `null` / `undefined` is "not here". */
238export type SsAssetBytes = ArrayBuffer | Uint8Array | Blob | null | undefined;
239/**
240 * Stands in for `fetch` in a load. `url` is absolute, resolved exactly as the
241 * fetch would have been, so a host keys its files by the URL it gave `load`.
242 */
243export type SsAssetReader = (url: string) => SsAssetBytes | Promise<SsAssetBytes>;
244"#;
245
246/// [`fetch_files`] with the host's `read` in place of `fetch`.
247///
248/// For files a page holds but cannot fetch: a dropped folder, an archive it
249/// unpacked. Each path is resolved against `base_url` exactly as a fetch would
250/// be, and `read` is handed that absolute URL. The texture keys are hashed from
251/// the same URLs, so they are as distinct as fetched ones: two folders dropped
252/// under two bases are two sets of images, even when both name `spritemap1.png`.
253///
254/// `read` answers an `ArrayBuffer`, a `Uint8Array` or a `Blob` (a dropped `File`
255/// is one), or a promise of one. `null` / `undefined` means the reader does not
256/// have the file, and the walk reports it the same way as a 404.
257async fn read_files(read: &js_sys::Function, paths: &[String], base_url: Option<&str>) -> HashMap<String, Rc<[u8]>> {
258    let mut out = HashMap::new();
259    let base = resolved_base(base_url);
260
261    let answers = js_sys::Array::new();
262    let mut ordered: Vec<&String> = Vec::new();
263    for path in paths {
264        let url = match base.as_deref().and_then(|base| web_sys::Url::new_with_base(path, base).ok()) {
265            Some(url) => url.href(),
266            None => {
267                warn(&format!("[ssplayer-wgpu] {path}: cannot resolve against a base URL; pass `baseUrl` to loadSsab"));
268                continue;
269            }
270        };
271        // A reader that throws costs that one file, as a rejection does.
272        let answer = match read.call1(&JsValue::NULL, &JsValue::from_str(&url)) {
273            Ok(value) => js_sys::Promise::resolve(&value),
274            Err(e) => js_sys::Promise::reject(&e),
275        };
276        answers.push(&answer);
277        ordered.push(path);
278    }
279    if ordered.is_empty() {
280        return out;
281    }
282
283    let settled = match wasm_bindgen_futures::JsFuture::from(js_sys::Promise::all_settled(&answers)).await {
284        Ok(value) => js_sys::Array::from(&value),
285        Err(e) => {
286            warn(&format!("[ssplayer-wgpu] read failed: {e:?}"));
287            return out;
288        }
289    };
290
291    // Second round, for the Blobs: their bytes are a promise of their own.
292    let bodies = js_sys::Array::new();
293    let mut with_body: Vec<&String> = Vec::new();
294    for (i, path) in ordered.iter().enumerate() {
295        let entry = settled.get(i as u32);
296        let field = |name: &str| js_sys::Reflect::get(&entry, &JsValue::from_str(name)).unwrap_or(JsValue::UNDEFINED);
297        if field("status").as_string().as_deref() == Some("rejected") {
298            warn(&format!("[ssplayer-wgpu] {path}: read rejected: {:?}", field("reason")));
299            continue;
300        }
301        let value = field("value");
302        if value.is_null() || value.is_undefined() {
303            continue;
304        }
305        match value.dyn_ref::<web_sys::Blob>() {
306            Some(blob) => bodies.push(&blob.array_buffer()),
307            None => bodies.push(&js_sys::Promise::resolve(&value)),
308        };
309        with_body.push(path);
310    }
311    if with_body.is_empty() {
312        return out;
313    }
314
315    let settled = match wasm_bindgen_futures::JsFuture::from(js_sys::Promise::all_settled(&bodies)).await {
316        Ok(value) => js_sys::Array::from(&value),
317        Err(e) => {
318            warn(&format!("[ssplayer-wgpu] body read failed: {e:?}"));
319            return out;
320        }
321    };
322    for (i, path) in with_body.iter().enumerate() {
323        let entry = settled.get(i as u32);
324        let value = js_sys::Reflect::get(&entry, &JsValue::from_str("value")).unwrap_or(JsValue::UNDEFINED);
325        let bytes = match value.dyn_ref::<js_sys::ArrayBuffer>() {
326            Some(buffer) => Some(js_sys::Uint8Array::new(buffer).to_vec()),
327            None => value.dyn_ref::<js_sys::Uint8Array>().map(js_sys::Uint8Array::to_vec),
328        };
329        match bytes {
330            Some(bytes) => {
331                out.insert((*path).clone(), Rc::from(bytes));
332            }
333            None => warn(&format!("[ssplayer-wgpu] {path}: the reader answered neither an ArrayBuffer, a Uint8Array nor a Blob")),
334        }
335    }
336    out
337}
338
339/// Request a device and subscribe to its `GPUDevice.lost`. The returned
340/// flag flips when the browser drops the device — which it does on its own schedule
341/// (backgrounded tab, GPU process crash, driver reset), so a long-lived ad creative
342/// has to expect it. Once set, the host is meant to call [`SsContextWeb::restore_device`].
343async fn request_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue, Arc<AtomicBool>), JsValue> {
344    // GPU timing when the browser offers it — Chrome gates
345    // `timestamp-query` behind a flag on some platforms, so this must not be
346    // required, only taken when available.
347    let device_desc = wgpu::DeviceDescriptor { required_features: adapter.features() & wgpu::Features::TIMESTAMP_QUERY, ..Default::default() };
348    let (device, queue) = adapter.request_device(&device_desc).await.map_err(js_err)?;
349    let lost = Arc::new(AtomicBool::new(false));
350    let flag = Arc::clone(&lost);
351    device.set_device_lost_callback(move |_reason, _message| flag.store(true, Ordering::Relaxed));
352    Ok((device, queue, lost))
353}
354
355/// Ask the instance for an adapter.
356///
357/// No `compatible_surface`: the device is page-scoped and is requested before any
358/// canvas exists. A browser exposes one adapter for the page, so pinning it to the
359/// first canvas would constrain nothing and would force surface creation to come first.
360async fn request_adapter(instance: &wgpu::Instance) -> Result<wgpu::Adapter, JsValue> {
361    instance
362        .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: None, force_fallback_adapter: false, apply_limit_buckets: false })
363        .await
364        .map_err(|_| js_error("no WebGPU adapter (this browser/GPU may not support WebGPU)"))
365}
366
367/// One canvas: its swapchain and the scene drawn into it.
368struct SurfaceEntry {
369    /// Always with a stencil buffer: masks rely on one being present.
370    swapchain: Swapchain,
371    scene: SSScene,
372    /// The players drawn into this canvas. The scene borrows them per frame
373    /// rather than owning them, so the owner is the host — here.
374    players: Roster<SSPlayer>,
375}
376
377/// Everything the page owns. One instance behind an `Rc<RefCell<_>>`; the
378/// exported types are handles into it.
379struct WebContext {
380    /// Device-scoped renderer: pipelines, sampler and the atlas
381    /// cache. **Every surface and player on the page shares this one**, so the
382    /// same character in two canvases is uploaded once.
383    renderer: SSRenderer,
384    device: wgpu::Device,
385    queue: wgpu::Queue,
386    surfaces: Roster<SurfaceEntry>,
387    /// Kept so a lost device can be replaced without rebuilding the canvases'
388    /// surfaces (a canvas context outlives the device it was configured with).
389    adapter: wgpu::Adapter,
390    /// Set from `GPUDevice.lost`. While it is set every `frame` is a no-op —
391    /// each GPU object on the page is dead until `restoreDevice`.
392    device_lost: Arc<AtomicBool>,
393    /// The **encoded** bytes behind every texture supplied through
394    /// [`SsContextWeb::add_texture_from_bytes`], kept so a device loss can be
395    /// repaired without the page re-fetching or re-reading anything.
396    ///
397    /// Affordable precisely because they are encoded: a 2048² atlas is a few
398    /// hundred KB here against the 16 MB its pixels would take under
399    /// [`Retention::Retain`].
400    encoded_textures: HashMap<u32, Rc<[u8]>>,
401    /// Kept last: the instance must outlive the surfaces it created.
402    instance: wgpu::Instance,
403}
404
405impl WebContext {
406    /// Build a surface + scene for `canvas`.
407    fn add_surface(&mut self, canvas: web_sys::HtmlCanvasElement) -> Result<SlotId, JsValue> {
408        let size = (canvas.width(), canvas.height());
409        let surface = self.instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas)).map_err(js_err)?;
410        let swapchain = Swapchain::new(&self.device, &self.adapter, surface, size, Some(PAGE_ALPHA_MODE), true).ok_or_else(|| js_error("the adapter cannot present to this canvas"))?;
411
412        // The scene is format-specific; the renderer is not, which is
413        // what lets canvases with different formats share one of it.
414        let mut scene = SSScene::new(&self.device, &SceneConfig { color_format: swapchain.format(), stencil_format: Some(STENCIL_FORMAT), mask: MaskBackend::Stencil });
415        let (width, height) = swapchain.size();
416        scene.set_viewport(&self.queue, width as f32, height as f32, false);
417
418        Ok(self.surfaces.insert(SurfaceEntry { swapchain, scene, players: Roster::default() }))
419    }
420
421    /// Upload a decoded `bitmap` and register it under `hash`.
422    ///
423    /// Goes through [`SSRenderer::set_texture`] rather than `upload_texture`
424    /// because the pixels never pass through Rust: `copyExternalImageToTexture`
425    /// moves them from the browser's decoded image straight into the texture,
426    /// with none of the CPU premultiply pass (and none of its 16 MB temporary)
427    /// that `upload_texture` needs. The renderer only borrows the view
428    /// — and since wgpu handles are refcounted, dropping our `Texture` here is
429    /// fine: the view it hands over keeps it alive.
430    ///
431    /// Refuses a bitmap the device cannot hold — past its
432    /// `max_texture_dimension_2d`, or empty, which is also what a closed one
433    /// reports — before anything changes. wgpu would raise it as a validation
434    /// error, whose default handler aborts the wasm instance and takes every
435    /// player on the page with it.
436    fn set_texture_from_bitmap(&mut self, hash: u32, bitmap: &web_sys::ImageBitmap) -> Result<(), JsValue> {
437        let (width, height) = (bitmap.width(), bitmap.height());
438        if let Some(why) = texture_extent_error(&self.device, (width, height)) {
439            return Err(js_error(format!("{why} (a closed ImageBitmap reports 0x0)")));
440        }
441        let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };
442        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
443            label: Some("SpriteStudio Atlas (ImageBitmap)"),
444            size,
445            mip_level_count: 1,
446            sample_count: 1,
447            dimension: wgpu::TextureDimension::D2,
448            format: wgpu::TextureFormat::Rgba8Unorm,
449            // RENDER_ATTACHMENT is not a use of ours: WebGPU requires it of any
450            // `copyExternalImageToTexture` destination.
451            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT,
452            view_formats: &[],
453        });
454
455        self.queue.copy_external_image_to_texture(
456            &wgpu::CopyExternalImageSourceInfo { source: wgpu::ExternalImageSource::ImageBitmap(bitmap.clone()), origin: wgpu::Origin2d::ZERO, flip_y: false },
457            wgpu::CopyExternalImageDestInfo {
458                texture: &texture,
459                mip_level: 0,
460                origin: wgpu::Origin3d::ZERO,
461                aspect: wgpu::TextureAspect::All,
462                color_space: wgpu::PredefinedColorSpace::Srgb,
463                // The bitmap was asked for premultiplied and the destination is
464                // declared premultiplied, so the copy converts nothing.
465                premultiplied_alpha: true,
466            },
467            size,
468        );
469
470        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
471        self.renderer.set_texture(&self.device, hash, &view, (width, height), AlphaMode::Premultiplied);
472        Ok(())
473    }
474}
475
476/// The page's WebGPU context: **one adapter, one device, one [`SSRenderer`]**,
477/// shared by every canvas and every player on the page.
478///
479/// ```js
480/// const ctx = await SsContextWeb.create();
481/// const surf = ctx.createSurface(canvas);
482/// const player = surf.createPlayer();
483/// await player.loadSsab(bytes);
484/// player.setAnimation('idle');
485/// player.play();
486/// ```
487#[wasm_bindgen]
488pub struct SsContextWeb {
489    inner: Rc<RefCell<WebContext>>,
490}
491
492#[wasm_bindgen]
493impl SsContextWeb {
494    /// Initialise WebGPU for the page. Rejects if the browser has no WebGPU
495    /// adapter/device (the caller should surface a fallback message).
496    ///
497    /// Call this **once per page** and share the result. Calling it twice builds
498    /// two devices, and nothing is shared between them.
499    pub async fn create() -> Result<SsContextWeb, JsValue> {
500        console_error_panic_hook::set_once();
501
502        let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
503        instance_desc.backends = wgpu::Backends::BROWSER_WEBGPU;
504        let instance = wgpu::Instance::new(instance_desc);
505        let adapter = request_adapter(&instance).await?;
506        let (device, queue, device_lost) = request_device(&adapter).await?;
507        let renderer = SSRenderer::new(&device);
508
509        Ok(SsContextWeb { inner: Rc::new(RefCell::new(WebContext { renderer, device, queue, surfaces: Roster::default(), adapter, device_lost, encoded_textures: HashMap::new(), instance })) })
510    }
511
512    /// Attach a canvas and get the scene that draws into it. Any number of
513    /// canvases may share this context.
514    #[wasm_bindgen(js_name = createSurface)]
515    pub fn create_surface(&self, canvas: web_sys::HtmlCanvasElement) -> Result<SsSurfaceWeb, JsValue> {
516        let id = self.inner.borrow_mut().add_surface(canvas)?;
517        Ok(SsSurfaceWeb { ctx: Rc::clone(&self.inner), id })
518    }
519
520    /// Supply a texture under a `textureRefs` entry's `key`, from **raw straight-alpha RGBA**.
521    ///
522    /// Device-scoped, so it covers every canvas and every player at once — which
523    /// is exactly why it is here and not on a surface or a player.
524    ///
525    /// Prefer [`SsContextWeb::add_texture_from_bytes`] when what you have is an
526    /// encoded image: this path premultiplies on the CPU and keeps the pixels for
527    /// device-loss recovery, so a 2048² atlas costs two 16 MB passes through wasm
528    /// memory that `createImageBitmap` does not.
529    ///
530    /// Throws, uploading nothing, when `rgba` is not `width * height * 4` bytes or
531    /// the device cannot hold the texture (past its `max_texture_dimension_2d`).
532    #[wasm_bindgen(js_name = addTexture)]
533    pub fn add_texture(&self, key: u32, rgba: &[u8], width: u32, height: u32) -> Result<(), JsValue> {
534        let ctx = &mut *self.inner.borrow_mut();
535        let WebContext { renderer, device, queue, encoded_textures, .. } = ctx;
536        if let Some(why) = texture_extent_error(device, (width, height)) {
537            return Err(js_error(&why));
538        }
539        // Inside the device's limit, so the product cannot overflow.
540        if rgba.len() != (width as usize) * (height as usize) * 4 {
541            return Err(js_error(format!("{} bytes do not fill a {width}x{height} RGBA8 texture", rgba.len())));
542        }
543        // One key, one supplier: whichever path registered it last owns the
544        // recovery too, so the other's retained source must go.
545        encoded_textures.remove(&key);
546        renderer.upload_texture(device, queue, key, rgba, (width, height), Retention::Retain);
547        Ok(())
548    }
549
550    /// Supply a texture under its `key` from **encoded image bytes** (PNG) — the main
551    /// texture path of this face.
552    ///
553    /// Both `.ssab` forms end here. An embedded pack's atlases come from
554    /// [`SsPlayerWeb::embedded_textures`] and need no fetch; a reference pack's
555    /// come from fetching each [`SsPlayerWeb::texture_refs`] entry whose
556    /// `embedded` is false, resolved against the `.ssab`'s own URL — which is how
557    /// this face supports both forms without carrying a decoder.
558    ///
559    /// The bytes are kept (they are the encoded image, not the pixels) so
560    /// [`SsContextWeb::restore_device`] can rebuild this texture on its own.
561    #[wasm_bindgen(js_name = addTextureFromBytes)]
562    pub async fn add_texture_from_bytes(&self, key: u32, bytes: Vec<u8>) -> Result<(), JsValue> {
563        upload_encoded(&self.inner, key, Rc::from(bytes)).await
564    }
565
566    /// Supply a texture under its `key` from an `ImageBitmap` the **page** decoded.
567    ///
568    /// For a host with its own asset pipeline — the analogue of
569    /// [`crate::SSRenderer::set_texture`]. The bitmap must be premultiplied
570    /// (`createImageBitmap(blob, { premultiplyAlpha: 'premultiply' })`), which is
571    /// what the whole pipeline composites in.
572    ///
573    /// Device loss is the supplier's to repair on this path, exactly as on the
574    /// Rust one: nothing is retained here, so the page registers it again after
575    /// [`SsContextWeb::restore_device`]. Use
576    /// [`SsContextWeb::add_texture_from_bytes`] to be spared that.
577    ///
578    /// Throws, registering nothing, for a bitmap the device cannot hold — past
579    /// its `max_texture_dimension_2d`, or closed.
580    #[wasm_bindgen(js_name = addTextureFromBitmap)]
581    pub fn add_texture_from_bitmap(&self, key: u32, bitmap: &web_sys::ImageBitmap) -> Result<(), JsValue> {
582        let ctx = &mut *self.inner.borrow_mut();
583        ctx.set_texture_from_bitmap(key, bitmap)?;
584        ctx.encoded_textures.remove(&key);
585        Ok(())
586    }
587
588    /// Whether an atlas is already registered for `key`.
589    ///
590    /// The texture map is device-scoped, so this answers for the
591    /// whole page: it is how a page that decodes atlases itself keeps "N players of
592    /// one pack decode its atlas once between them" true. The
593    /// player-side flush gets that for free (it filters before the decode); a
594    /// page supplying textures itself has to ask.
595    #[wasm_bindgen(js_name = hasTexture)]
596    pub fn has_texture(&self, key: u32) -> bool {
597        self.inner.borrow().renderer.texture_size(key).is_some()
598    }
599
600    /// Whether the browser has taken the WebGPU device away. While
601    /// this is true every surface's `frame` is a no-op; call
602    /// [`SsContextWeb::restore_device`] to bring the whole page back.
603    #[wasm_bindgen(js_name = isDeviceLost)]
604    pub fn is_device_lost(&self) -> bool {
605        self.inner.borrow().device_lost.load(Ordering::Relaxed)
606    }
607
608    /// This player's version.
609    #[wasm_bindgen(getter)]
610    pub fn version(&self) -> String {
611        crate::VERSION.to_owned()
612    }
613
614    /// The SpriteStudio-SDK version whose runtime this build links, written as
615    /// its release tag (`v7.0.0`), or `local` from a plain `cargo build`. The
616    /// package carries the same string in `wasm/VERSION`.
617    #[wasm_bindgen(getter, js_name = sdkVersion)]
618    pub fn sdk_version(&self) -> String {
619        crate::SDK_VERSION.to_owned()
620    }
621
622    /// Rebuild the page's WebGPU stack after a device loss and restore every
623    /// surface and player on it (pipelines, buffers, atlases, projections) —
624    /// playback continues from the frame it was interrupted on, with no re-fetch
625    /// of any `.ssab` and no re-fetch of any atlas.
626    ///
627    /// **One call for the page**, however many canvases it holds.
628    ///
629    /// Rejects if WebGPU is gone for good, or if the new adapter cannot present a
630    /// surface's baked format (then the host should rebuild from `create`).
631    #[wasm_bindgen(js_name = restoreDevice)]
632    pub async fn restore_device(&self) -> Result<(), JsValue> {
633        // Nothing is borrowed across these awaits: a `RefMut` held over a yield
634        // point would still be held when JS re-enters through a rAF callback.
635        let instance = self.inner.borrow().instance.clone();
636        let adapter = request_adapter(&instance).await?;
637        let (device, queue, device_lost) = request_device(&adapter).await?;
638
639        let encoded: Vec<(u32, Rc<[u8]>)> = {
640            let ctx = &mut *self.inner.borrow_mut();
641            // Device-scoped first, then each target, then each player's atlases.
642            ctx.renderer.restore_device(&device, &queue);
643            for surface in ctx.surfaces.iter_mut() {
644                if !surface.swapchain.presents_on(&adapter) {
645                    return Err(js_error("the restored adapter cannot present a canvas's original surface format; rebuild the context"));
646                }
647                surface.swapchain.restore(&device, &adapter);
648                surface.scene.restore_device(&device, &queue);
649                for player in surface.players.iter_mut() {
650                    player.restore_textures(&mut ctx.renderer, &device, &queue);
651                }
652                // `restore_device` re-applies the viewport the scene last saw, which is
653                // stale if the canvas was resized while the device was gone (`resize`
654                // only records the size then). The swapchain's is authoritative — re-apply it.
655                let (width, height) = surface.swapchain.size();
656                surface.scene.set_viewport(&queue, width as f32, height as f32, false);
657            }
658
659            ctx.adapter = adapter;
660            ctx.device = device;
661            ctx.queue = queue;
662            ctx.device_lost = device_lost;
663            ctx.encoded_textures.iter().map(|(&hash, bytes)| (hash, Rc::clone(bytes))).collect()
664        };
665
666        // The atlases this context decoded itself went with the old device:
667        // `set_texture` is the supplier's to repair, and here the
668        // supplier is us. Re-decoding is why the encoded bytes were kept — the
669        // page fetches nothing. Last, so that a hash claimed by both an explicit
670        // supply and an embedded pack ends up where it was before the loss:
671        // `addTextureFrom*` overwrites, on this path as on the first one.
672        for (hash, bytes) in encoded {
673            upload_encoded(&self.inner, hash, bytes).await?;
674        }
675        Ok(())
676    }
677
678    /// How many canvases this context currently drives (diagnostic).
679    #[wasm_bindgen(js_name = surfaceCount)]
680    pub fn surface_count(&self) -> usize {
681        self.inner.borrow().surfaces.len()
682    }
683}
684
685/// Decode `bytes` in the browser, upload the result under `hash` and retain the
686/// bytes for device-loss recovery.
687///
688/// A free function because both faces need it: the context supplies textures the
689/// page hands over, and a player supplies its own pack's. Takes an
690/// `Rc` so the restore path can re-run it without copying every retained atlas.
691/// Nothing is borrowed across the await — a `RefMut` held over a yield point
692/// would still be held when JS re-enters through a rAF callback.
693async fn upload_encoded(ctx: &Rc<RefCell<WebContext>>, hash: u32, bytes: Rc<[u8]>) -> Result<(), JsValue> {
694    let bitmap = decode_image(&bytes).await?;
695    let supplied = {
696        let ctx = &mut *ctx.borrow_mut();
697        let supplied = ctx.set_texture_from_bitmap(hash, &bitmap);
698        if supplied.is_ok() {
699            ctx.encoded_textures.insert(hash, bytes);
700        }
701        supplied
702    };
703    // Ours to decode, ours to release: the copy captured the pixels already.
704    bitmap.close();
705    supplied
706}
707
708/// One canvas and the scene drawn into it. Holds **any number of
709/// players**, composited in ascending `order` in a single render pass.
710#[wasm_bindgen]
711pub struct SsSurfaceWeb {
712    ctx: Rc<RefCell<WebContext>>,
713    id: SlotId,
714}
715
716#[wasm_bindgen]
717impl SsSurfaceWeb {
718    /// Add a player to this canvas. Players hold no GPU resource of their own, so a canvas with a dozen characters still costs one device,
719    /// one renderer and one scene.
720    #[wasm_bindgen(js_name = createPlayer)]
721    pub fn create_player(&self) -> Result<SsPlayerWeb, JsValue> {
722        let ctx = &mut *self.ctx.borrow_mut();
723        let entry = ctx.surfaces.get_mut(self.id).ok_or_else(|| gone("surface"))?;
724        let id = entry.players.insert(SSPlayer::new());
725        Ok(SsPlayerWeb { ctx: Rc::clone(&self.ctx), surface: self.id, id, loading: Cell::new(false) })
726    }
727
728    /// Advance every player on this canvas by `dt` seconds and render one frame.
729    ///
730    /// A no-op while the device is lost — every GPU object it would touch is
731    /// dead. The host polls [`SsContextWeb::is_device_lost`] and calls
732    /// `restoreDevice` to resume.
733    pub fn frame(&self, dt: f32) -> Result<(), JsValue> {
734        let ctx = &mut *self.ctx.borrow_mut();
735        if ctx.device_lost.load(Ordering::Relaxed) {
736            return Ok(());
737        }
738        // Split the borrow: the scene needs `&mut` on itself *and* on the
739        // renderer, which live in different fields of the same struct.
740        let WebContext { renderer, device, queue, surfaces, .. } = ctx;
741        let entry = surfaces.get_mut(self.id).ok_or_else(|| gone("surface"))?;
742
743        entry.scene.update_with(renderer, device, queue, dt, entry.players.slots_mut(), Slot::value_mut);
744        // A lost surface (a tab restore, say) is configured again and the frame
745        // skipped; the transparent clear is what lets the page show through.
746        entry.swapchain.render(device, queue, renderer, &mut entry.scene, wgpu::Color::TRANSPARENT, "ss-web frame").map_err(JsValue::from_str)
747    }
748
749    /// Resize the swapchain, the stencil buffer and the projection to the
750    /// canvas's new pixel size.
751    pub fn resize(&self, width: u32, height: u32) {
752        let ctx = &mut *self.ctx.borrow_mut();
753        let lost = ctx.device_lost.load(Ordering::Relaxed);
754        let WebContext { device, queue, surfaces, .. } = ctx;
755        let Some(entry) = surfaces.get_mut(self.id) else { return };
756        // Zero draws at 1 x 1 rather than being ignored, as the native host
757        // ignores it: configuring sets the canvas's own size, so a canvas the page
758        // set to zero is put back in step with its swapchain and stencil buffer.
759        // While the device is gone the new size is only recorded; `restoreDevice`
760        // configures the surface and the stencil from it on the way back.
761        entry.swapchain.resize(device, width, height, lost);
762        if !lost {
763            let (width, height) = entry.swapchain.size();
764            entry.scene.set_viewport(queue, width as f32, height as f32, false);
765        }
766    }
767
768    /// Fade each player whose alpha is below 1 as one layer, composited at its
769    /// alpha, rather than part by part — so overlapping parts of a half-faded
770    /// character read half, not three quarters. Off by default.
771    ///
772    /// Each player faded at once costs a render pass per frame and a layer the
773    /// size of the canvas (about 8 MiB at 1920x1080), counted in
774    /// `stats().groupLayers`; turning it off frees them. Inside a layer the parts
775    /// blend against transparency rather than the page: Add, Mul and Screen
776    /// parts composite with the player's own parts alone.
777    #[wasm_bindgen(js_name = setGroupAlpha)]
778    pub fn set_group_alpha(&self, on: bool) -> Result<(), JsValue> {
779        let ctx = &mut *self.ctx.borrow_mut();
780        let entry = ctx.surfaces.get_mut(self.id).ok_or_else(|| gone("surface"))?;
781        entry.scene.set_group_alpha(on);
782        Ok(())
783    }
784
785    /// Whether `setGroupAlpha` is on.
786    #[wasm_bindgen(js_name = groupAlpha)]
787    pub fn group_alpha(&self) -> Result<bool, JsValue> {
788        let ctx = &mut *self.ctx.borrow_mut();
789        let entry = ctx.surfaces.get_mut(self.id).ok_or_else(|| gone("surface"))?;
790        Ok(entry.scene.group_alpha())
791    }
792
793    /// What the last frame cost, as a plain JS object.
794    ///
795    /// `gpuPassTimeNs` is `undefined` unless the browser granted
796    /// `timestamp-query`, and lags one or two frames by design. The counters are
797    /// always available: `mergeableDraws` counts the draw calls that could have
798    /// joined the one before them, and `redundantTextureBinds` the texture binds
799    /// that repeated the one before them.
800    pub fn stats(&self) -> Result<js_sys::Object, JsValue> {
801        let ctx = &mut *self.ctx.borrow_mut();
802        let entry = ctx.surfaces.get_mut(self.id).ok_or_else(|| gone("surface"))?;
803        let s = entry.scene.stats();
804        let out = js_sys::Object::new();
805        let set = |key: &str, value: JsValue| {
806            let _ = js_sys::Reflect::set(&out, &JsValue::from_str(key), &value);
807        };
808        set("players", s.players.into());
809        set("prims", s.prims.into());
810        set("drawCalls", s.draw_calls.into());
811        set("uploadedBytes", (s.uploaded_bytes as f64).into());
812        set("mergeableDraws", s.mergeable_draws.into());
813        set("redundantTextureBinds", s.redundant_texture_binds.into());
814        set("groupLayers", s.group_layers.into());
815        if let Some(ns) = s.gpu_pass_time_ns {
816            set("gpuPassTimeNs", (ns as f64).into());
817        }
818        Ok(out)
819    }
820
821    /// How many players draw into this canvas (diagnostic).
822    #[wasm_bindgen(js_name = playerCount)]
823    pub fn player_count(&self) -> usize {
824        self.ctx.borrow_mut().surfaces.get_mut(self.id).map(|e| e.players.len()).unwrap_or(0)
825    }
826
827    /// Detach this canvas and release its swapchain, scene and players.
828    ///
829    /// Explicit because dropping the JS wrapper cannot do it: the surface lives
830    /// in the shared context, not in this handle. Calling it twice, or calling
831    /// anything else afterwards, is safe — the handle resolves to "destroyed".
832    pub fn destroy(&self) {
833        let ctx = &mut *self.ctx.borrow_mut();
834        let WebContext { surfaces, renderer, encoded_textures, .. } = ctx;
835        if let Some(entry) = surfaces.get_mut(self.id) {
836            for player in entry.players.iter_mut() {
837                for key in player.override_keys() {
838                    renderer.forget_texture(key);
839                    encoded_textures.remove(&key);
840                }
841            }
842        }
843        surfaces.remove(self.id);
844    }
845}
846
847/// One character. Holds the playback tree and its placement in the
848/// scene — and no GPU resource at all, which is what makes it cheap to have many.
849#[wasm_bindgen]
850pub struct SsPlayerWeb {
851    ctx: Rc<RefCell<WebContext>>,
852    surface: SlotId,
853    id: SlotId,
854    /// Set while a load holds this player outside the context — see
855    /// [`SsPlayerWeb::with_player_detached`], which is the only thing that reads
856    /// it. On the handle rather than in the slot because `createPlayer` is the
857    /// only way to get one, so there is exactly one of these per player.
858    loading: Cell<bool>,
859}
860
861/// Read one field off an options object. A missing object and a missing field
862/// are the same thing here: the default.
863fn field(options: Option<&js_sys::Object>, key: &str) -> JsValue {
864    match options {
865        Some(object) => js_sys::Reflect::get(object, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED),
866        None => JsValue::UNDEFINED,
867    }
868}
869
870fn number_field(options: Option<&js_sys::Object>, key: &str, default: f32) -> f32 {
871    field(options, key).as_f64().map(|value| value as f32).unwrap_or(default)
872}
873
874fn set_number(out: &js_sys::Object, key: &str, value: f32) {
875    let _ = js_sys::Reflect::set(out, &JsValue::from_str(key), &JsValue::from_f64(value as f64));
876}
877
878/// The options object [`SsPlayerWeb::fit_into`] takes, as a [`Placement`].
879///
880/// Unrecognised `fit` / `align` strings throw rather than falling back to the
881/// default: a typo that silently centres is a bug the page cannot see, and the
882/// message lists what is accepted.
883fn read_placement(options: Option<&js_sys::Object>) -> Result<Placement, JsValue> {
884    let fit = match field(options, "fit").as_string() {
885        None => Fit::default(),
886        Some(name) => match name.as_str() {
887            "contain" => Fit::Contain,
888            "cover" => Fit::Cover,
889            "none" => Fit::None,
890            other => return Err(js_error(format!("unknown fit {other:?}; expected \"contain\", \"cover\" or \"none\""))),
891        },
892    };
893    let align = match field(options, "align").as_string() {
894        None => Align::default(),
895        Some(name) => match name.as_str() {
896            "center" => Align::Center,
897            "top" => Align::Top,
898            "bottom" => Align::Bottom,
899            "left" => Align::Left,
900            "right" => Align::Right,
901            "top-left" => Align::TopLeft,
902            "top-right" => Align::TopRight,
903            "bottom-left" => Align::BottomLeft,
904            "bottom-right" => Align::BottomRight,
905            other => {
906                return Err(js_error(format!("unknown align {other:?}; expected \"center\", \"top\", \"bottom\", \"left\", \"right\", \"top-left\", \"top-right\", \"bottom-left\" or \"bottom-right\"")));
907            }
908        },
909    };
910    let frame = field(options, "frame").dyn_into::<js_sys::Object>().ok().map(|rect| {
911        let rect = Some(&rect);
912        Rect { x: number_field(rect, "x", 0.0), y: number_field(rect, "y", 0.0), width: number_field(rect, "width", 0.0), height: number_field(rect, "height", 0.0) }
913    });
914    Ok(Placement {
915        fit,
916        align,
917        frame,
918        offset: (number_field(options, "offsetX", 0.0), number_field(options, "offsetY", 0.0)),
919        scale: number_field(options, "scale", 1.0),
920        flip_x: field(options, "flipX").is_truthy(),
921        flip_y: field(options, "flipY").is_truthy(),
922        rotation: number_field(options, "rotation", 0.0),
923    })
924}
925
926/// Run `body` on the player this handle names.
927///
928/// A macro rather than a helper method because the closure would have to borrow
929/// the `RefCell` for the caller, and every one of these is a one-liner.
930macro_rules! with_player {
931    ($self:ident, |$player:ident| $body:expr) => {{
932        let ctx = &mut *$self.ctx.borrow_mut();
933        let entry = ctx.surfaces.get_mut($self.surface).ok_or_else(|| gone("surface"))?;
934        let $player = entry.players.get_mut($self.id).ok_or_else(|| gone("player"))?;
935        #[allow(clippy::let_and_return)]
936        let out = $body;
937        Ok(out)
938    }};
939}
940
941/// The web half of [`AssetLoader`]: `fetch` for files, or the host's own reader
942/// in its place, and `createImageBitmap` for images.
943///
944/// The counterpart of the filesystem loader behind `SSPlayer::load`, and the
945/// reason the walk itself — both texture tables, deduplication by file,
946/// transitive instance packs — is written once in [`SSPlayer::load_with`]
947/// rather than twice. What differs is only
948/// what a browser can do that a filesystem cannot, and the other way round.
949///
950/// Holds the context by `Rc` and takes its `RefMut` for a moment at a time,
951/// never across an await: JS re-enters through rAF callbacks, and a borrow held
952/// over a yield point would still be held when it does.
953struct WebAssetLoader {
954    ctx: Rc<RefCell<WebContext>>,
955    /// The base the host gave us, which [`AssetLoader::set_base`] never moves.
956    /// Every base is derived from *this*, so one loader survives several loads.
957    /// `None` means "the document's URL".
958    origin_url: Option<String>,
959    /// What the pack's relative paths resolve against — the `.ssab`'s own URL.
960    /// `None` falls back to the document's.
961    base_url: Option<String>,
962    /// The host's `SsAssetReader`, asked instead of `fetch` (see [`read_files`]).
963    read: Option<js_sys::Function>,
964}
965
966impl WebAssetLoader {
967    /// Rooted wherever the host said, or at the document when it said nothing.
968    fn new(ctx: Rc<RefCell<WebContext>>, base_url: Option<String>, read: Option<js_sys::Function>) -> Self {
969        Self { ctx, origin_url: base_url.clone(), base_url, read }
970    }
971}
972
973impl AssetLoader for WebAssetLoader {
974    fn reset_base(&mut self) {
975        self.base_url.clone_from(&self.origin_url);
976    }
977
978    /// URL resolution **is** the answer here, the way `Path::parent` is on the
979    /// filesystem face: a base that names a file has its last segment
980    /// replaced, so keeping the `.ssab`'s own URL as the base is what makes
981    /// `atlas.png` next to it resolve correctly — and what makes `../` and a
982    /// query string behave the way every other URL on the page does.
983    ///
984    /// Resolved against `origin_url` — what the host gave us — and not against the
985    /// base a previous load left behind, so this is idempotent and a reused loader
986    /// does not walk `assets/assets/` deeper on every call. Stored absolute,
987    /// because `URL(relative, base)` needs an absolute base and a host may well
988    /// have passed `assets/overall/`.
989    fn set_base(&mut self, src: &str) {
990        match absolute_url(src, self.origin_url.as_deref()) {
991            Some(url) => self.base_url = Some(url),
992            None => self.warn(&format!("{src}: cannot be resolved to a URL; the pack's siblings will be looked for against the document")),
993        }
994    }
995
996    /// One `fetch` per path, settled together: this is the face where overlapping
997    /// the waiting is the difference between one round trip and N.
998    async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>> {
999        let fetched = match &self.read {
1000            Some(read) => read_files(read, paths, self.base_url.as_deref()).await,
1001            None => fetch_files(paths, self.base_url.as_deref()).await,
1002        };
1003        paths.iter().map(|path| fetched.get(path).map(|bytes| bytes.to_vec())).collect()
1004    }
1005
1006    /// The URL `path` resolves to, hashed — the same resolution `read` performs,
1007    /// so two packs fetched from two directories that both name `spritemap1.png`
1008    /// are two images and the sibling packs of one project are one.
1009    fn texture_key(&self, path: &str, cellmap_hash: u32) -> u32 {
1010        match absolute_url(path, self.base_url.as_deref()) {
1011            Some(url) => ssruntime::fnv1a_hash_str(&url),
1012            // Unresolvable: `read` will fail too and the atlas be reported
1013            // missing. Keying it as the slot keeps that path unchanged.
1014            None => cellmap_hash,
1015        }
1016    }
1017
1018    async fn supply_texture(&mut self, key: u32, encoded: &[u8]) {
1019        if let Err(e) = upload_encoded(&self.ctx, key, Rc::from(encoded)).await {
1020            self.warn(&format!("the image for {key:#010x} is not uploaded: {e:?}"));
1021        }
1022    }
1023
1024    /// What the renderer holds. `key` names the image rather than a slot inside
1025    /// one pack, so a second project's `spritemap1` is not mistaken for the
1026    /// first's.
1027    fn has_texture(&self, key: u32) -> bool {
1028        self.ctx.borrow().renderer.texture_size(key).is_some()
1029    }
1030
1031    fn warn(&self, message: &str) {
1032        warn(&format!("[ssplayer-wgpu] {message}"));
1033    }
1034}
1035
1036impl SsPlayerWeb {
1037    /// Parse `bytes` and register the pack, selecting it when `select`.
1038    ///
1039    /// A pack keeps the name the exporter wrote unless the caller overrides it,
1040    /// because that is the name external instance parts are resolved against
1041    /// (`ref_anime_pack`) and the exporter writes the same string on
1042    /// both sides. An override is a promise that the caller knows better.
1043    fn register(&self, bytes: &[u8], pack: Option<String>, select: bool) -> Result<SSPack, JsValue> {
1044        let pack = match pack.as_deref() {
1045            Some(name) => SSPack::load_named(name, bytes),
1046            None => SSPack::load(bytes),
1047        }
1048        .map_err(js_err)?;
1049        // Annotated because the macro's `Ok(out)` leaves the error type to the
1050        // caller, and here the value is discarded rather than returned.
1051        let registered: Result<(), JsValue> = with_player!(self, |p| if select { p.set_pack(&pack) } else { p.add_pack(&pack) });
1052        registered?;
1053        Ok(pack)
1054    }
1055
1056    /// Run `body` on this handle's player, **outside** the context's `RefCell`.
1057    ///
1058    /// [`SSPlayer::load_with`] holds `&mut SSPlayer` across its awaits, and on this
1059    /// face the player lives inside the one cell everything else borrows — so it
1060    /// is lifted out for the duration and put back after. The slot keeps a blank
1061    /// player meanwhile, which draws nothing: it has no animation yet, which is
1062    /// the only state a load can be in.
1063    ///
1064    /// If the handle is destroyed while the load is in flight, the finished
1065    /// player is dropped rather than written back over its successor — the same
1066    /// rule the generation-tagged slots exist for.
1067    ///
1068    /// **One at a time**, which is what [`SsPlayerWeb::ensure_idle`] enforces: a
1069    /// second load would detach the blank placeholder the first one left, walk
1070    /// *that*, and write it back over the finished player — so whichever settled
1071    /// last would win, taking the other one's pack, atlases and transform with
1072    /// it. A host that starts a load without awaiting the previous one is told
1073    /// so rather than losing one of them quietly.
1074    async fn with_player_detached<F, Fut, T>(&self, body: F) -> Result<T, JsValue>
1075    where
1076        F: FnOnce(SSPlayer) -> Fut,
1077        Fut: core::future::Future<Output = (SSPlayer, T)>,
1078    {
1079        let taken = {
1080            self.ensure_idle()?;
1081            let ctx = &mut *self.ctx.borrow_mut();
1082            let entry = ctx.surfaces.get_mut(self.surface).ok_or_else(|| gone("surface"))?;
1083            let slot = entry.players.get_mut(self.id).ok_or_else(|| gone("player"))?;
1084            self.loading.set(true);
1085            core::mem::take(slot)
1086        };
1087
1088        let (player, out) = body(taken).await;
1089        self.loading.set(false);
1090
1091        let ctx = &mut *self.ctx.borrow_mut();
1092        if let Some(entry) = ctx.surfaces.get_mut(self.surface)
1093            && let Some(slot) = entry.players.get_mut(self.id)
1094        {
1095            *slot = player;
1096        }
1097        Ok(out)
1098    }
1099
1100    /// Refuse a call that would register or load into the placeholder another
1101    /// load has left in this player's slot.
1102    ///
1103    /// Checked before the registration `loadSsab` / `addSsab` do as well as in
1104    /// [`SsPlayerWeb::with_player_detached`], because a pack registered into that
1105    /// placeholder goes the same way the placeholder does.
1106    fn ensure_idle(&self) -> Result<(), JsValue> {
1107        if self.loading.get() {
1108            return Err(js_error("this player is already loading; await that promise before starting another load on it"));
1109        }
1110        Ok(())
1111    }
1112}
1113
1114#[wasm_bindgen]
1115impl SsPlayerWeb {
1116    /// Register + select a `.ssab`, **and load the textures it needs**.
1117    ///
1118    /// It loads the pack's textures before returning and leaves `setAnimation` a
1119    /// pure selection. Texture loading belongs to initialisation, not to
1120    /// animation selection: switching motions is a frequent, synchronous
1121    /// operation that must not carry a `Promise`, so
1122    /// [`SsPlayerWeb::set_animation`] stays synchronous.
1123    ///
1124    /// This is async because `fetch` and `createImageBitmap` are. **That is the
1125    /// one place the asynchrony appears.**
1126    ///
1127    /// * `pack` names the pack for external instance references (`ref_anime_pack`).
1128    /// Pass `null`/`undefined` — the usual case — to use the name the exporter
1129    /// wrote into the `.ssab`, which is the name those references
1130    /// are resolved against. A name of your own overrides it, and then any
1131    /// external instance reference to this pack stops resolving.
1132    /// * `baseUrl` is where the `.ssab` came from; reference-mode atlas paths are
1133    /// relative to it. Defaults to the document's URL. Embedded packs ignore it.
1134    /// * `read` answers in place of `fetch`, as it does for [`SsPlayerWeb::load`].
1135    ///
1136    /// An atlas the renderer already has is left alone ("registered wins"), so
1137    /// N players of one pack load it once between them. An atlas
1138    /// that cannot be fetched or decoded is reported on the console and skipped,
1139    /// as in `_load_external_ssabs`' `ERR_PRINT` and `PackResolver`'s
1140    /// `console.warn`: one missing image should not cost you the character.
1141    #[wasm_bindgen(js_name = loadSsab)]
1142    pub async fn load_ssab(
1143        &self,
1144        bytes: Vec<u8>,
1145        // Spelled out because a typed trailing parameter costs the ones before it
1146        // their `?` in the generated `.d.ts`.
1147        #[wasm_bindgen(unchecked_optional_param_type = "string | null")] pack: Option<String>,
1148        #[wasm_bindgen(js_name = "baseUrl", unchecked_optional_param_type = "string | null")] base_url: Option<String>,
1149        #[wasm_bindgen(unchecked_optional_param_type = "SsAssetReader | null")] read: Option<js_sys::Function>,
1150    ) -> Result<(), JsValue> {
1151        self.ensure_idle()?;
1152        let registered = self.register(&bytes, pack, true)?;
1153        let mut loader = WebAssetLoader::new(Rc::clone(&self.ctx), base_url, read);
1154        let name = registered.name().to_string();
1155        self.with_player_detached(|mut player| async move {
1156            // The pack is registered; only the assets around it are left, so the
1157            // walk starts from what is already loaded rather than re-reading it.
1158            // There is no `src` to re-root on — the bytes came from the host — so
1159            // `baseUrl` is the base, exactly as documented.
1160            player.load_assets(&mut loader, &name).await;
1161            (player, ())
1162        })
1163        .await
1164    }
1165
1166    /// Fetch a `.ssab` **and everything it needs**, then select it.
1167    ///
1168    /// The shortest form: a URL is the one input that answers both questions a pack raises — what the
1169    /// bytes are, and what its sibling files resolve against. `src` may be
1170    /// absolute or relative (resolved against the document, like any URL a page
1171    /// uses), and the pack keeps the name the exporter gave it.
1172    ///
1173    /// This is [`SSPlayer::load_with`] with the browser's loader plugged in — the
1174    /// same walk a native host's `SSPlayer::load` makes. Use [`SsPlayerWeb::load_ssab`] when the bytes have
1175    /// no URL at all — a bundler's import — and pass `baseUrl` if that pack
1176    /// still has siblings to find.
1177    ///
1178    /// `read` stands in for `fetch` when the files are not on a server: a
1179    /// dropped folder, an archive the page unpacked. It is handed each file's
1180    /// absolute URL — `src` resolved against the document, everything after it
1181    /// resolved against `src` — and answers an `ArrayBuffer`, a `Uint8Array` or a
1182    /// `Blob`, or `null` for a file it does not have. So a page that files a
1183    /// dropped folder under URLs of its own choosing gets the whole walk:
1184    ///
1185    /// ```js
1186    /// const base = new URL('dropped/1/', location.href);
1187    /// const files = new Map(dropped.map((f) => [new URL(f.path, base).href, f.file]));
1188    /// await player.load(new URL('Ringo/Ringo.ssab', base).href, (url) => files.get(url));
1189    /// ```
1190    ///
1191    /// The atlases are keyed by those URLs, as fetched ones are, so a second
1192    /// folder needs a base of its own: under the same one, an atlas that shares
1193    /// a name with the first folder's is taken as already loaded.
1194    ///
1195    /// **One load at a time per player.** Starting a second before the first has
1196    /// settled is rejected, because the two would otherwise race for the slot the
1197    /// player was lifted out of and one of them would be lost — `await` the
1198    /// promise, or chain the calls. Two *different* players load concurrently as
1199    /// usual, and share whatever atlases they have in common.
1200    pub async fn load(&self, src: &str, #[wasm_bindgen(unchecked_optional_param_type = "SsAssetReader | null")] read: Option<js_sys::Function>) -> Result<(), JsValue> {
1201        // No base of our own: `src` is page-relative like any other URL here, so
1202        // the document resolves it. The walk then hands `src` to `set_base` — after
1203        // it has been read, never before — and the `.ssab`'s own URL becomes what
1204        // its siblings resolve against. Setting it here instead would resolve
1205        // `src` against itself and fetch `assets/assets/Basic.ssab`.
1206        let mut loader = WebAssetLoader::new(Rc::clone(&self.ctx), None, read);
1207        let label = src.to_owned();
1208        let src = src.to_owned();
1209        self.with_player_detached(|mut player| async move {
1210            let out = player.load_with(&mut loader, &src).await;
1211            (player, out)
1212        })
1213        .await?
1214        .map_err(|e| js_error(format!("{label}: {e}")))
1215    }
1216
1217    /// [`SsPlayerWeb::load_ssab`] without changing what plays: registers an
1218    /// additional pack for external instance references, and loads its assets
1219    /// too — a sub-animation's cells come out of its own pack's atlases.
1220    ///
1221    /// Rarely needed, since [`SsPlayerWeb::load`] resolves those references
1222    /// itself; it is for packs that are not URL-addressable.
1223    #[wasm_bindgen(js_name = addSsab)]
1224    pub async fn add_ssab(
1225        &self,
1226        bytes: Vec<u8>,
1227        // Spelled out because a typed trailing parameter costs the ones before it
1228        // their `?` in the generated `.d.ts`.
1229        #[wasm_bindgen(unchecked_optional_param_type = "string | null")] pack: Option<String>,
1230        #[wasm_bindgen(js_name = "baseUrl", unchecked_optional_param_type = "string | null")] base_url: Option<String>,
1231        #[wasm_bindgen(unchecked_optional_param_type = "SsAssetReader | null")] read: Option<js_sys::Function>,
1232    ) -> Result<(), JsValue> {
1233        self.ensure_idle()?;
1234        let registered = self.register(&bytes, pack, false)?;
1235        let mut loader = WebAssetLoader::new(Rc::clone(&self.ctx), base_url, read);
1236        let name = registered.name().to_string();
1237        self.with_player_detached(|mut player| async move {
1238            player.load_assets(&mut loader, &name).await;
1239            (player, ())
1240        })
1241        .await
1242    }
1243
1244    /// The animation names in the loaded pack.
1245    #[wasm_bindgen(js_name = animationNames)]
1246    pub fn animation_names(&self) -> Result<Vec<String>, JsValue> {
1247        with_player!(self, |p| p.animation_names().unwrap_or_default())
1248    }
1249
1250    /// The animation currently set up, or `undefined` before the first
1251    /// `setAnimation` and again after a load replaced the pack.
1252    #[wasm_bindgen(js_name = currentAnimation)]
1253    pub fn current_animation(&self) -> Result<Option<String>, JsValue> {
1254        with_player!(self, |p| p.current_animation().map(str::to_owned))
1255    }
1256
1257    /// The atlases a registered pack asks for, as `{ key, path, embedded }[]`
1258    /// in pack order. `pack` undefined selects the main pack.
1259    ///
1260    /// The counterpart of [`SsContextWeb::add_texture`]: only the `.ssab` knows where its atlases were exported to, so a page
1261    /// showing a reference-mode pack fetches `new URL(path, ssabUrl)` for every
1262    /// entry whose `embedded` is false and registers the pixels by **`key`**.
1263    /// Embedded entries need no fetch — they arrive with the pack.
1264    ///
1265    /// `key` is what the renderer is keyed by, not the slot the pack names the
1266    /// atlas by. The two differ whenever two packs could name one atlas alike,
1267    /// which a tool naming every project's atlas `spritemap1.png` does —
1268    /// registering by the slot is how a page ends up drawing another project's
1269    /// atlas, which is why the slot is not handed out here.
1270    #[wasm_bindgen(js_name = textureRefs)]
1271    pub fn texture_refs(&self, pack: Option<String>) -> Result<js_sys::Array, JsValue> {
1272        with_player!(self, |p| {
1273            let out = js_sys::Array::new();
1274            for texture in p.textures(pack.as_deref()).unwrap_or_default() {
1275                let entry = js_sys::Object::new();
1276                let set = |key: &str, value: JsValue| {
1277                    let _ = js_sys::Reflect::set(&entry, &JsValue::from_str(key), &value);
1278                };
1279                set("key", p.texture_key(pack.as_deref(), texture.slot).into());
1280                set("path", texture.path.as_str().into());
1281                set("embedded", texture.embedded.into());
1282                out.push(&entry);
1283            }
1284            out
1285        })
1286    }
1287
1288    /// The atlases a registered pack **carries**, as `{ key, bytes }[]` — the
1289    /// encoded images, not pixels. Empty for a reference-mode pack.
1290    /// `pack` undefined selects the main pack.
1291    ///
1292    /// The embedded half of texture supply, and the counterpart of
1293    /// [`SsPlayerWeb::texture_refs`]: there is nothing to fetch, but there is
1294    /// still something to decode, and on this face the decoder is the browser.
1295    /// Hand each entry to [`SsContextWeb::add_texture_from_bytes`].
1296    ///
1297    /// It is what lets this face support embedded packs without carrying an image
1298    /// decoder into the bundle.
1299    #[wasm_bindgen(js_name = embeddedTextures)]
1300    pub fn embedded_textures(&self, pack: Option<String>) -> Result<js_sys::Array, JsValue> {
1301        with_player!(self, |p| {
1302            let out = js_sys::Array::new();
1303            for image in p.embedded_images(pack.as_deref()).unwrap_or_default() {
1304                let entry = js_sys::Object::new();
1305                let set = |key: &str, value: JsValue| {
1306                    let _ = js_sys::Reflect::set(&entry, &JsValue::from_str(key), &value);
1307                };
1308                set("key", p.texture_key(pack.as_deref(), image.slot).into());
1309                set("bytes", js_sys::Uint8Array::from(image.bytes).into());
1310                out.push(&entry);
1311            }
1312            out
1313        })
1314    }
1315
1316    /// What the last load could not get, as `{ kind, name, slot }[]`.
1317    /// Empty means everything the packs asked for arrived.
1318    ///
1319    /// `load` rejects only when the `.ssab` itself is unreadable — one missing
1320    /// atlas must not cost you the character — so this is how a page tells a
1321    /// complete load from one that played anyway. `kind` is `"texture"` (its
1322    /// parts draw as white silhouettes) or `"pack"` (its parts do not appear).
1323    #[wasm_bindgen(js_name = missingAssets)]
1324    pub fn missing_assets(&self) -> Result<js_sys::Array, JsValue> {
1325        with_player!(self, |p| {
1326            let out = js_sys::Array::new();
1327            for missing in p.missing_assets() {
1328                let entry = js_sys::Object::new();
1329                let set = |key: &str, value: JsValue| {
1330                    let _ = js_sys::Reflect::set(&entry, &JsValue::from_str(key), &value);
1331                };
1332                set(
1333                    "kind",
1334                    JsValue::from_str(match missing.kind {
1335                        MissingKind::Texture => "texture",
1336                        MissingKind::Pack => "pack",
1337                    }),
1338                );
1339                set("name", missing.name.as_str().into());
1340                set("slot", missing.slot.into());
1341                out.push(&entry);
1342            }
1343            out
1344        })
1345    }
1346
1347    // --- Runtime texture replacement ---------------------------
1348    //
1349    // Swap the texture a cellmap binds, from the page rather than the authoring
1350    // data — costume changes, dynamic expressions.
1351    // Per player: the redirect lives in this
1352    // player's atlas-key table, so another player of the same pack is unaffected,
1353    // and an instance child (its own pack) does not inherit it.
1354    //
1355    // The replacement is registered in the page's one shared renderer under a
1356    // private key and this player's cellmap is pointed at it — the same
1357    // `set_texture`/`copyExternalImageToTexture` path `addTextureFromBitmap` uses,
1358    // so device loss is the page's to repair (re-apply the override), exactly as
1359    // for a page-supplied atlas.
1360
1361    /// Every replaceable name in a pack — cellmap names and TextureChange targets
1362    /// both, the namespace [`SsPlayerWeb::set_cellmap_texture`] takes. `pack` null
1363    /// selects the main pack.
1364    #[wasm_bindgen(js_name = replaceableCellmapNames)]
1365    pub fn replaceable_cellmap_names(&self, pack: Option<String>) -> Result<Vec<String>, JsValue> {
1366        with_player!(self, |p| p.replaceable_cellmap_names(pack.as_deref()).unwrap_or_default())
1367    }
1368
1369    /// Replace the texture a cellmap binds, from a premultiplied `ImageBitmap` the
1370    /// page decoded (`createImageBitmap(blob, { premultiplyAlpha: 'premultiply' })`).
1371    ///
1372    /// `pack` null selects the main pack. `name` is one of
1373    /// [`SsPlayerWeb::replaceable_cellmap_names`]. The replacement should match the
1374    /// original atlas's size and cell layout — the runtime's UVs stay in the
1375    /// original cellmap's pixel space. Rejects when the player is unbound, for a
1376    /// pack or name it cannot replace, and for a bitmap the device cannot hold —
1377    /// past its `max_texture_dimension_2d`, or closed — leaving the cellmap as it
1378    /// was.
1379    #[wasm_bindgen(js_name = setCellmapTexture)]
1380    pub fn set_cellmap_texture(&self, pack: Option<String>, name: &str, bitmap: &web_sys::ImageBitmap) -> Result<(), JsValue> {
1381        let ctx = &mut *self.ctx.borrow_mut();
1382        if let Some(why) = texture_extent_error(&ctx.device, (bitmap.width(), bitmap.height())) {
1383            return Err(js_error(format!("{name}: {why} (a closed ImageBitmap reports 0x0)")));
1384        }
1385        let key = {
1386            let entry = ctx.surfaces.get_mut(self.surface).ok_or_else(|| gone("surface"))?;
1387            let player = entry.players.get_mut(self.id).ok_or_else(|| gone("player"))?;
1388            player.override_cellmap_texture_key(pack.as_deref(), name).ok_or_else(|| unreplaceable(player, pack.as_deref(), name))?
1389        };
1390        ctx.set_texture_from_bitmap(key, bitmap)
1391    }
1392
1393    /// [`SsPlayerWeb::set_cellmap_texture`] from **encoded image bytes** (PNG); the
1394    /// library runs them through `createImageBitmap`. Decoded before anything
1395    /// changes, so a bad image leaves the cellmap as it was.
1396    #[wasm_bindgen(js_name = setCellmapTextureFromBytes)]
1397    pub async fn set_cellmap_texture_from_bytes(&self, pack: Option<String>, name: String, bytes: Vec<u8>) -> Result<(), JsValue> {
1398        // Decoded first — and off any RefCell borrow, since `createImageBitmap` is
1399        // a yield point JS re-enters through.
1400        let bitmap = decode_image(&bytes).await?;
1401        let supplied = self.supply_cellmap_bitmap(pack.as_deref(), &name, &bitmap);
1402        // Closed on every path: a decoded atlas is megabytes the page cannot free.
1403        bitmap.close();
1404        supplied
1405    }
1406
1407    /// The synchronous half of [`SsPlayerWeb::set_cellmap_texture_from_bytes`],
1408    /// split out so the bitmap is closed whichever way it returns.
1409    fn supply_cellmap_bitmap(&self, pack: Option<&str>, name: &str, bitmap: &web_sys::ImageBitmap) -> Result<(), JsValue> {
1410        let ctx = &mut *self.ctx.borrow_mut();
1411        if let Some(why) = texture_extent_error(&ctx.device, (bitmap.width(), bitmap.height())) {
1412            return Err(js_error(format!("{name}: {why}")));
1413        }
1414        let key = {
1415            let entry = ctx.surfaces.get_mut(self.surface).ok_or_else(|| gone("surface"))?;
1416            let player = entry.players.get_mut(self.id).ok_or_else(|| gone("player"))?;
1417            player.override_cellmap_texture_key(pack, name).ok_or_else(|| unreplaceable(player, pack, name))?
1418        };
1419        ctx.set_texture_from_bitmap(key, bitmap)
1420    }
1421
1422    /// Undo a runtime override: point the cellmap back at its original atlas and
1423    /// drop the replacement from the renderer. A no-op if it was not overridden;
1424    /// rejects a pack or name the player cannot replace.
1425    #[wasm_bindgen(js_name = restoreCellmapTexture)]
1426    pub fn restore_cellmap_texture(&self, pack: Option<String>, name: &str) -> Result<(), JsValue> {
1427        let ctx = &mut *self.ctx.borrow_mut();
1428        let freed = {
1429            let entry = ctx.surfaces.get_mut(self.surface).ok_or_else(|| gone("surface"))?;
1430            let player = entry.players.get_mut(self.id).ok_or_else(|| gone("player"))?;
1431            // A live override is restorable even after a load dropped its pack.
1432            if !player.can_replace(pack.as_deref(), name) && !player.is_cellmap_overridden(pack.as_deref(), name) {
1433                return Err(unreplaceable(player, pack.as_deref(), name));
1434            }
1435            player.restore_cellmap_texture(pack.as_deref(), name)
1436        };
1437        if let Some(key) = freed {
1438            ctx.renderer.forget_texture(key);
1439            ctx.encoded_textures.remove(&key);
1440        }
1441        Ok(())
1442    }
1443
1444    /// Whether a cellmap currently carries a runtime override. `pack` null selects
1445    /// the main pack.
1446    #[wasm_bindgen(js_name = isCellmapOverridden)]
1447    pub fn is_cellmap_overridden(&self, pack: Option<String>, name: &str) -> Result<bool, JsValue> {
1448        with_player!(self, |p| p.is_cellmap_overridden(pack.as_deref(), name))
1449    }
1450
1451    /// Select an animation: builds the instance tree, and the only call here that
1452    /// allocates. Starting playback is [`SsPlayerWeb::play`], a separate call.
1453    #[wasm_bindgen(js_name = setAnimation)]
1454    pub fn set_animation(&self, name: &str) -> Result<(), JsValue> {
1455        with_player!(self, |p| p.set_animation(name).map_err(|e| js_error(format!("{name}: {e}")))?)
1456    }
1457
1458    /// Start from the head of the section, re-arming the loop count. Not a
1459    /// resume: it rewinds. Use [`SsPlayerWeb::resume`] to lift a hold.
1460    pub fn play(&self) -> Result<(), JsValue> {
1461        with_player!(self, |p| p.play())
1462    }
1463
1464    /// `play()` from `startFrame` rather than the head of the section.
1465    #[wasm_bindgen(js_name = playFrom)]
1466    pub fn play_from(&self, #[wasm_bindgen(js_name = "startFrame")] start_frame: f32) -> Result<(), JsValue> {
1467        with_player!(self, |p| p.play_from(start_frame))
1468    }
1469
1470    /// Hold the current frame. Idempotent, and ignored while nothing is playing.
1471    pub fn pause(&self) -> Result<(), JsValue> {
1472        with_player!(self, |p| p.pause())
1473    }
1474
1475    /// Lift a [`SsPlayerWeb::pause`], carrying on from the same frame.
1476    /// Idempotent, and a no-op on a stopped animation.
1477    pub fn resume(&self) -> Result<(), JsValue> {
1478        with_player!(self, |p| p.resume())
1479    }
1480
1481    /// Stop playback. The playhead stays where it stands; nothing rewinds.
1482    pub fn stop(&self) -> Result<(), JsValue> {
1483        with_player!(self, |p| p.stop())
1484    }
1485
1486    /// Playback rate multiplier (1.0 = as authored).
1487    #[wasm_bindgen(js_name = setSpeedScale)]
1488    pub fn set_speed_scale(&self, speed: f32) -> Result<(), JsValue> {
1489        with_player!(self, |p| p.set_speed_scale(speed))
1490    }
1491
1492    /// The speed in effect: `0` for a speed that was set to zero or below,
1493    /// since that is the stop it became.
1494    #[wasm_bindgen(js_name = speedScale)]
1495    pub fn speed_scale(&self) -> Result<f32, JsValue> {
1496        with_player!(self, |p| p.speed_scale())
1497    }
1498
1499    /// Whether this player is currently advancing.
1500    #[wasm_bindgen(js_name = isPlaying)]
1501    pub fn is_playing(&self) -> Result<bool, JsValue> {
1502        with_player!(self, |p| p.is_playing())
1503    }
1504
1505    /// Held in place rather than stopped: `isPlaying` stays true.
1506    #[wasm_bindgen(js_name = isPausing)]
1507    pub fn is_pausing(&self) -> Result<bool, JsValue> {
1508        with_player!(self, |p| p.is_pausing())
1509    }
1510
1511    /// Which way the playhead is actually travelling — not the heading
1512    /// `setPlaybackDirection` configured, which `playbackDirection` reports.
1513    /// Under ping-pong the return leg runs backward while that still reads
1514    /// forward. Gate audio on this: SpriteStudio has no reverse audio.
1515    #[wasm_bindgen(js_name = isPlayingForward)]
1516    pub fn is_playing_forward(&self) -> Result<bool, JsValue> {
1517        with_player!(self, |p| p.is_playing_forward())
1518    }
1519
1520    /// Every configured loop has played. Sticky, and never true under an
1521    /// infinite loop.
1522    #[wasm_bindgen(js_name = isFinished)]
1523    pub fn is_finished(&self) -> Result<bool, JsValue> {
1524        with_player!(self, |p| p.is_finished())
1525    }
1526
1527    /// Jump to `frame`. Fractional values are honoured.
1528    pub fn seek(&self, frame: f32) -> Result<(), JsValue> {
1529        with_player!(self, |p| p.seek(frame))
1530    }
1531
1532    /// Current playhead position, fractional.
1533    #[wasm_bindgen(js_name = frameNo)]
1534    pub fn frame_no(&self) -> Result<f32, JsValue> {
1535        with_player!(self, |p| p.frame_no())
1536    }
1537
1538    /// First frame of the range being played. Follows `setAnimationSection`.
1539    #[wasm_bindgen(js_name = startFrame)]
1540    pub fn start_frame(&self) -> Result<i32, JsValue> {
1541        with_player!(self, |p| p.start_frame())
1542    }
1543
1544    /// Last frame of the range being played.
1545    #[wasm_bindgen(js_name = endFrame)]
1546    pub fn end_frame(&self) -> Result<i32, JsValue> {
1547        with_player!(self, |p| p.end_frame())
1548    }
1549
1550    /// Length of that range, both ends inclusive — feed it to a scrubber.
1551    #[wasm_bindgen(js_name = totalFrames)]
1552    pub fn total_frames(&self) -> Result<i32, JsValue> {
1553        with_player!(self, |p| p.total_frames())
1554    }
1555
1556    /// `count` cycles then stop; `-1` (or `0`) loops forever. Under ping-pong
1557    /// one cycle is a full round trip.
1558    #[wasm_bindgen(js_name = setLoopCount)]
1559    pub fn set_loop_count(&self, count: i32) -> Result<(), JsValue> {
1560        with_player!(self, |p| p.set_loop_count(count))
1561    }
1562
1563    /// The configured loop count — before an animation is set up, the one
1564    /// `setLoopCount` is holding for it, or 0 when none was set.
1565    #[wasm_bindgen(js_name = loopCount)]
1566    pub fn loop_count(&self) -> Result<i32, JsValue> {
1567        with_player!(self, |p| p.loop_count())
1568    }
1569
1570    /// How many cycles of the loop count are left; 0 with no animation.
1571    #[wasm_bindgen(js_name = remainingLoops)]
1572    pub fn remaining_loops(&self) -> Result<i32, JsValue> {
1573        with_player!(self, |p| p.remaining_loops())
1574    }
1575
1576    /// Override the advance rate in fps. Prefer `setSpeedScale`, which scales
1577    /// playback without replacing the authored rate.
1578    #[wasm_bindgen(js_name = setFrameRate)]
1579    pub fn set_frame_rate(&self, fps: i32) -> Result<(), JsValue> {
1580        with_player!(self, |p| p.set_frame_rate(fps))
1581    }
1582
1583    /// The rate the animation advances at.
1584    #[wasm_bindgen(js_name = frameRate)]
1585    pub fn frame_rate(&self) -> Result<i32, JsValue> {
1586        with_player!(self, |p| p.frame_rate())
1587    }
1588
1589    /// Restrict playback to `start..=end` of the current animation. Call it
1590    /// *after* `setAnimation`, which rebuilds the tree and takes the section
1591    /// with it. Throws, changing nothing, on an end before the start when both
1592    /// are inside the animation; an end outside it is the animation's edge.
1593    #[wasm_bindgen(js_name = setAnimationSection)]
1594    pub fn set_animation_section(&self, start: i32, end: i32) -> Result<(), JsValue> {
1595        with_player!(self, |p| p.set_animation_section(start, end).map_err(|e| js_error(format!("setAnimationSection({start}, {end}): {e}")))?)
1596    }
1597
1598    /// `direction`: 0 forward, 1 backward. `style`: 0 normal, 1 ping-pong.
1599    /// Set as a pair — pass the current value for whichever you are not
1600    /// changing.
1601    #[wasm_bindgen(js_name = setPlaybackDirection)]
1602    pub fn set_playback_direction(&self, direction: i32, style: i32) -> Result<(), JsValue> {
1603        with_player!(self, |p| p.set_playback_direction(PlaybackDirection::from_wire(direction), PlaybackStyle::from_wire(style)))
1604    }
1605
1606    /// 0 forward, 1 backward.
1607    #[wasm_bindgen(js_name = playbackDirection)]
1608    pub fn playback_direction(&self) -> Result<i32, JsValue> {
1609        with_player!(self, |p| p.playback_direction().as_wire())
1610    }
1611
1612    /// 0 normal, 1 ping-pong.
1613    #[wasm_bindgen(js_name = playbackStyle)]
1614    pub fn playback_style(&self) -> Result<i32, JsValue> {
1615        with_player!(self, |p| p.playback_style().as_wire())
1616    }
1617
1618    /// On (the default) draws between authored frames; off floors the frame that
1619    /// is drawn, pinning playback to whole ones.
1620    ///
1621    /// The playhead keeps its fraction either way (`frameNo` reports it
1622    /// unrounded), and so does the stepping of instance and effect children.
1623    /// This affects only what is drawn.
1624    #[wasm_bindgen(js_name = setSubFrameEnabled)]
1625    pub fn set_sub_frame_enabled(&self, enabled: bool) -> Result<(), JsValue> {
1626        with_player!(self, |p| p.set_sub_frame_enabled(enabled))
1627    }
1628
1629    /// See `setSubFrameEnabled`.
1630    #[wasm_bindgen(js_name = subFrameEnabled)]
1631    pub fn sub_frame_enabled(&self) -> Result<bool, JsValue> {
1632        with_player!(self, |p| p.sub_frame_enabled())
1633    }
1634
1635    /// On (the default) keeps playback on the wall clock by dropping frames;
1636    /// off advances exactly one frame per `frame()` call.
1637    #[wasm_bindgen(js_name = setFrameSkipEnabled)]
1638    pub fn set_frame_skip_enabled(&self, skip: bool) -> Result<(), JsValue> {
1639        with_player!(self, |p| p.set_frame_skip_enabled(skip))
1640    }
1641
1642    /// See `setFrameSkipEnabled`.
1643    #[wasm_bindgen(js_name = frameSkipEnabled)]
1644    pub fn frame_skip_enabled(&self) -> Result<bool, JsValue> {
1645        with_player!(self, |p| p.frame_skip_enabled())
1646    }
1647
1648    // --- Per-part overrides ---
1649    //
1650    // Indices address the root animation and are stable within one pack, so
1651    // resolve a name once with `findPartIndex` and keep the index. Overrides do
1652    // not reach inside an instance part — its child runs as its own context.
1653    // Call them only after `setAnimation`, which is what sizes the runtime's
1654    // override table and clears everything but a permanent override.
1655
1656    /// Resolve a part name to its index in the current animation, or `-1` when
1657    /// the name is unknown or no animation is set up.
1658    #[wasm_bindgen(js_name = findPartIndex)]
1659    pub fn find_part_index(&self, name: &str) -> Result<i32, JsValue> {
1660        with_player!(self, |p| p.find_part_index(name).map(|i| i as i32).unwrap_or(-1))
1661    }
1662
1663    /// Force-hide a part (`hide` = true) or revert it to the animation.
1664    /// `cascade` propagates a force-hide to the part's descendants — a keyframe
1665    /// hide never cascades, so this is the only way to hide a sub-tree.
1666    #[wasm_bindgen(js_name = setPartVisibilityOverrideByIndex)]
1667    pub fn set_part_visibility_override_by_index(&self, part: u32, hide: bool, cascade: bool) -> Result<(), JsValue> {
1668        with_player!(self, |p| p.set_part_visibility_override_by_index(part, hide, cascade).map_err(js_err)?)
1669    }
1670
1671    /// Revert a part to the animation's own visibility.
1672    #[wasm_bindgen(js_name = clearPartVisibilityOverrideByIndex)]
1673    pub fn clear_part_visibility_override_by_index(&self, part: u32) -> Result<(), JsValue> {
1674        with_player!(self, |p| p.clear_part_visibility_override_by_index(part).map_err(js_err)?)
1675    }
1676
1677    /// Override a part's colour. `blendOp`: 0 mix, 1 mul, 2 add, 3 sub.
1678    /// `rgba` is packed `0xRRGGBBAA` in the authored 8-bit sRGB space — do not
1679    /// pre-multiply it. `priority`: 0 until the next keyframe, 1 until the next
1680    /// animation, 2 permanent. Normal parts only.
1681    #[wasm_bindgen(js_name = setPartColorOverrideByIndex)]
1682    pub fn set_part_color_override_by_index(&self, part: u32, rgba: u32, #[wasm_bindgen(js_name = "blendOp")] blend_op: u8, priority: u8) -> Result<(), JsValue> {
1683        let blend_op = BlendOp::from_wire(blend_op).ok_or_else(|| js_error("blendOp must be 0..=3"))?;
1684        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1685        with_player!(self, |p| p.set_part_color_override_by_index(part, rgba, blend_op, priority).map_err(js_err)?)
1686    }
1687
1688    /// Four-corner colour override, for a gradient. `corners` is 16 bytes in the
1689    /// runtime's order — left-top, right-top, left-bottom, right-bottom, each
1690    /// `[r, g, b, a]`. Otherwise as `setPartColorOverride`.
1691    #[wasm_bindgen(js_name = setPartColorOverrideCornersByIndex)]
1692    pub fn set_part_color_override_corners_by_index(&self, part: u32, corners: &[u8], #[wasm_bindgen(js_name = "blendOp")] blend_op: u8, priority: u8) -> Result<(), JsValue> {
1693        let blend_op = BlendOp::from_wire(blend_op).ok_or_else(|| js_error("blendOp must be 0..=3"))?;
1694        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1695        if corners.len() != 16 {
1696            return Err(js_error("corners must be 16 bytes (4 corners x RGBA)"));
1697        }
1698        let mut rgba = [[0u8; 4]; 4];
1699        rgba.copy_from_slice(corners.as_chunks::<4>().0);
1700        with_player!(self, |p| p.set_part_color_override_corners_by_index(part, rgba, blend_op, priority).map_err(js_err)?)
1701    }
1702
1703    /// Revert a part to the animation's own colour.
1704    #[wasm_bindgen(js_name = clearPartColorOverrideByIndex)]
1705    pub fn clear_part_color_override_by_index(&self, part: u32) -> Result<(), JsValue> {
1706        with_player!(self, |p| p.clear_part_color_override_by_index(part).map_err(js_err)?)
1707    }
1708
1709    /// Make a part draw a different cell. `cellmapName` is written without the
1710    /// `.ssce` extension. Normal and Mask parts only; throws when the cell
1711    /// cannot be resolved against the loaded pack.
1712    #[wasm_bindgen(js_name = setPartCellOverrideByIndex)]
1713    pub fn set_part_cell_override_by_index(&self, part: u32, #[wasm_bindgen(js_name = "cellmapName")] cellmap_name: &str, #[wasm_bindgen(js_name = "cellName")] cell_name: &str, priority: u8) -> Result<(), JsValue> {
1714        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1715        with_player!(self, |p| p.set_part_cell_override_by_index(part, cellmap_name, cell_name, priority).map_err(js_err)?)
1716    }
1717
1718    /// Revert a part to the animation's own cell.
1719    #[wasm_bindgen(js_name = clearPartCellOverrideByIndex)]
1720    pub fn clear_part_cell_override_by_index(&self, part: u32) -> Result<(), JsValue> {
1721        with_player!(self, |p| p.clear_part_cell_override_by_index(part).map_err(js_err)?)
1722    }
1723
1724    // --- overrides, by part name ---
1725    //
1726    // The unsuffixed form takes a NAME; `ByIndex` is the optimisation for a
1727    // caller that cached one. wasm-bindgen
1728    // cannot express a `string | number` union, so the two are separate methods
1729    // here rather than one overload as in the browser Players.
1730
1731    /// Force-hide a part by name, or revert it to the animation.
1732    #[wasm_bindgen(js_name = setPartVisibilityOverride)]
1733    pub fn set_part_visibility_override(&self, part: &str, hide: bool, cascade: bool) -> Result<(), JsValue> {
1734        with_player!(self, |p| p.set_part_visibility_override(part, hide, cascade).map_err(js_err)?)
1735    }
1736
1737    /// Revert a part to the animation's own visibility, by name.
1738    #[wasm_bindgen(js_name = clearPartVisibilityOverride)]
1739    pub fn clear_part_visibility_override(&self, part: &str) -> Result<(), JsValue> {
1740        with_player!(self, |p| p.clear_part_visibility_override(part).map_err(js_err)?)
1741    }
1742
1743    /// Override a part's colour by name. Arguments as `setPartColorOverrideByIndex`.
1744    #[wasm_bindgen(js_name = setPartColorOverride)]
1745    pub fn set_part_color_override(&self, part: &str, rgba: u32, #[wasm_bindgen(js_name = "blendOp")] blend_op: u8, priority: u8) -> Result<(), JsValue> {
1746        let blend_op = BlendOp::from_wire(blend_op).ok_or_else(|| js_error("blendOp must be 0..=3"))?;
1747        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1748        with_player!(self, |p| p.set_part_color_override(part, rgba, blend_op, priority).map_err(js_err)?)
1749    }
1750
1751    /// Four-corner colour override by name. Arguments as the `ByIndex` sibling.
1752    #[wasm_bindgen(js_name = setPartColorOverrideCorners)]
1753    pub fn set_part_color_override_corners(&self, part: &str, corners: &[u8], #[wasm_bindgen(js_name = "blendOp")] blend_op: u8, priority: u8) -> Result<(), JsValue> {
1754        let blend_op = BlendOp::from_wire(blend_op).ok_or_else(|| js_error("blendOp must be 0..=3"))?;
1755        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1756        if corners.len() != 16 {
1757            return Err(js_error("corners must be 16 bytes (4 corners x RGBA)"));
1758        }
1759        let mut rgba = [[0u8; 4]; 4];
1760        rgba.copy_from_slice(corners.as_chunks::<4>().0);
1761        with_player!(self, |p| p.set_part_color_override_corners(part, rgba, blend_op, priority).map_err(js_err)?)
1762    }
1763
1764    /// Revert a part to the animation's own colour, by name.
1765    #[wasm_bindgen(js_name = clearPartColorOverride)]
1766    pub fn clear_part_color_override(&self, part: &str) -> Result<(), JsValue> {
1767        with_player!(self, |p| p.clear_part_color_override(part).map_err(js_err)?)
1768    }
1769
1770    /// Make a part draw a different cell, by name.
1771    #[wasm_bindgen(js_name = setPartCellOverride)]
1772    pub fn set_part_cell_override(&self, part: &str, #[wasm_bindgen(js_name = "cellmapName")] cellmap_name: &str, #[wasm_bindgen(js_name = "cellName")] cell_name: &str, priority: u8) -> Result<(), JsValue> {
1773        let priority = OverridePriority::from_wire(priority).ok_or_else(|| js_error("priority must be 0..=2"))?;
1774        with_player!(self, |p| p.set_part_cell_override(part, cellmap_name, cell_name, priority).map_err(js_err)?)
1775    }
1776
1777    /// Revert a part to the animation's own cell, by name.
1778    #[wasm_bindgen(js_name = clearPartCellOverride)]
1779    pub fn clear_part_cell_override(&self, part: &str) -> Result<(), JsValue> {
1780        with_player!(self, |p| p.clear_part_cell_override(part).map_err(js_err)?)
1781    }
1782
1783    /// A part's current-frame transform by name, as the six affine terms, or an
1784    /// empty array when the name is unknown.
1785    #[wasm_bindgen(js_name = partTransform)]
1786    pub fn part_transform(&self, part: &str) -> Result<Vec<f32>, JsValue> {
1787        with_player!(self, |p| p.part_transform(part).map(|m| m.to_vec()).unwrap_or_default())
1788    }
1789
1790    /// Whether the part is hidden on the frame the last `frame()` built, or
1791    /// `undefined` when the pack has no such part. An override shows from the next
1792    /// `frame()`.
1793    ///
1794    /// The companion to `partTransform`, which reports where a part *would* be
1795    /// whether or not it is drawn — a host following a part needs both.
1796    #[wasm_bindgen(js_name = isPartHidden)]
1797    pub fn is_part_hidden(&self, part: &str) -> Result<Option<bool>, JsValue> {
1798        with_player!(self, |p| p.is_part_hidden(part))
1799    }
1800
1801    /// Whether the part is a **skinned** mesh — one whose vertices are drawn by
1802    /// bone skinning — or `undefined` when the pack has no such part.
1803    ///
1804    /// A skinned mesh cannot be followed with `partTransform`: its node stays at
1805    /// the setup position (near the character root) while the bones move the
1806    /// visible vertices, so a follower would snap to the root. A picker can use
1807    /// this to warn, or to steer the choice to a null / bone part. A rigid
1808    /// (deform-only) mesh follows correctly and reports `false`.
1809    #[wasm_bindgen(js_name = isPartSkinnedMesh)]
1810    pub fn is_part_skinned_mesh(&self, part: &str) -> Result<Option<bool>, JsValue> {
1811        with_player!(self, |p| p.is_part_skinned_mesh(part))
1812    }
1813
1814    /// Index form of `isPartHidden`, for the `partIndex` an event carries or a
1815    /// slot in `partNames`; `undefined` when `part` is out of range.
1816    #[wasm_bindgen(js_name = isPartHiddenByIndex)]
1817    pub fn is_part_hidden_by_index(&self, part: u32) -> Result<Option<bool>, JsValue> {
1818        with_player!(self, |p| p.is_part_hidden_by_index(part))
1819    }
1820
1821    /// Index form of `isPartSkinnedMesh`; `undefined` when `part` is out of range.
1822    #[wasm_bindgen(js_name = isPartSkinnedMeshByIndex)]
1823    pub fn is_part_skinned_mesh_by_index(&self, part: u32) -> Result<Option<bool>, JsValue> {
1824        with_player!(self, |p| p.is_part_skinned_mesh_by_index(part))
1825    }
1826
1827    /// Every part name, in part-index order — what turns the `partIndex` an event
1828    /// carries back into something a human reads, and what fills a part picker.
1829    ///
1830    /// An unnamed part holds its slot as an empty string, so the array stays
1831    /// index-aligned. `length` is the part count, and unlike `partCount`, which
1832    /// is 0 until an animation is set up, it is there as soon as a pack is bound.
1833    #[wasm_bindgen(js_name = partNames)]
1834    pub fn part_names(&self) -> Result<Vec<String>, JsValue> {
1835        with_player!(self, |p| p.part_names().unwrap_or_default())
1836    }
1837
1838    /// Every cellmap name in the pack, without the `.ssce` extension — the
1839    /// namespace `setPartCellOverride` takes.
1840    #[wasm_bindgen(js_name = cellmapNames)]
1841    pub fn cellmap_names(&self) -> Result<Vec<String>, JsValue> {
1842        with_player!(self, |p| p.cellmap_names().unwrap_or_default())
1843    }
1844
1845    /// The cell names inside one cellmap — the other half of what
1846    /// `setPartCellOverride` takes.
1847    #[wasm_bindgen(js_name = cellNames)]
1848    pub fn cell_names(&self, #[wasm_bindgen(js_name = "cellmapName")] cellmap_name: &str) -> Result<Vec<String>, JsValue> {
1849        with_player!(self, |p| p.cell_names(cellmap_name).unwrap_or_default())
1850    }
1851
1852    /// Drop every override on the root animation at once.
1853    #[wasm_bindgen(js_name = clearAllPartOverrides)]
1854    pub fn clear_all_part_overrides(&self) -> Result<(), JsValue> {
1855        with_player!(self, |p| p.clear_all_part_overrides())
1856    }
1857
1858    /// How many parts the root animation has; 0 before one is set up.
1859    #[wasm_bindgen(js_name = partCount)]
1860    pub fn part_count(&self) -> Result<usize, JsValue> {
1861        with_player!(self, |p| p.part_count())
1862    }
1863
1864    // --- Motion blending: tracks and sources ---
1865    //
1866    // The track stack: tracks fold onto the setup pose in ascending order,
1867    // track 0 being what `setAnimation` establishes. A track's alpha is its
1868    // strength; a source's weight only sets proportions among the animations
1869    // sharing one track. A read of a track or source that does not exist answers
1870    // `undefined`; a command on one throws.
1871
1872    /// Put `name` on `track`, replacing what it was playing. Track 0 is better set
1873    /// with `setAnimation`, which rebuilds the instance tree. On track 0 it still
1874    /// makes `name` the current animation.
1875    #[wasm_bindgen(js_name = setTrackAnimation)]
1876    pub fn set_track_animation(&self, track: u32, name: &str) -> Result<(), JsValue> {
1877        with_player!(self, |p| p.set_track_animation(track, name).map_err(js_err)?)
1878    }
1879
1880    /// Number of tracks, empty ones included; 0 before an animation is set up.
1881    #[wasm_bindgen(js_name = trackCount)]
1882    pub fn track_count(&self) -> Result<u32, JsValue> {
1883        with_player!(self, |p| p.track_count())
1884    }
1885
1886    /// Silence a track. Track 0 is refused — fade it to alpha 0 instead.
1887    #[wasm_bindgen(js_name = clearTrack)]
1888    pub fn clear_track(&self, track: u32) -> Result<(), JsValue> {
1889        with_player!(self, |p| p.clear_track(track).map_err(js_err)?)
1890    }
1891
1892    /// How much of `track` survives onto the pose below. Not clamped: above 1
1893    /// extrapolates, 0 or below contributes nothing.
1894    #[wasm_bindgen(js_name = setTrackAlpha)]
1895    pub fn set_track_alpha(&self, track: u32, alpha: f32) -> Result<(), JsValue> {
1896        with_player!(self, |p| p.set_track_alpha(track, alpha).map_err(js_err)?)
1897    }
1898
1899    /// `track`'s alpha, or `undefined` when there is no such track.
1900    #[wasm_bindgen(js_name = trackAlpha)]
1901    pub fn track_alpha(&self, track: u32) -> Result<Option<f32>, JsValue> {
1902        with_player!(self, |p| p.track_alpha(track))
1903    }
1904
1905    /// `blend`: 0 = mix (lerp onto what is below), 1 = additive (offset from the setup pose).
1906    #[wasm_bindgen(js_name = setTrackBlend)]
1907    pub fn set_track_blend(&self, track: u32, blend: u32) -> Result<(), JsValue> {
1908        let blend = match blend {
1909            0 => crate::TrackBlend::Mix,
1910            1 => crate::TrackBlend::Additive,
1911            _ => return Err(js_error("blend must be 0 (mix) or 1 (additive)")),
1912        };
1913        with_player!(self, |p| p.set_track_blend(track, blend).map_err(js_err)?)
1914    }
1915
1916    /// 0 = mix, 1 = additive.
1917    #[wasm_bindgen(js_name = trackBlend)]
1918    pub fn track_blend(&self, track: u32) -> Result<Option<u32>, JsValue> {
1919        with_player!(self, |p| p.track_blend(track).map(|b| match b {
1920            crate::TrackBlend::Mix => 0,
1921            crate::TrackBlend::Additive => 1,
1922        }))
1923    }
1924
1925    /// `sync`: 0 = free (an animation laid on the track starts from its head),
1926    /// 1 = start (it starts at the phase track 0 stands at). Set it before
1927    /// laying; `setAnimation` resets every track to free.
1928    #[wasm_bindgen(js_name = setTrackSync)]
1929    pub fn set_track_sync(&self, track: u32, sync: u32) -> Result<(), JsValue> {
1930        let sync = match sync {
1931            0 => crate::TrackSync::Free,
1932            1 => crate::TrackSync::Start,
1933            _ => return Err(js_error("sync must be 0 (free) or 1 (start)")),
1934        };
1935        with_player!(self, |p| p.set_track_sync(track, sync).map_err(js_err)?)
1936    }
1937
1938    /// 0 = free, 1 = start.
1939    #[wasm_bindgen(js_name = trackSync)]
1940    pub fn track_sync(&self, track: u32) -> Result<Option<u32>, JsValue> {
1941        with_player!(self, |p| p.track_sync(track).map(|s| match s {
1942            crate::TrackSync::Free => 0,
1943            crate::TrackSync::Start => 1,
1944        }))
1945    }
1946
1947    /// Fade `track` to `name` over `durationMs`, starting from whatever it is
1948    /// playing. Advanced by `frame()`. On track 0, `name` takes over from the
1949    /// call on: it is the current animation, its state is what `isFinished`
1950    /// reports, and it plays with the speed, direction and loop count the page
1951    /// set. The instance tree is not rebuilt; the instance and effect parts
1952    /// belong to the pack, so the running children carry on.
1953    pub fn crossfade(&self, track: u32, name: &str, #[wasm_bindgen(js_name = "durationMs")] duration_ms: f32) -> Result<(), JsValue> {
1954        with_player!(self, |p| p.crossfade(track, name, duration_ms).map_err(js_err)?)
1955    }
1956
1957    /// Drive `track`'s alpha to `target` over `durationMs`. Fading track 0 to 0
1958    /// settles the character onto the setup pose.
1959    #[wasm_bindgen(js_name = fadeTrack)]
1960    pub fn fade_track(&self, track: u32, target: f32, #[wasm_bindgen(js_name = "durationMs")] duration_ms: f32) -> Result<(), JsValue> {
1961        with_player!(self, |p| p.fade_track(track, target, duration_ms).map_err(js_err)?)
1962    }
1963
1964    /// How far the fade on `track` has got, 0 to 1; `undefined` when it is not fading.
1965    #[wasm_bindgen(js_name = trackFadeProgress)]
1966    pub fn track_fade_progress(&self, track: u32) -> Result<Option<f32>, JsValue> {
1967        with_player!(self, |p| p.track_fade_progress(track))
1968    }
1969
1970    /// Stop the fade on `track`, leaving alpha and weights where they stand.
1971    #[wasm_bindgen(js_name = cancelTrackFade)]
1972    pub fn cancel_track_fade(&self, track: u32) -> Result<(), JsValue> {
1973        with_player!(self, |p| p.cancel_track_fade(track).map_err(js_err)?)
1974    }
1975
1976    /// Seek `track`'s animation — how a continuous-control axis is driven.
1977    #[wasm_bindgen(js_name = setTrackFrame)]
1978    pub fn set_track_frame(&self, track: u32, frame: f32) -> Result<(), JsValue> {
1979        with_player!(self, |p| p.set_track_frame(track, frame).map_err(js_err)?)
1980    }
1981
1982    /// `track`'s playhead, or `undefined` when there is no such track.
1983    #[wasm_bindgen(js_name = trackFrame)]
1984    pub fn track_frame(&self, track: u32) -> Result<Option<f32>, JsValue> {
1985        with_player!(self, |p| p.track_frame(track))
1986    }
1987
1988    /// `track`'s own playback speed; 0 parks it, which is how a scrubbed axis
1989    /// stays where `setTrackFrame` puts it.
1990    #[wasm_bindgen(js_name = setTrackSpeed)]
1991    pub fn set_track_speed(&self, track: u32, speed: f32) -> Result<(), JsValue> {
1992        with_player!(self, |p| p.set_track_speed(track, speed).map_err(js_err)?)
1993    }
1994
1995    // A track's playback settings are the track's, not its animation's: they
1996    // reach every animation on it now, both sides of a crossfade included, and
1997    // every one laid on it later. Track 0's are the transport calls above
1998    // (`setSpeedScale` and the rest). The loop count is the exception: it
1999    // belongs to the animation, and laying another one starts it looping
2000    // forever again.
2001
2002    /// `track`'s speed (see `setTrackSpeed`), or `undefined` when there is no such track.
2003    #[wasm_bindgen(js_name = trackSpeed)]
2004    pub fn track_speed(&self, track: u32) -> Result<Option<f32>, JsValue> {
2005        with_player!(self, |p| p.track_speed(track))
2006    }
2007
2008    /// `setFrameRate` for one track.
2009    #[wasm_bindgen(js_name = setTrackFrameRate)]
2010    pub fn set_track_frame_rate(&self, track: u32, fps: i32) -> Result<(), JsValue> {
2011        with_player!(self, |p| p.set_track_frame_rate(track, fps).map_err(js_err)?)
2012    }
2013
2014    /// The rate `track`'s animation plays at, the override or the authored
2015    /// rate; 0 for a track with neither.
2016    #[wasm_bindgen(js_name = trackFrameRate)]
2017    pub fn track_frame_rate(&self, track: u32) -> Result<Option<i32>, JsValue> {
2018        with_player!(self, |p| p.track_frame_rate(track))
2019    }
2020
2021    /// `setFrameSkipEnabled` for one track.
2022    #[wasm_bindgen(js_name = setTrackFrameSkipEnabled)]
2023    pub fn set_track_frame_skip_enabled(&self, track: u32, skip: bool) -> Result<(), JsValue> {
2024        with_player!(self, |p| p.set_track_frame_skip_enabled(track, skip).map_err(js_err)?)
2025    }
2026
2027    /// Whether `track` skips frames to keep time, or `undefined` when there is no such track.
2028    #[wasm_bindgen(js_name = trackFrameSkipEnabled)]
2029    pub fn track_frame_skip_enabled(&self, track: u32) -> Result<Option<bool>, JsValue> {
2030        with_player!(self, |p| p.track_frame_skip_enabled(track))
2031    }
2032
2033    /// `setPlaybackDirection` for one track, with the same `0` / `1` values.
2034    #[wasm_bindgen(js_name = setTrackPlaybackDirection)]
2035    pub fn set_track_playback_direction(&self, track: u32, direction: i32, style: i32) -> Result<(), JsValue> {
2036        with_player!(self, |p| p.set_track_playback_direction(track, PlaybackDirection::from_wire(direction), PlaybackStyle::from_wire(style)).map_err(js_err)?)
2037    }
2038
2039    /// 0 = forward, 1 = backward.
2040    #[wasm_bindgen(js_name = trackPlaybackDirection)]
2041    pub fn track_playback_direction(&self, track: u32) -> Result<Option<i32>, JsValue> {
2042        with_player!(self, |p| p.track_playback_direction(track).map(PlaybackDirection::as_wire))
2043    }
2044
2045    /// 0 = normal, 1 = ping-pong.
2046    #[wasm_bindgen(js_name = trackPlaybackStyle)]
2047    pub fn track_playback_style(&self, track: u32) -> Result<Option<i32>, JsValue> {
2048        with_player!(self, |p| p.track_playback_style(track).map(PlaybackStyle::as_wire))
2049    }
2050
2051    /// How many times `track`'s animation plays before it holds its last
2052    /// frame; `-1` (or `0`) loops forever. Set it after laying the animation:
2053    /// one is laid looping forever. On track 0 this is `setLoopCount`, and the
2054    /// player keeps the count for every animation laid there.
2055    #[wasm_bindgen(js_name = setTrackLoopCount)]
2056    pub fn set_track_loop_count(&self, track: u32, count: i32) -> Result<(), JsValue> {
2057        with_player!(self, |p| p.set_track_loop_count(track, count).map_err(js_err)?)
2058    }
2059
2060    /// `-1` for a track that loops forever; `undefined` for one with no animation.
2061    #[wasm_bindgen(js_name = trackLoopCount)]
2062    pub fn track_loop_count(&self, track: u32) -> Result<Option<i32>, JsValue> {
2063        with_player!(self, |p| p.track_loop_count(track))
2064    }
2065
2066    /// Whether `track`'s animation has played its loop count out and holds its
2067    /// last frame. A state, as `isFinished` is for track 0; there is no edge.
2068    #[wasm_bindgen(js_name = isTrackFinished)]
2069    pub fn is_track_finished(&self, track: u32) -> Result<bool, JsValue> {
2070        with_player!(self, |p| p.is_track_finished(track))
2071    }
2072
2073    /// Whether the last `frame()` wrapped `track`'s animation back to its
2074    /// start, as `justLooped` is for track 0.
2075    #[wasm_bindgen(js_name = trackJustLooped)]
2076    pub fn track_just_looped(&self, track: u32) -> Result<bool, JsValue> {
2077        with_player!(self, |p| p.track_just_looped(track))
2078    }
2079
2080    /// How far into a crossfade on `track` the outgoing animation keeps firing
2081    /// events: while its share of the track, `1 - progress`, is at least
2082    /// `threshold`. The default, `Infinity`, silences it from the moment the
2083    /// fade begins; `0.5` keeps it firing for the first half. Kept by the track.
2084    /// The update that completes the fade has already released the outgoing
2085    /// animation, so it fires nothing there, even at `0`.
2086    #[wasm_bindgen(js_name = setTrackOutgoingEventThreshold)]
2087    pub fn set_track_outgoing_event_threshold(&self, track: u32, threshold: f32) -> Result<(), JsValue> {
2088        with_player!(self, |p| p.set_track_outgoing_event_threshold(track, threshold).map_err(js_err)?)
2089    }
2090
2091    /// The threshold the outgoing side of a crossfade on `track` fires its events
2092    /// at, or `undefined` when there is no such track.
2093    #[wasm_bindgen(js_name = trackOutgoingEventThreshold)]
2094    pub fn track_outgoing_event_threshold(&self, track: u32) -> Result<Option<f32>, JsValue> {
2095        with_player!(self, |p| p.track_outgoing_event_threshold(track))
2096    }
2097
2098    /// The source carrying `track`'s animation; `undefined` when it has none.
2099    #[wasm_bindgen(js_name = trackMainSource)]
2100    pub fn track_main_source(&self, track: u32) -> Result<Option<u32>, JsValue> {
2101        with_player!(self, |p| p.track_main_source(track))
2102    }
2103
2104    /// Lay `name` on `track` beside what it already carries, at `weight`, and
2105    /// return its handle. On an empty track it becomes the main source.
2106    #[wasm_bindgen(js_name = addTrackSource)]
2107    pub fn add_track_source(&self, track: u32, name: &str, weight: f32) -> Result<u32, JsValue> {
2108        with_player!(self, |p| p.add_track_source(track, name, weight).map_err(js_err)?)
2109    }
2110
2111    /// A source's share **within its track**; weights are ratios.
2112    #[wasm_bindgen(js_name = setSourceWeight)]
2113    pub fn set_source_weight(&self, source: u32, weight: f32) -> Result<(), JsValue> {
2114        with_player!(self, |p| p.set_source_weight(source, weight).map_err(js_err)?)
2115    }
2116
2117    /// `source`'s weight within its track, or `undefined` when there is no such source.
2118    #[wasm_bindgen(js_name = sourceWeight)]
2119    pub fn source_weight(&self, source: u32) -> Result<Option<f32>, JsValue> {
2120        with_player!(self, |p| p.source_weight(source))
2121    }
2122
2123    /// Seek one source — how a page keeps sources of different lengths in step.
2124    #[wasm_bindgen(js_name = setSourceFrame)]
2125    pub fn set_source_frame(&self, source: u32, frame: f32) -> Result<(), JsValue> {
2126        with_player!(self, |p| p.set_source_frame(source, frame).map_err(js_err)?)
2127    }
2128
2129    /// `source`'s playhead, or `undefined` when there is no such source.
2130    #[wasm_bindgen(js_name = sourceFrame)]
2131    pub fn source_frame(&self, source: u32) -> Result<Option<f32>, JsValue> {
2132        with_player!(self, |p| p.source_frame(source))
2133    }
2134
2135    /// The weight at or above which `source` fires its events. Only track 0's
2136    /// main source fires by default (the default threshold is `Infinity`); lower
2137    /// this to the source's weight or below to have it fire too.
2138    #[wasm_bindgen(js_name = setSourceEventThreshold)]
2139    pub fn set_source_event_threshold(&self, source: u32, threshold: f32) -> Result<(), JsValue> {
2140        with_player!(self, |p| p.set_source_event_threshold(source, threshold).map_err(js_err)?)
2141    }
2142
2143    /// The weight `source` must reach for its events to fire, or `undefined` when
2144    /// there is no such source.
2145    #[wasm_bindgen(js_name = sourceEventThreshold)]
2146    pub fn source_event_threshold(&self, source: u32) -> Result<Option<f32>, JsValue> {
2147        with_player!(self, |p| p.source_event_threshold(source))
2148    }
2149
2150    // --- Events ---
2151    //
2152    // Polled after `frame()`, which is what advanced the clock. All four
2153    // describe that tick and are replaced by the next one.
2154
2155    /// Whether the last `frame()` was the first to run after a `play()` /
2156    /// `playFrom()` — true for exactly one call. Not raised by `resume()`, which
2157    /// carries on rather than starting.
2158    #[wasm_bindgen(js_name = justStarted)]
2159    pub fn just_started(&self) -> Result<bool, JsValue> {
2160        with_player!(self, |p| p.just_started())
2161    }
2162
2163    /// Whether the last `frame()` crossed a loop boundary. One report per call
2164    /// however many cycles it crossed.
2165    #[wasm_bindgen(js_name = justLooped)]
2166    pub fn just_looped(&self) -> Result<bool, JsValue> {
2167        with_player!(self, |p| p.just_looped())
2168    }
2169
2170    /// Whether the last `frame()` **completed** playback — true for exactly one
2171    /// call, unlike the sticky `isFinished`. Never true under an infinite loop,
2172    /// and not raised by `stop()`.
2173    #[wasm_bindgen(js_name = justFinished)]
2174    pub fn just_finished(&self) -> Result<bool, JsValue> {
2175        with_player!(self, |p| p.just_finished())
2176    }
2177
2178    /// Timeline events the last `frame()` crossed, as an array of plain objects
2179    /// tagged by `kind`:
2180    ///
2181    /// ```js
2182    /// { kind: 'userData', partIndex, integer?, rect?, point?, text? }
2183    /// { kind: 'signal', partIndex, commandId, params: [{ id, value }] }
2184    /// { kind: 'audio', partIndex, soundName, soundListNameHash, soundNameHash, loopNum }
2185    /// ```
2186    ///
2187    /// Every kind also carries `frameNo` (the frame the key is authored on),
2188    /// `partName`, and `source`: the handle of the source on the track stack
2189    /// that fired it, which tells events apart once another source has opted in
2190    /// with `setSourceEventThreshold`.
2191    ///
2192    /// **Frames skipped over are still represented**: a long tick reports every
2193    /// frame it stepped through, not just the one it landed on. Empty on a tick
2194    /// that crossed nothing, and on a culled player, which does not advance; a
2195    /// hidden one reports as usual.
2196    pub fn events(&self) -> Result<js_sys::Array, JsValue> {
2197        with_player!(self, |p| {
2198            let out = js_sys::Array::new();
2199            for event in p.events() {
2200                out.push(&event_to_js(event));
2201            }
2202            out
2203        })
2204    }
2205
2206    /// The part's transform on the current frame as the 2D affine
2207    /// `[m00, m01, m10, m11, tx, ty]` — the same six numbers `ssplayer-webgl`'s
2208    /// `getPartTransform` returns, in animation-local (Y-down) space, with
2209    /// neither `setTransform` nor the canvas projection applied.
2210    ///
2211    /// Empty when no animation is set up or `part` is out of range. Read it
2212    /// after `frame()`: it describes the frame that produced. Hidden parts still
2213    /// report where they would have been.
2214    #[wasm_bindgen(js_name = partTransformByIndex)]
2215    pub fn part_transform_by_index(&self, part: u32) -> Result<Vec<f32>, JsValue> {
2216        with_player!(self, |p| p.part_transform_by_index(part).map(|m| m.to_vec()).unwrap_or_default())
2217    }
2218
2219    /// Place this player in the scene, in pixels from the canvas centre, with
2220    /// `y` measured **downward** (as `partTransform` reports, and as ForWeb's
2221    /// `offsetY` means it). `rotation` is in radians.
2222    #[wasm_bindgen(js_name = setTransform)]
2223    pub fn set_transform(&self, x: f32, y: f32, #[wasm_bindgen(js_name = "scaleX")] scale_x: f32, #[wasm_bindgen(js_name = "scaleY")] scale_y: f32, rotation: f32) -> Result<(), JsValue> {
2224        with_player!(self, |p| p.set_transform(x, y, scale_x, scale_y, rotation))
2225    }
2226
2227    /// Back to the identity placement (centred, unscaled, unrotated).
2228    #[wasm_bindgen(js_name = resetTransform)]
2229    pub fn reset_transform(&self) -> Result<(), JsValue> {
2230        with_player!(self, |p| p.reset_transform())
2231    }
2232
2233    /// The authored canvas of the animation now playing, as
2234    /// `{ x, y, width, height }` in player-local units — the box
2235    /// [`SsPlayerWeb::fit_into`] fits when you pass no `frame` of your own.
2236    ///
2237    /// `undefined` when no animation is set up. It is the frame the artist
2238    /// composed in, placed against the origin by the animation's pivot, not a
2239    /// measured bounding box.
2240    #[wasm_bindgen(js_name = canvasRect)]
2241    pub fn canvas_rect(&self) -> Result<JsValue, JsValue> {
2242        with_player!(self, |p| match p.canvas_rect() {
2243            Some(rect) => {
2244                let out = js_sys::Object::new();
2245                set_number(&out, "x", rect.x);
2246                set_number(&out, "y", rect.y);
2247                set_number(&out, "width", rect.width);
2248                set_number(&out, "height", rect.height);
2249                out.into()
2250            }
2251            None => JsValue::UNDEFINED,
2252        })
2253    }
2254
2255    /// Fit the animation into a `width` x `height` box and place it there, as
2256    /// `setTransform` would. Returns what was written, as
2257    /// `{ x, y, scaleX, scaleY }`.
2258    ///
2259    /// ```js
2260    /// player.fitInto(canvas.width, canvas.height, { fit: 'contain', align: 'bottom' });
2261    /// ```
2262    ///
2263    /// Every field of the options object is optional:
2264    ///
2265    /// * `fit` — `'contain'` (default) | `'cover'` | `'none'`
2266    /// * `align` — `'center'` (default), `'top'`, `'bottom'`, `'left'`,
2267    ///   `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`,
2268    ///   `'bottom-right'`
2269    /// * `frame` — `{ x, y, width, height }` in player-local units. Supply it and
2270    ///   nothing is read from the pack
2271    /// * `offsetX` / `offsetY` — pixels, applied **after** the fit
2272    /// * `scale` — a multiplier **on top of** the fit's scale (default 1)
2273    /// * `flipX` / `flipY` — mirrors; the alignment follows them
2274    /// * `rotation` — radians, passed straight through
2275    ///
2276    /// The size is in **canvas pixels**, so call it again on resize and after
2277    /// `setAnimation` when the canvas differs. A collapsed box, or no animation,
2278    /// places the player centred and unscaled rather than throwing. An
2279    /// unrecognised `fit` or `align` does throw, naming what it accepts.
2280    #[wasm_bindgen(js_name = fitInto)]
2281    pub fn fit_into(&self, width: f32, height: f32, options: Option<js_sys::Object>) -> Result<js_sys::Object, JsValue> {
2282        let placement = read_placement(options.as_ref())?;
2283        with_player!(self, |p| {
2284            let placed = p.fit_into(width, height, &placement);
2285            let out = js_sys::Object::new();
2286            set_number(&out, "x", placed.x);
2287            set_number(&out, "y", placed.y);
2288            set_number(&out, "scaleX", placed.scale_x);
2289            set_number(&out, "scaleY", placed.scale_y);
2290            out
2291        })
2292    }
2293
2294    /// Draw order within the canvas; lower draws first.
2295    #[wasm_bindgen(js_name = setOrder)]
2296    pub fn set_order(&self, order: i32) -> Result<(), JsValue> {
2297        with_player!(self, |p| p.set_order(order))
2298    }
2299
2300    /// The draw order `setOrder` set.
2301    pub fn order(&self) -> Result<i32, JsValue> {
2302        with_player!(self, |p| p.order())
2303    }
2304
2305    /// Hide this player. A hidden player draws nothing but keeps playing: its
2306    /// playhead advances and its events are reported.
2307    #[wasm_bindgen(js_name = setVisible)]
2308    pub fn set_visible(&self, visible: bool) -> Result<(), JsValue> {
2309        with_player!(self, |p| p.set_visible(visible))
2310    }
2311
2312    /// Whether this player draws, as `setVisible` set it.
2313    #[wasm_bindgen(js_name = isVisible)]
2314    pub fn is_visible(&self) -> Result<bool, JsValue> {
2315        with_player!(self, |p| p.is_visible())
2316    }
2317
2318    /// Cull this player. A culled player is skipped by both update and draw, so
2319    /// it costs nothing and its playhead stops where it was.
2320    #[wasm_bindgen(js_name = setCulled)]
2321    pub fn set_culled(&self, culled: bool) -> Result<(), JsValue> {
2322        with_player!(self, |p| p.set_culled(culled))
2323    }
2324
2325    /// Whether this player is culled, as `setCulled` set it.
2326    #[wasm_bindgen(js_name = isCulled)]
2327    pub fn is_culled(&self) -> Result<bool, JsValue> {
2328        with_player!(self, |p| p.is_culled())
2329    }
2330
2331    /// Player-level fade in 0..1, multiplied into every part — so overlapping
2332    /// parts read more opaque than `alpha`, unless the canvas fades each player
2333    /// as one layer (`SsSurfaceWeb.setGroupAlpha`).
2334    #[wasm_bindgen(js_name = setAlpha)]
2335    pub fn set_alpha(&self, alpha: f32) -> Result<(), JsValue> {
2336        with_player!(self, |p| p.set_alpha(alpha))
2337    }
2338
2339    /// The player-level fade in effect, after `setAlpha` clamped it to 0..1.
2340    pub fn alpha(&self) -> Result<f32, JsValue> {
2341        with_player!(self, |p| p.alpha())
2342    }
2343
2344    /// Player-level tint as `0xRRGGBB`, multiplied into every part after the
2345    /// PartColor blend. `0xffffff` (the default) leaves colours untouched — the
2346    /// same property `tint` names on `@spritestudio/ssplayer-webgl`.
2347    #[wasm_bindgen(js_name = setTint)]
2348    pub fn set_tint(&self, rgb: u32) -> Result<(), JsValue> {
2349        with_player!(self, |p| p.set_tint(rgb))
2350    }
2351
2352    /// The player-level tint as `0xRRGGBB`.
2353    pub fn tint(&self) -> Result<u32, JsValue> {
2354        with_player!(self, |p| p.tint())
2355    }
2356
2357    /// Draw this one playhead once at each member's placement: a crowd that costs
2358    /// one player's evaluation and draw calls, however large.
2359    ///
2360    /// `placements` holds six numbers a member — `x, y, scaleX, scaleY, rotation,
2361    /// alpha`, the first five in `setTransform` terms and composed under it, the
2362    /// alpha multiplied into the player's — and `tints`, when given, one
2363    /// `0xRRGGBB` a member. An empty array draws the player once again. Throws,
2364    /// leaving the crowd as it was, when `placements` is not a whole number of
2365    /// members, `tints` does not match it, or there are more than 4096.
2366    ///
2367    /// Everything else is shared: the frame, the events (reported once), the
2368    /// masks and the effects. Each draw is issued for every member in turn, so
2369    /// where two members overlap their parts interleave, and masks clip
2370    /// correctly only where members do not overlap.
2371    #[wasm_bindgen(js_name = setCrowd)]
2372    pub fn set_crowd(&self, placements: &[f32], tints: Option<Vec<u32>>) -> Result<(), JsValue> {
2373        const STRIDE: usize = 6;
2374        if !placements.len().is_multiple_of(STRIDE) {
2375            return Err(js_error(format!("setCrowd: {} numbers are not a whole number of members, six apiece", placements.len())));
2376        }
2377        let count = placements.len() / STRIDE;
2378        if count > MAX_CROWD_MEMBERS {
2379            return Err(js_error(format!("setCrowd: a crowd of {count} is past the {MAX_CROWD_MEMBERS} one player draws")));
2380        }
2381        if let Some(tints) = &tints
2382            && tints.len() != count
2383        {
2384            return Err(js_error(format!("setCrowd: {} tints for {count} members", tints.len())));
2385        }
2386        let member = |i: usize| {
2387            let [x, y, scale_x, scale_y, rotation, alpha] = placements[i * STRIDE..i * STRIDE + STRIDE].try_into().expect("a whole member");
2388            CrowdMember { x, y, scale_x, scale_y, rotation, alpha, tint: tints.as_ref().map_or(CrowdMember::default().tint, |tints| tints[i]) }
2389        };
2390        with_player!(self, |p| p.set_crowd_from((0..count).map(member)))
2391    }
2392
2393    /// How many members `setCrowd` last gave this player; 0 when it draws once.
2394    #[wasm_bindgen(js_name = crowdCount)]
2395    pub fn crowd_count(&self) -> Result<usize, JsValue> {
2396        with_player!(self, |p| p.crowd().len())
2397    }
2398
2399    /// The authored canvas size of the selected animation, as `[width, height]`,
2400    /// or an empty array when nothing is loaded. Useful for scaling a character
2401    /// to fit the element it was dropped into.
2402    #[wasm_bindgen(js_name = canvasSize)]
2403    pub fn canvas_size(&self) -> Result<Vec<f32>, JsValue> {
2404        with_player!(self, |p| p.canvas_size().map(|(w, h)| vec![w, h]).unwrap_or_default())
2405    }
2406
2407    /// Remove this player from its canvas. Safe to call twice; afterwards every
2408    /// method on this handle reports that it is destroyed rather than acting on
2409    /// whichever player later reuses the slot.
2410    pub fn destroy(&self) {
2411        let ctx = &mut *self.ctx.borrow_mut();
2412        let WebContext { surfaces, renderer, encoded_textures, .. } = ctx;
2413        if let Some(entry) = surfaces.get_mut(self.surface) {
2414            // Its texture overrides live in the page's renderer, which outlives it.
2415            if let Some(player) = entry.players.get_mut(self.id) {
2416                for key in player.override_keys() {
2417                    renderer.forget_texture(key);
2418                    encoded_textures.remove(&key);
2419                }
2420            }
2421            entry.players.remove(self.id);
2422        }
2423    }
2424}
2425
2426/// One event as a plain JS object, tagged by `kind`.
2427///
2428/// Hand-built rather than serde-derived: the `web` feature carries no
2429/// serialisation crate, and one small object per event is not worth adding one
2430/// for. Optional UserData fields are simply absent when unset, which is what
2431/// distinguishes "the animator left it blank" from "it is zero".
2432fn event_to_js(event: &SsEvent) -> JsValue {
2433    let out = js_sys::Object::new();
2434    let set = |key: &str, value: JsValue| {
2435        let _ = js_sys::Reflect::set(&out, &JsValue::from_str(key), &value);
2436    };
2437    // On every kind, because both answer "where did this come from": the frame
2438    // is the one the key is **authored** on, which is not the frame the tick
2439    // landed on when several were crossed at once.
2440    set("frameNo", event.frame_no().into());
2441    set("partName", JsValue::from_str(event.part_name()));
2442    // The source on the track stack that fired it, as `trackMainSource` and
2443    // `addTrackSource` name it.
2444    set("source", event.source().into());
2445    match event {
2446        SsEvent::UserData(u) => {
2447            set("kind", JsValue::from_str("userData"));
2448            set("partIndex", u.part_index.into());
2449            if let Some(v) = u.integer {
2450                set("integer", v.into());
2451            }
2452            if let Some(r) = u.rect {
2453                set("rect", js_sys::Float32Array::from(&r[..]).into());
2454            }
2455            if let Some(p) = u.point {
2456                set("point", js_sys::Float32Array::from(&p[..]).into());
2457            }
2458            if let Some(t) = &u.text {
2459                set("text", JsValue::from_str(t));
2460            }
2461        }
2462        SsEvent::Signal(s) => {
2463            set("kind", JsValue::from_str("signal"));
2464            set("partIndex", s.part_index.into());
2465            set("commandId", JsValue::from_str(&s.command_id));
2466            let params = js_sys::Array::new();
2467            for param in &s.params {
2468                let entry = js_sys::Object::new();
2469                let _ = js_sys::Reflect::set(&entry, &JsValue::from_str("id"), &JsValue::from_str(&param.id));
2470                let value = match &param.value {
2471                    SignalValue::Bool(b) => JsValue::from_bool(*b),
2472                    SignalValue::Index(i) | SignalValue::Integer(i) => (*i).into(),
2473                    SignalValue::Floating(f) => (*f).into(),
2474                    SignalValue::Text(t) => JsValue::from_str(t),
2475                    SignalValue::None => JsValue::NULL,
2476                };
2477                let _ = js_sys::Reflect::set(&entry, &JsValue::from_str("value"), &value);
2478                params.push(&entry);
2479            }
2480            set("params", params.into());
2481        }
2482        SsEvent::Audio(a) => {
2483            set("kind", JsValue::from_str("audio"));
2484            set("partIndex", a.part_index.into());
2485            set("soundName", JsValue::from_str(&a.sound_name));
2486            set("soundListNameHash", a.sound_list_name_hash.into());
2487            set("soundNameHash", a.sound_name_hash.into());
2488            set("loopNum", a.loop_num.into());
2489        }
2490    }
2491    out.into()
2492}