ssplayer_wgpu/pack.rs
1//! The shared unit of content: one loaded `.ssab`, referenced by any
2//! number of players.
3//!
4//! **An `SSPack` holds CPU data only — never a GPU texture.** Owning textures
5//! here would compete with the host's own asset lifecycle (in Bevy,
6//! `Assets<Image>` / `RenderAssets<GpuImage>`), so a pack *describes* the
7//! textures it needs ([`SSPack::textures`]) and can *hand over pixels*
8//! ([`SSPack::decode_embedded`]); whoever owns GPU memory registers them with
9//! [`crate::SSRenderer`].
10//!
11//! "The same character twenty times" costs one parse and one atlas, however the
12//! twenty arrived: cloning a pack is an `Arc` bump and two small shared slices,
13//! and loading bytes that a live pack already holds shares that pack's parse.
14
15use ssab::ssab::ss::format::root_as_ss_anime_binary_unchecked;
16use ssruntime::error::SSRuntimeError;
17use ssruntime::{SsabData, SsabResource};
18use std::collections::HashMap;
19use std::sync::{Arc, Mutex, PoisonError, Weak};
20
21/// Every parse a pack still holds, so that loading the same bytes again shares
22/// it instead of building a second.
23///
24/// The runtime keeps everything it derives from a pack on the parse — the
25/// decoded keys, each played animation's part caches and setup pose, the mesh
26/// data — so twenty players that each load Ringo would otherwise hold twenty
27/// copies of it. Held weakly: the last pack to drop a parse frees it.
28static PARSES: Mutex<Vec<Weak<SsabResource>>> = Mutex::new(Vec::new());
29
30/// The live parse of `bytes`, or a new one.
31///
32/// Matched on the bytes themselves, not on where they came from: the same file
33/// reached by two paths is one parse, and a file re-exported under the same path
34/// is a new one.
35///
36/// # Safety
37///
38/// `bytes` must be a valid `.ssab`, as for [`SsabResource::new`].
39unsafe fn parse(bytes: &[u8]) -> Result<Arc<SsabResource>, SSRuntimeError> {
40 let mut parses = PARSES.lock().unwrap_or_else(PoisonError::into_inner);
41 parses.retain(|parse| parse.strong_count() > 0);
42 if let Some(shared) = parses.iter().filter_map(Weak::upgrade).find(|parse| parse.data().as_slice() == bytes) {
43 return Ok(shared);
44 }
45 // SAFETY: the caller's contract.
46 let resource = unsafe { SsabResource::new(SsabData::load_copy(bytes)?) };
47 if resource.resource_static_ptr().is_null() {
48 return Err(SSRuntimeError::NotLoaded);
49 }
50 parses.push(Arc::downgrade(&resource));
51 Ok(resource)
52}
53
54/// One atlas image decoded out of an embedded `.ssab`.
55///
56/// The pixels are **straight-alpha** RGBA8, exactly as the PNG decoded: whoever
57/// takes them decides what to do about premultiplication.
58/// [`crate::SSRenderer::upload_texture`] premultiplies on the way to the GPU; an
59/// engine that puts them in its own asset system declares
60/// [`crate::AlphaMode::Straight`] instead.
61pub struct EmbeddedTexture {
62 /// The cellmap's `name_hash` — what `DrawBatch.texture_hash` carries.
63 ///
64 /// A slot **inside this pack**, not an identity for the image: hand it to
65 /// [`crate::SSPlayer::texture_key`] for what [`crate::SSRenderer`] is keyed
66 /// by. The two differ whenever two packs could name one atlas alike, which
67 /// a tool that names every project's atlas `spritemap1.png` does.
68 pub slot: u32,
69 /// Straight-alpha RGBA8, `width * height * 4` bytes.
70 pub rgba: Vec<u8>,
71 pub width: u32,
72 pub height: u32,
73}
74
75/// One atlas an embedded `.ssab` carries, still in the form the exporter wrote
76/// it: **encoded image bytes (PNG), not pixels**.
77///
78/// This is the *parsing* half of embedded support, and it deliberately has no
79/// decoder behind it — which is why it is available without the `embedded`
80/// feature. A host with a decoder
81/// already — a browser, or an engine's asset pipeline — wants this;
82/// [`SSPack::decode_embedded`] is for hosts that would rather the player do it.
83///
84/// The bytes borrow the pack's `.ssab`, so nothing is copied to produce them.
85pub struct EmbeddedImage<'a> {
86 /// The cellmap's `name_hash` — what `DrawBatch.texture_hash` carries.
87 ///
88 /// A slot **inside this pack**, not an identity for the image: hand it to
89 /// [`crate::SSPlayer::texture_key`] for what [`crate::SSRenderer`] is keyed
90 /// by. The two differ whenever two packs could name one atlas alike, which
91 /// a tool that names every project's atlas `spritemap1.png` does.
92 pub slot: u32,
93 /// The encoded image exactly as the exporter embedded it.
94 pub bytes: &'a [u8],
95}
96
97/// One atlas a pack asks for, described the way the `.ssab` itself describes it.
98///
99/// This is what makes reference mode loadable without the host guessing: the
100/// pack answers *what* it needs and *where the exporter put it*, and the host —
101/// the only side that has a filesystem or a network — does the reading. A host
102/// resolves
103/// [`TextureRef::path`] against the directory the `.ssab` came from, skipping
104/// the entries that are [`TextureRef::embedded`] because those arrive with the
105/// pack.
106#[derive(Clone, Debug)]
107pub struct TextureRef {
108 /// What `DrawBatch.texture_hash` carries: a cellmap's `name_hash`, or a
109 /// texture file name's hash for a TextureChange target (see
110 /// [`SSPack::textures`]).
111 ///
112 /// A slot **inside this pack**, not an identity for the image — two packs
113 /// from two projects one tool exported can both name theirs `spritemap1`. Hand it to
114 /// [`crate::SSPlayer::texture_key`] for what [`crate::SSRenderer`] is keyed
115 /// by, which is what a host supplying its own pixels registers under.
116 pub slot: u32,
117 /// The image path the exporter wrote, relative to the `.ssab`'s own location.
118 pub path: String,
119 /// Whether this image rides inside the `.ssab` (embedded mode).
120 /// `true` means the host has nothing to load: [`SSPack::decode_embedded`]
121 /// already produces it, and a player registers it on the next update.
122 pub embedded: bool,
123}
124
125/// A loaded `.ssab`, shareable between players.
126///
127/// Loading costs a parse, unless a live pack already holds the same bytes;
128/// sharing costs an `Arc` clone. [`SSPlayer::set_pack`]
129/// selects the pack to play from and [`SSPlayer::add_pack`] registers the extra
130/// packs that external instance parts reference by name.
131///
132/// [`SSPlayer::set_pack`]: crate::SSPlayer::set_pack
133/// [`SSPlayer::add_pack`]: crate::SSPlayer::add_pack
134#[derive(Clone)]
135pub struct SSPack {
136 name: Arc<str>,
137 resource: Arc<SsabResource>,
138 /// Every cellmap's atlas, in pack order.
139 textures: Arc<[TextureRef]>,
140 /// Whether any cellmap's image is carried inside the `.ssab`.
141 has_embedded: bool,
142}
143
144impl SSPack {
145 /// Parse `bytes`, naming the pack after the `.ssab` itself.
146 ///
147 /// The name matters because instance parts resolve their sub-animation by
148 /// pack name (`ref_anime_pack`), and the exporter writes that same
149 /// name into each pack — so the two agree without the host having to derive
150 /// one from a file path. Use [`SSPack::load_named`] when the host names packs
151 /// itself.
152 ///
153 /// The bytes are not verified — not here, and not by the runtime — so a malformed or
154 /// crafted `.ssab` can cause out-of-bounds reads. Load only packs you trust (SECURITY.md).
155 pub fn load(bytes: &[u8]) -> Result<Self, SSRuntimeError> {
156 Self::build(None, bytes)
157 }
158
159 /// Parse `bytes` under a name the caller chooses, overriding the one in the
160 /// `.ssab`. What `add_ssab` / `load_ssab` use.
161 ///
162 /// The bytes are not verified — not here, and not by the runtime — so a malformed or
163 /// crafted `.ssab` can cause out-of-bounds reads. Load only packs you trust (SECURITY.md).
164 pub fn load_named(name: &str, bytes: &[u8]) -> Result<Self, SSRuntimeError> {
165 Self::build(Some(name), bytes)
166 }
167
168 fn build(name: Option<&str>, bytes: &[u8]) -> Result<Self, SSRuntimeError> {
169 // SAFETY: `load` and `load_named` require the host to pass a valid `.ssab` (their
170 // docs); neither this crate nor the runtime checks it.
171 let resource = unsafe { parse(bytes)? };
172
173 // SAFETY: the same bytes, which the host guaranteed are a valid `.ssab` (above), read
174 // from the copy the resource owns, which outlives this borrow.
175 let ab = unsafe { root_as_ss_anime_binary_unchecked(resource.data().as_slice()) };
176 let name: Arc<str> = Arc::from(name.unwrap_or_else(|| ab.name()));
177
178 // The two hashes are different things and must not be swapped:
179 // `name_hash` is what a draw batch asks for, `image_path_hash` is the key
180 // of the embedded byte blob.
181 let embedded: Vec<u32> = ab.embedded_assets().map(|assets| assets.iter().map(|a| a.name_hash()).collect()).unwrap_or_default();
182 let mut textures = Vec::new();
183 let mut has_embedded = false;
184 if let Some(cellmaps) = ab.cellmaps() {
185 for cm in cellmaps {
186 let is_embedded = embedded.contains(&cm.image_path_hash());
187 has_embedded |= is_embedded;
188 textures.push(TextureRef { slot: cm.name_hash(), path: cm.image_path().to_string(), embedded: is_embedded });
189 }
190 }
191 // The second table, and not optional: a `DrawBatch.texture_hash` is a
192 // cellmap's `name_hash` *or* a texture file name's hash, the latter for a
193 // part the author gave a TextureChange (`TCHG`). Miss these and those
194 // batches resolve to nothing — here that means the 1x1 white fallback,
195 // so the part turns into a white silhouette rather than disappearing.
196 // Both tables go into one list under the key a draw batch will ask for.
197 //
198 // An `ExternalTexture`'s `name_hash` is the hash of its file name, so it
199 // is also the key of its embedded blob — no join needed, unlike a
200 // cellmap. The same file can therefore appear twice in this list under
201 // two different hashes (once as a cellmap's image, once by name); a host
202 // that fetches per entry should dedupe by [`TextureRef::path`].
203 if let Some(externals) = ab.external_textures() {
204 for et in externals {
205 let Some(name) = et.name() else { continue };
206 let is_embedded = embedded.contains(&et.name_hash());
207 has_embedded |= is_embedded;
208 textures.push(TextureRef { slot: et.name_hash(), path: name.to_string(), embedded: is_embedded });
209 }
210 }
211
212 Ok(Self { name, resource, textures: textures.into(), has_embedded })
213 }
214
215 /// The name instance references resolve against.
216 pub fn name(&self) -> &str {
217 &self.name
218 }
219
220 /// The atlases this pack's draw batches will ask for: every cellmap's image,
221 /// then every `external_textures()` entry.
222 ///
223 /// A reference-mode host walks this to know what to load, and from where,
224 /// before playing (see [`TextureRef`]); combined with
225 /// [`crate::SSRenderer::texture_size`] it also answers "is this pack ready to
226 /// draw".
227 ///
228 /// **Both tables, always.** `DrawBatch.texture_hash` is a cellmap's
229 /// `name_hash` for an ordinary part but a texture *file name*'s hash for one
230 /// the author gave a TextureChange (`TCHG`), and the two tables are the only
231 /// places those keys come from. An external texture can be a cellmap's own
232 /// image under a second hash. Loading only the cellmaps leaves the changed
233 /// parts on the white fallback.
234 pub fn textures(&self) -> &[TextureRef] {
235 &self.textures
236 }
237
238 /// Whether the atlases ride inside the `.ssab` (embedded mode).
239 /// `false` means the host supplies them (reference mode).
240 pub fn has_embedded_textures(&self) -> bool {
241 self.has_embedded
242 }
243
244 /// The names of the packs this one's instance parts play from,
245 /// deduplicated, in `external_instances()` order.
246 ///
247 /// The counterpart of [`SSPack::textures`] for playback data rather than
248 /// images: a pack answers what else it needs, and the host — the only side
249 /// with a filesystem or a network — fetches it and hands it to
250 /// [`SSPlayer::add_pack`]. The exporter writes the referenced pack's own name
251 /// here, which is both the file's stem and the key `ref_anime_pack` resolves
252 /// against, so `<the .ssab's directory>/<name>.ssab` finds it.
253 ///
254 /// Only genuinely external references appear: `external_instances()` is the
255 /// exporter's own list, so a pack whose instance parts play its own
256 /// animations reports nothing.
257 ///
258 /// [`SSPlayer::add_pack`]: crate::SSPlayer::add_pack
259 pub fn instance_packs(&self) -> Vec<String> {
260 // SAFETY: as in `build` — the resource owns the buffer being read.
261 let ab = unsafe { root_as_ss_anime_binary_unchecked(self.resource.data().as_slice()) };
262 let Some(externals) = ab.external_instances() else { return Vec::new() };
263 let mut out: Vec<String> = Vec::new();
264 for entry in externals {
265 let Some(name) = entry.anime_pack_name() else { continue };
266 if name != &*self.name && !out.iter().any(|seen| seen == name) {
267 out.push(name.to_string());
268 }
269 }
270 out
271 }
272
273 /// Names of every animation in the pack.
274 pub fn animation_names(&self) -> Vec<String> {
275 self.resource.resource().map(|r| r.get_animation_names()).unwrap_or_default()
276 }
277
278 /// The encoded atlases this pack carries, in cellmap order.
279 /// Empty for a reference-mode pack.
280 ///
281 /// Parsing only — no image decoder is involved, so this works in every build
282 /// and is the route a host with its own decoder takes (see [`EmbeddedImage`]).
283 /// On the web that host is the browser: `createImageBitmap` on these bytes
284 /// decodes off the main thread and premultiplies for free, which
285 /// [`SSPack::decode_embedded`] cannot do and pays for in wasm size.
286 ///
287 /// The two hashes are different things and must not be swapped:
288 /// the blob is keyed by `image_path_hash`, and what comes back is keyed by
289 /// `name_hash` — the one a draw batch asks for.
290 pub fn embedded_images(&self) -> Vec<EmbeddedImage<'_>> {
291 if !self.has_embedded {
292 return Vec::new();
293 }
294 // SAFETY: as in `build` — the resource owns the buffer being read.
295 let ab = unsafe { root_as_ss_anime_binary_unchecked(self.resource.data().as_slice()) };
296 let Some(assets) = ab.embedded_assets() else { return Vec::new() };
297 let mut bytes_by_hash: HashMap<u32, &[u8]> = HashMap::new();
298 for asset in assets {
299 if let Some(bytes) = asset.data() {
300 bytes_by_hash.insert(asset.name_hash(), bytes.bytes());
301 }
302 }
303
304 // Each table on its own: a pack can have one and not the other. An
305 // embedded pack whose parts only draw TextureChange targets has no
306 // cellmaps at all (`assets/overall_emb/Instance.ssab` is one), and
307 // requiring both would leave it carrying nothing — every part on the white
308 // fallback, with its atlas sitting unread inside the file.
309 let mut out = Vec::new();
310 if let Some(cellmaps) = ab.cellmaps() {
311 for cm in cellmaps {
312 if let Some(&bytes) = bytes_by_hash.get(&cm.image_path_hash()) {
313 out.push(EmbeddedImage { slot: cm.name_hash(), bytes });
314 }
315 }
316 }
317 // TextureChange targets, keyed by file name — which for an
318 // `ExternalTexture` is its `name_hash`, the blob key as well. One blob can
319 // come back twice under two hashes (as a cellmap's image and by name);
320 // that is what the draw batches ask for, so both entries are wanted.
321 if let Some(externals) = ab.external_textures() {
322 for et in externals {
323 if let Some(&bytes) = bytes_by_hash.get(&et.name_hash()) {
324 out.push(EmbeddedImage { slot: et.name_hash(), bytes });
325 }
326 }
327 }
328 out
329 }
330
331 /// Decode the atlases this pack carries. Empty for a
332 /// reference-mode pack, and empty without the `embedded` feature.
333 ///
334 /// Decoding is not cached: the pixels are handed over so the caller can put
335 /// them wherever GPU memory is owned (`upload_texture`, or an engine's asset
336 /// system). Call it once per pack, not once per player.
337 pub fn decode_embedded(&self) -> Vec<EmbeddedTexture> {
338 self.decode_embedded_where(|_| true)
339 }
340
341 /// [`SSPack::decode_embedded`], restricted to the hashes `wanted` accepts.
342 ///
343 /// The filter runs *before* the PNG decode, which is the whole point: a player
344 /// joining a scene where its atlas is already registered skips the decode
345 /// entirely, so N players of one pack cost one decode and one upload.
346 /// The decodes overlap where there is more than one image; the result stays in
347 /// pack order, so an image that will not decode drops out without shifting the
348 /// ones after it.
349 #[cfg(feature = "embedded")]
350 pub fn decode_embedded_where(&self, wanted: impl Fn(u32) -> bool) -> Vec<EmbeddedTexture> {
351 let images: Vec<EmbeddedImage<'_>> = self.embedded_images().into_iter().filter(|i| wanted(i.slot)).collect();
352 let encoded: Vec<&[u8]> = images.iter().map(|i| i.bytes).collect();
353 crate::decode::decode_all(&encoded, false).into_iter().zip(&images).filter_map(|(decoded, image)| decoded.map(|d| EmbeddedTexture { slot: image.slot, rgba: d.rgba, width: d.width, height: d.height })).collect()
354 }
355
356 /// Without the `embedded` feature the player carries no image decoder, so the
357 /// host decodes instead — in the browser that is `createImageBitmap` over
358 /// [`SSPack::embedded_images`], which still needs no sibling files.
359 #[cfg(not(feature = "embedded"))]
360 pub fn decode_embedded_where(&self, _wanted: impl Fn(u32) -> bool) -> Vec<EmbeddedTexture> {
361 Vec::new()
362 }
363
364 /// The runtime resource this pack wraps, for building playback contexts.
365 pub(crate) fn resource(&self) -> &Arc<SsabResource> {
366 &self.resource
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 fn fixture(name: &str) -> Option<Vec<u8>> {
375 std::fs::read(format!("{}/../../assets/overall/{name}.ssab", env!("CARGO_MANIFEST_DIR"))).ok()
376 }
377
378 /// Players that each load the same `.ssab` hold one parse between them,
379 /// whatever they name it, and the parse goes with the last pack holding it.
380 #[test]
381 fn loading_the_same_bytes_again_shares_the_parse() {
382 let (Some(basic), Some(mask)) = (fixture("Basic"), fixture("Mask")) else {
383 eprintln!("fixture missing; run scripts/deploy-examples.sh. skipping.");
384 return;
385 };
386 let first = SSPack::load(&basic).unwrap();
387 let named = SSPack::load_named("renamed", &basic).unwrap();
388 assert!(Arc::ptr_eq(first.resource(), named.resource()), "the same bytes were parsed twice");
389 assert_eq!(named.name(), "renamed");
390 assert!(!Arc::ptr_eq(first.resource(), SSPack::load(&mask).unwrap().resource()), "different bytes shared a parse");
391
392 let parse = Arc::downgrade(first.resource());
393 drop((first, named));
394 assert!(parse.upgrade().is_none(), "the parse outlived every pack holding it");
395 }
396}