Loading and Initialization¶
This page covers how to hand an ssab to the Brain and make it ready to play, and how to destroy it. Decide first who holds the ssab memory (borrow / copy), in Player Design Approach §2.
1. Resource and Context¶
The Brain uses two objects.
| Object | Contents | Sharing |
|---|---|---|
| Resource | The ssab bytes, and the read-only metadata read from them | Can be shared by every Context that plays the same ssab |
| Context | The playback state and computation buffers for one character | Not shared. Create one for each character you play |
To play the same animation on several characters, create only one resource, then create a Context for each character and bind the resource to it.
#include "ssruntime.h"
// 1. Create the resource. borrow references the Player's memory; copy duplicates it inside the Brain
void* resource = ss_resource_create_borrow(ssab_data_ptr, ssab_data_len);
if (resource == nullptr) { /* ptr is null, or the ssab's version does not match (§4-2) */ }
// 2. Create the Context
void* context = ss_runtime_create();
// 3. Bind the resource to the Context
ss_runtime_bind_resource(context, resource);
If you use only one Context, you can also use ss_runtime_load_ssab_borrow / ss_runtime_load_ssab_copy, which create the resource and bind it in one call.
When you use the Brain directly from Rust, it takes three steps, with the lifetimes of the bytes, the metadata and the Context expressed as types.
// 1. Reference the bytes (ssab_data_ptr: *const u8, ssab_data_len: usize)
let ssab_data = unsafe { ssruntime::SsabData::load_borrow(ssab_data_ptr, ssab_data_len).unwrap() };
// 2. Read the metadata. `unsafe`: anything but a valid ssab is undefined behaviour (§2 below)
let resource = unsafe { ssruntime::AnimationResource::new(ssab_data.as_slice()) }.unwrap();
// 3. Create the Context and bind it
let mut context = ssruntime::Context::new();
context.bind_resource(&resource);
1-1. Lifetime and destruction order¶
Resources are reference counted. A Context holds a reference to the resource bound to it, so even if you call ss_resource_destroy first, the resource is not freed while any Context has it bound. You may destroy them in any order.
However, a resource created with borrow reads the Player's bytes directly. Do not free the original bytes until the resource itself, and every Context and effect slot that refers to it, has been destroyed.
| Object | Owner | Destruction |
|---|---|---|
| ssab bytes | The Player with borrow, the Brain with copy | With borrow, the Player frees them after the resource, and every Context and effect slot that refers to it, has been destroyed |
| Resource | The Brain (reference counted) | ss_resource_destroy. It remains while a Context has it bound |
| Context | The Player | ss_runtime_destroy |
2. Validating an ssab before passing it¶
The Brain does not validate the structure of an ssab (Limitations §5). If you receive an ssab from the network or from user input, check the following before passing it to the Brain.
- File identifier: the 4 bytes at offsets 4 to 7 (counting from 0) of an ssab hold the ASCII
"SSAB"as the file identifier. Comparing these 4 bytes prevents passing a file of another format, or an empty file, by mistake. - FlatBuffers bounds check: to validate the structure as well, run the data through the Verifier generated by the FlatBuffers bindings for the Player's language (C++'s
flatbuffers::Verifier, C#'sSsAnimeBinaryVerify, and so on) before passing it.
For an ssab whose version does not match the Brain, creating the resource fails (ss_resource_create_* returns nullptr, and ss_runtime_load_ssab_* returns false).
Note
The ssab that ssconverter outputs has no size prefix. Use the normal functions (GetSsAnimeBinary and so on), not FlatBuffers' size-prefixed functions (C++'s GetSizePrefixedSsAnimeBinary and so on).
3. Loading textures¶
The texture to bind when drawing is decided by DrawBatch.texture_hash (Render Loop §2). Its value is one of the following two kinds of hash.
texture_hash value |
Matching ssab entry | When it is used |
|---|---|---|
| Hash of the cellmap name | cellmaps()[].name_hash |
Normally |
| Hash of the texture file name | external_textures()[].name_hash |
When a texture change (TCHG) is authored on that part |
Load both cellmaps() and external_textures(), and put them into one map keyed by each entry's name_hash. If you do not load external_textures(), parts with a texture change are not drawn. How texture changes work is described in External Resources and Textures §2.
3-1. File-reference strings in the ssab¶
ssconverter builds the file-reference strings in the ssab (textures, sounds, fonts and so on) by the following rules. Assume these rules when you map them to your engine's assets.
- File paths and file names written in
sspj/ss*e(ssae/ssce/ssee/ssse) /fntare stored as the same string. No case or separator normalization and no conversion to absolute paths is done. - The texture file name of a charmap (
.fnt) is prefixed with the directory part of the charmap path written in the sspj.- Example: if the sspj says
font/font.fntand the texture name insidefont.fntisglyphs.png, the ssab'sname_textureisfont/glyphs.png.
- Example: if the sspj says
3-2. Reference-mode ssab¶
- Load the textures with the engine's normal asset loading, using the paths in
cellmaps()[].image_path()andexternal_textures()[].name(). - The paths are relative to the ssab. Join them in the Player with the directory that contains the ssab. Resolving them is simpler if your ssab loading also receives that directory.
// Example in Godot (C++)
void load_textures(const ss::format::SsAnimeBinary* binary, String base_dir) {
for (int i = 0; i < binary->cellmaps()->size(); i++) {
auto cellmap = binary->cellmaps()->Get(i);
String image_path = base_dir.path_join(String::utf8(cellmap->image_path()->c_str()));
_textures[cellmap->name_hash()] = ResourceLoader::get_singleton()->load(image_path);
}
// What a texture change (TCHG) binds to. Put it in the same map, keyed by the hash of the texture name
if (binary->external_textures() != nullptr) {
for (int i = 0; i < binary->external_textures()->size(); i++) {
auto etexture = binary->external_textures()->Get(i);
String image_path = base_dir.path_join(String::utf8(etexture->name()->c_str()));
_textures[etexture->name_hash()] = ResourceLoader::get_singleton()->load(image_path);
}
}
}
3-3. Embedded-mode ssab¶
- Walk
embedded_assets()and pass each image's bytes to the engine's "create a texture from image data" facility. External textures are embedded too. - The
name_hashinembedded_assets()is the hash of the file name (image_pathfor a cellmap,namefor an external texture). It differs from the hash of the cellmap name, so map them through thecellmaps()/external_textures()entries.
3-4. Cell index¶
So that you do not have to search on every draw, we recommend building the following index at initialization.
- For each cellmap, a table that looks up a cell's cut-out rectangle and origin from the
name_hashincells().
3-5. Texture filtering and wrapping¶
Texture filtering (nearest or linear) and wrapping (clamp, repeat or mirror) are outside the scope of this guide. Both are set in the engine, the same way as for any other texture the game loads: in Unity's texture importer, and through the engine's resource management elsewhere. cellmaps()[].filter_mode and wrap_mode carry the settings made in SpriteStudio, and a Player does not apply them: if it did, each Player would handle a texture registered under two settings in its own way.
4. Logs and errors¶
4-1. Log callback¶
The distributed Brain cannot use standard output (Integrating into no_std Environments). To receive the Brain's errors, register a log callback at the very start of initialization.
void my_log_callback(int level, const char* message) {
// Pass it to the engine's log function (UE_LOG, Debug.Log, print_line and so on)
}
ss_runtime_set_log_callback(my_log_callback);
level is one of SS_RUNTIME_LOG_ERROR (1) / SS_RUNTIME_LOG_WARN (2) / SS_RUNTIME_LOG_INFO (3). Only ERROR is emitted; WARN and INFO are reserved. Handle all three in your switch.
A failed C-API call that takes a Context emits one ERROR line, prefixed with the function that failed (ss_runtime_setup_animation: Animation not found). If no callback is registered, the string is never built, so this costs nothing.
4-2. Failure reasons¶
A C-API call that fails reports the failure through its return value (false, -1, NaN and so on). Get the reason as a numeric code with ss_runtime_get_last_error(context) right after the call, and turn it into text with ss_runtime_error_message(code). Code 0 means success. The log is for callers that do not check return values, and it reports the same failures as ss_runtime_get_last_error.
ss_resource_create_* and ss_effect_slot_create take no Context, so they have neither the log nor ss_runtime_get_last_error: returning nullptr is the whole report. ss_resource_create_* returns nullptr only when ptr is nullptr or the ssab's version differs from the one the Brain reads (empty or corrupted bytes are not detected; §2). To tell the user about a version mismatch, show the Brain's version (ss_runtime_ssab_schema_version()) next to the ssab's version().
For how the Player's public API reports failure, follow Player API Conventions §7.
5. Listing animation names¶
An ssab contains several animations. Read the list of names from the ssab.
auto binary = ss::format::GetSsAnimeBinary(ssab_data_ptr);
if (binary->animations()) {
for (auto anime : *binary->animations()) {
std::string name = anime->name()->str();
// Return it from the Player's public API (animationNames)
}
}