# JavaScript API reference

The package ships full type definitions (`dist/index.d.ts`), so an editor will complete everything below. This page is the map.

```js
import { sharedContext, restoreSharedDevice, setWasmUrl } from '@spritestudio/ssplayer-wgpu';
import { SsPlayerWebGPUElement, defineSsPlayerWebGPUElement } from '@spritestudio/ssplayer-wgpu/element';
```

`read` is an `SsAssetReader`: `(url: string) => SsAssetBytes | Promise<SsAssetBytes>`, with `SsAssetBytes` = `ArrayBuffer | Uint8Array | Blob | null | undefined`. Both types, and `SsPlayerWebGPUElement` (the element's class), are exported. `SsContextWeb.create()` builds a context of its own, i.e. a second device; call `sharedContext()` instead.

Every throw and rejection is an `Error`; its `message` names the URL or the name the call was given where there is one.

The element lives behind its own entry point, so a bundle that only wants the API never carries it.

## Module functions

|  |  |
| --- | --- |
| `sharedContext(): Promise<SsContextWeb>` | The page's one context — device, pipelines, atlas cache. Call it as often as you like; you get the same one |
| `restoreSharedDevice(ctx): Promise<void>` | Rebuild everything on a new device after a loss |
| `setWasmUrl(url)` | Point at the wasm binary explicitly, before the first `sharedContext()` |
| `defineSsPlayerWebGPUElement(tag?)` | Register `<ss-player-webgpu>`, or the element under `tag` to avoid a name clash. Opt-in, not a side effect of the import |

## `SsContextWeb` — the page

|  |  |
| --- | --- |
| `createSurface(canvas)` | One per `<canvas>` |
| `addTexture(key, rgba, width, height)` | Supply an atlas as raw **straight-alpha** RGBA8, under a `textureRefs` entry's `key` |
| `addTextureFromBytes(key, bytes): Promise` | ... from encoded bytes, decoded by the browser |
| `addTextureFromBitmap(key, imageBitmap)` | ... from an `ImageBitmap` you already have. It must be **premultiplied** (`createImageBitmap(blob, { premultiplyAlpha: 'premultiply' })`) |
| `hasTexture(key)` | Whether the cache already holds one |
| `isDeviceLost()` / `restoreDevice()` | See [Device loss](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/device-loss/index.md>) |
| `surfaceCount()` | Diagnostic |
| `version` / `sdkVersion` | This player's version, and the SpriteStudio-SDK version it links, written as its release tag (`v7.0.0`), or `local` for a build without `scripts/build.sh`. Read-only; `element.ctx` reaches them from the custom element |

`addTexture`, `addTextureFromBitmap` and `setCellmapTexture` throw, changing nothing, when the device cannot hold the texture: wider or taller than its `max_texture_dimension_2d`, a closed `ImageBitmap`, or — for `addTexture` — `rgba` that is not `width * height * 4` bytes. The `FromBytes` forms reject for the same reasons.

Textures supplied from an `ImageBitmap` (`addTextureFromBitmap`, `setCellmapTexture`, `setCellmapTextureFromBytes`) are not kept across a device loss: supply or apply them again after `restoreSharedDevice`. `addTexture`, `addTextureFromBytes` and a pack's own atlases are rebuilt for you.

## `SsSurfaceWeb` — one canvas

|  |  |
| --- | --- |
| `createPlayer()` | Add a character |
| `frame(dt)` | Update every player on this canvas and draw them in one pass. `dt` in **seconds** |
| `resize(width, height)` | Drawable pixels |
| `setGroupAlpha(on)` / `groupAlpha()` | Fade each faded player as one layer. See [Whole-character tint and alpha](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/part-overrides/index.md#whole-character-tint-and-alpha>) |
| `stats()` | `{ players, prims, drawCalls, uploadedBytes, mergeableDraws, redundantTextureBinds, groupLayers, gpuPassTimeNs? }` |
| `playerCount()` | Diagnostic |
| `destroy()` | Explicit and idempotent. It releases the swapchain **and every player on the canvas**; dropping the JS reference would leave a swapchain behind |

## `SsPlayerWeb` — one character

**Loading** — apart from `setCellmapTextureFromBytes`, the `load` family is the only asynchronous part of a player, and a player takes **one load at a time**: starting a second before the first settles is rejected, so `await` it or chain the calls.

|  |  |
| --- | --- |
| `load(src, read?): Promise` | Pack, atlases, sibling packs — from a URL. `read(url)` answers in place of `fetch`; see [In a browser](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/loading/index.md#in-a-browser>) |
| `loadSsab(bytes, pack?, baseUrl?, read?): Promise` | Register bytes, select that pack, and load its atlases and sibling packs (resolved against `baseUrl`) |
| `addSsab(bytes, pack?, baseUrl?, read?): Promise` | The same without selecting it, for instance parts to find |
| `missingAssets()` | What did not arrive, as `{ kind: 'texture' \\| 'pack', name, slot }[]`. **Not a rejection** |
| `textureRefs(pack?)` / `embeddedTextures(pack?)` | What atlases a pack asks for: `{ key, path, embedded }[]` (`path` relative to the `.ssab`'s URL) / `{ key, bytes }[]` |
| `animationNames()` / `partNames()` / `cellmapNames()` / `cellNames(cellmap)` | What the pack offers |
| `currentAnimation()` | The one set up, or `undefined` |
| `canvasSize()` | The authored canvas, `[width, height]`, or an empty array before an animation is set |

**Transport** — see [Playback and transport](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/playback/index.md>).

|  |  |
| --- | --- |
| `setAnimation(name)` | Select. Synchronous, and the allocating call |
| `play()` / `playFrom(frame)` | **Head-out** — rewinds and re-arms the loop count |
| `pause()` / `resume()` / `stop()` | Hold, carry on in place, end |
| `seek(frame)` / `frameNo()` | Fractional frames are honoured |
| `setSpeedScale(s)` / `speedScale()` | A multiple of the authored rate. `0` and negatives stop |
| `setLoopCount(n)` / `loopCount()` / `remainingLoops()` | `n` cycles; `-1` or `0` forever |
| `setAnimationSection(start, end)` | After `setAnimation`. An end before the start, both in range, throws, changing nothing |
| `setPlaybackDirection(dir, style)` / `playbackDirection()` / `playbackStyle()` | `0`/`1` each |
| `setFrameRate(fps)` / `frameRate()` | Replace the authored rate |
| `setSubFrameEnabled(on)` / `subFrameEnabled()` | Interpolate between authored frames |
| `setFrameSkipEnabled(on)` / `frameSkipEnabled()` | Cross several frames in one long tick |
| `startFrame()` / `endFrame()` / `totalFrames()` | The current range |
| `isPlaying()` / `isPausing()` / `isPlayingForward()` / `isFinished()` | State |
| `justStarted()` / `justLooped()` / `justFinished()` | Edges from the last `frame()`. `justStarted` is not raised by `resume()` |

**Placement**

|  |  |
| --- | --- |
| `setTransform(x, y, scaleX, scaleY, rotation)` / `resetTransform()` | Position in pixels from the canvas centre (`y` measured downward), scale, rotation in radians. Without a call the character sits centred and unscaled |
| `fitInto(width, height, options?)` | Fit the animation into a box and write the transform. Returns `{ x, y, scaleX, scaleY }`; an unknown `fit` or `align` throws. See [Fitting into a box](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/placement/index.md>) |
| `canvasRect()` | The box `fitInto` fits when no `frame` is given: `{ x, y, width, height }`, or `undefined` before `setAnimation` |
| `setOrder(n)` / `order()` | Draw order within the canvas, ascending |
| `setVisible(v)` / `isVisible()` | Hidden characters draw nothing but keep playing and reporting events |
| `setCulled(c)` / `isCulled()` | Culled characters **do not advance** and report no events |
| `setAlpha(a)` / `setTint(rgb)` | Whole-character. Read back with `alpha()` / `tint()` |
| `setCrowd(placements, tints?)` / `crowdCount()` | Draw the character at many placements: six numbers a member in a `Float32Array` (`x, y, scaleX, scaleY, rotation, alpha`), and optionally one `0xRRGGBB` a member in a `Uint32Array`. An empty array draws it once. See [Crowds](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/crowds/index.md>) |
| `destroy()` | Explicit and idempotent |

**Parts, overrides and events** — every override has a `ByIndex` twin; resolve once with `findPartIndex(name)`.

|  |  |
| --- | --- |
| `setPartVisibilityOverride(part, hide, cascade)` / `clearPartVisibilityOverride(part)` |  |
| `setPartColorOverride(part, rgba, blendOp, priority)` / `setPartColorOverrideCorners(...)` / `clearPartColorOverride(part)` | `blendOp` 0–3, `priority` 0–2 |
| `setPartCellOverride(part, cellmap, cell, priority)` / `clearPartCellOverride(part)` |  |
| `clearAllPartOverrides()` |  |
| `partTransform(part)` / `partTransformByIndex(i)` | `[m00, m01, m10, m11, tx, ty]`, or an empty array (never `null`) for an unknown part |
| `isPartHidden(part)` / `isPartSkinnedMesh(part)` / `partCount()` | `isPartHidden` and `isPartSkinnedMesh` → `true`/`false`, or `undefined` for an unknown part |
| `isPartHiddenByIndex(i)` / `isPartSkinnedMeshByIndex(i)` | The same by part index — an event's `partIndex`, a slot of `partNames()` — `undefined` out of range |
| `events()` | Plain objects tagged by `kind`: `'userData'` / `'signal'` / `'audio'`. Each carries `frameNo`, `partName` and `source`, the handle of the source that fired it |

**Texture replacement** — swap the whole texture a cell map binds (a costume or palette change). `pack` null selects the main pack. See [Texture replacement](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/texture-replacement/index.md>).

|  |  |
| --- | --- |
| `replaceableCellmapNames(pack?)` | The replaceable names: cell maps and TextureChange targets both |
| `setCellmapTexture(pack, name, imageBitmap)` | Replace from a **premultiplied** `ImageBitmap` |
| `setCellmapTextureFromBytes(pack, name, bytes): Promise` | …or from encoded bytes, decoded by the browser |
| `restoreCellmapTexture(pack, name)` | Put the original atlas back |
| `isCellmapOverridden(pack, name)` | Whether one is currently overridden |

### Motion blending

The track stack: tracks fold onto the setup pose in ascending order, track 0 being what `setAnimation` establishes. See [Motion blending](<https://cri-middleware.github.io/SSPlayerForWgpu/guide/motion-blending/index.md>).

|  |  |
| --- | --- |
| `setTrackAnimation(track, name)` | Lay an animation on a track, replacing what it played |
| `crossfade(track, name, ms)` | Fade a track over to another animation. On track 0 it is `currentAnimation()` from the call on |
| `fadeTrack(track, target, ms)` / `cancelTrackFade(track)` | Drive a track's alpha somewhere / stop the fade where it stands |
| `trackFadeProgress(track)` | 0 to 1; `undefined` when the track is not fading |
| `setTrackAlpha(track, a)` / `trackAlpha(track)` | A track's strength |
| `setTrackBlend(track, b)` / `trackBlend(track)` | `0` mix or `1` additive |
| `setTrackSync(track, s)` / `trackSync(track)` | `0` free or `1` start — set it before laying |
| `setTrackFrame` / `trackFrame` / `setTrackSpeed` | Scrub a track; speed 0 parks it |
| `trackSpeed` / `setTrackFrameRate` / `trackFrameRate` / `setTrackFrameSkipEnabled` / `trackFrameSkipEnabled` | A track's own playback settings; track 0's are the transport calls |
| `setTrackPlaybackDirection(track, direction, style)` / `trackPlaybackDirection` / `trackPlaybackStyle` | `0` / `1`, as `setPlaybackDirection` |
| `setTrackLoopCount` / `trackLoopCount` | The loop count of a track's animation — set it after laying one; `-1` loops forever |
| `isTrackFinished` / `trackJustLooped` | A track's end (a state) and its loop (one update) |
| `setTrackOutgoingEventThreshold` / `trackOutgoingEventThreshold` | How far into a crossfade the outgoing side keeps firing events; `Infinity` (the default) silences it |
| `trackCount()` / `clearTrack(track)` | How many tracks; silence one (not track 0) |
| `trackMainSource(track)` | The source carrying a track's animation |
| `addTrackSource(track, name, weight)` | Lay another animation beside it, mixed by weight; returns its handle |
| `setSourceWeight` / `setSourceFrame` / `setSourceEventThreshold`, and the reads without `set` | One source's weight, playhead and event threshold |

A read of a track or source that does not exist answers `undefined` (`isTrackFinished` and `trackJustLooped` answer `false`); a command on one throws.

## `<ss-player-webgpu>`

Documented in full on [its own page](<https://cri-middleware.github.io/SSPlayerForWgpu/reference/web-component/index.md>); the attributes, in short:

| Attribute | Meaning |
| --- | --- |
| `src` | URL of the `.ssab` |
| `pack` | Pack-name override |
| `animation` | Animation to play; defaults to the first |
| `autoplay` | Boolean attribute — **absent means no**, and the element holds its first frame |
| `pause-when-hidden` | On by default; opt out with `"false"` |
| `speed-scale` | A multiple of the authored rate |
| `fit`, `align`, `flip-x`, `flip-y` | How the authored canvas fits the element: `contain` and `center` by default, `fit="none"` for 1:1 |

`element.loadSrc(src, pack?, animation?, read?)` switches packs from script and resolves to the animation names. It dispatches `animationstarted`, `animationfinished`, `animationlooped`, `userdata`, `signal` and `audio` as DOM events, and `load` once a pack has loaded; `src`, `pack`, `animation`, `speed-scale` and the fit attributes can be changed on a live element, while `autoplay` is read when an animation is set up and `pause-when-hidden` once, when the element connects. Everything `SsPlayerWeb` offers, motion blending included, is on `element.player`.
