# resource/assetloader (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/resource/assetloader/

Loads assets together. (the original resource/assetloader.js)
- Puts images, JSON, text, binaries, sounds and fonts in a list and receives them as many at a time as the concurrency (set_concurrency). Failed ones also count as finished, so it does not stall.
- The original waits with await load(). In the Rust version too, load(engine) returns a handle (AssetLoaderLoadHandle) that can be awaited as in the original,
  and awaiting it waits until everything arrives and yields the failure list. (calls update every frame while waiting, wait_for_load().await is the same)
  Usage without await follows the engine's "request → fully read later" pattern:
    Functions like add_image return an asset with a still-empty load handle right away, and load(engine) requests the first batch.
    After that, update(engine) must be called every frame to request the next ones as earlier ones finish. (on desktop they are read on the spot and all finish in load)
    A scene hands get_completion_handle() to scene_base.track_load_handle to defer initialize until everything arrives.
    GameSceneBase hands it off with a single track_asset_loader, and draw_on_load calls update and passes the progress to the loading screen.
- A cheap-clone form that shares handles. (cloning points to the same list)
- Progress is finished count / total count. Failures stay in get_failed_list() as AssetLoadFailure. Calls the set_progress_handler function on change and the set_complete_handler function when all finish.
- Differences from the original:
  Fonts return a load handle instead of a FontAsset. (fonts in the Rust version are registered by name by the engine, and FontAsset is a shell holding a handle)
    The original descriptors (weight, style, character range) are taken as FontFaceDescriptors and passed to the engine's register_font_face_when_loaded. (FontFaceDescriptors::new() if none)
  JSON is a failure if it cannot be parsed after receiving, as in the original. (a failure if the original isLoaded() is false)
  Sounds return `Rc<AudioAsset>`, and count as finished only once decoding finishes after the bytes arrive.
  The original addTask (a hand-made fetch) corresponds to add_load_handle. A load handle requested directly and added is counted in the progress too.
    Just as an original worker picks up an addTask and uses one slot until it finishes, it counts toward the in-flight count (get_in_flight_count) and concurrency until it finishes.
    The handle was already requested before being added, so it cannot be deferred until its turn as in the original, and it is in flight from when it is added.
  The in-flight count is, as in the original, those picked up and started but not yet finished. (images until decoded, sounds until decoded. The original worker waits for that too) Concurrency is counted with this too.
  Images are decoded once fully received, like the original img.onload. Ones that cannot be decoded (broken PNG) go into the failure list, and decoded images are kept on the handle so ImageAsset does not decode them again.
  Items added while receiving are received together as free slots allow, as in the original. (the original spins up more workers when adding, the Rust version fills free slots on each update)

## AssetLoadFailure (struct) (Clone, Debug, PartialEq, Eq)

One item that could not be received. (the original { path, error })

Example: A missing file stays in the failure list

```rust
use vanilla::{AssetLoader, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let asset_loader = AssetLoader::new();
asset_loader.add_text("examples/assets/missing.txt");
asset_loader.load(&engine);
let failed_list = asset_loader.get_failed_list();
assert_eq!(failed_list.len(), 1);
assert_eq!(failed_list[0].path, "examples/assets/missing.txt");
assert!(!failed_list[0].error_message.is_empty());
```

- `pub path: String` (field, since 0.4.0): Path given when added. (for an external handle, that handle's path)
  - returns String
- `pub error_message: String` (field, since 0.4.0): Failure reason. (could not fetch, could not decode the image or parse the JSON, sound decoding failed)
  - returns String

## AssetLoaderProgressHandler (type)

Progress notification function. (progress, finished count, total count)

```rust
pub type AssetLoaderProgressHandler = Box<dyn FnMut(f64, usize, usize)>
```

## AssetLoaderCompleteHandler (type)

All-received notification function. (failure list)

```rust
pub type AssetLoaderCompleteHandler = Box<dyn FnMut(&[AssetLoadFailure])>
```

## AssetLoaderLoadHandle (struct) (Clone, IntoFuture)

Load-together handle. (returned by AssetLoader::load. Stands in for the Promise of the original load, shares the receive list)
- Awaiting it waits until everything arrives and finishes with the failure list.

Example: Wait for everything to load inside an engine task and check the failure list

```rust
use vanilla::{Asset, AssetLoader, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let asset_loader = AssetLoader::new();
let json_asset = asset_loader.add_json("examples/assets/atlas/icons.json");
asset_loader.add_text("examples/assets/missing.txt");
let loader_load_handle = asset_loader.load(&engine);
let task_handle = engine.spawn_task(|_engine_context| async move {
	let failed_list = loader_load_handle.await;
	assert_eq!(failed_list.len(), 1);
	assert_eq!(failed_list[0].path, "examples/assets/missing.txt");
});
assert!(task_handle.is_finished());
assert!(json_asset.is_loaded());
```

## AssetLoaderLoadFuture (struct) (Clone, Future)

Future that waits for everything to arrive. (made by awaiting the handle or returned by wait_for_load. Finishes with the failure list)
- Calls update on every poll to request the next ones.

Example: Call load and then wait with wait_for_load

```rust
use vanilla::{AssetLoader, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let asset_loader = AssetLoader::new();
let mut image_asset = asset_loader.add_image("examples/assets/atlas/icons.png");
asset_loader.load(&engine);
let loader_load_future = asset_loader.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
	assert!(loader_load_future.await.is_empty());
});
assert!(task_handle.is_finished());
assert_eq!(image_asset.get_image_size().x, 128.0);
```

## AssetLoader (struct) (Clone, Default)

Loads assets together.
- Functions like add_image immediately return an asset with an empty load handle, and load requests as many as the concurrency allows. After that, call update every frame.
- A Clone points to the same list.

Example: Add, start loading, and hand it to the scene (on desktop everything finishes in load)

```rust
use vanilla::{AssetLoader, Engine, EngineConfiguration, SceneBase};

let engine = Engine::new(EngineConfiguration::new());
let asset_loader = AssetLoader::new();
let mut image_asset = asset_loader.add_image("examples/assets/atlas/icons.png");
let json_asset = asset_loader.add_json("examples/assets/atlas/icons.json");
let mut text_asset = asset_loader.add_text("examples/assets/scenedocument.scene.json");
assert_eq!(asset_loader.get_total_count(), 3);
assert_eq!(asset_loader.get_progress(), 0.0);
let mut scene_base = SceneBase::new();
scene_base.track_load_handle(&asset_loader.get_completion_handle());
assert!(!scene_base.are_tracked_assets_finished());

asset_loader.load(&engine);
asset_loader.update(&engine);
assert!(asset_loader.is_finished());
assert_eq!(asset_loader.get_progress(), 1.0);
assert_eq!(asset_loader.get_loaded_count(), 3);
assert!(asset_loader.get_failed_list().is_empty());
assert!(scene_base.are_tracked_assets_finished());
assert_eq!(image_asset.get_image_size().x, 128.0);
assert_eq!(json_asset.get_data().expect("json")["meta"]["width"], 128);
assert!(text_asset.get_text().is_some());
```

- `pub fn new() -> AssetLoader` (constructor, since 0.4.0): Creates one. (concurrency 6)
  - returns AssetLoader: A loader with an empty list. (before load)
- `pub fn set_concurrency(&self, concurrency: usize)` (method, since 0.4.0): Sets the concurrency. (1 or more)
  - `concurrency` usize: Number of concurrent loads. (0 counts as 1)
- `pub fn get_concurrency(&self) -> usize` (method, since 0.4.0): Returns the number of concurrent loads.
  - returns usize: Number fetched at the same time. (default 6)
- `pub fn add_image(&self, path: &str) -> ImageAsset` (method, since 0.4.0): Adds an image. (an asset whose bytes fill in once received, decoded on the first get_image)
  - `path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - returns ImageAsset: Image asset with a load handle that is still empty. (fetched when its turn comes and decoded once fetched. Goes into the failure list if it cannot be decoded)
- `pub fn add_json(&self, path: &str) -> JsonAsset` (method, since 0.4.0): Adds JSON.
  - `path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - returns JsonAsset: JSON asset with a load handle that is still empty. (goes into the failure list if it cannot be parsed after fetching, the parsed data is shared with this asset)
- `pub fn add_text(&self, path: &str) -> TextAsset` (method, since 0.4.0): Adds text.
  - `path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - returns TextAsset: Text asset with a load handle that is still empty.
- `pub fn add_blob(&self, path: &str) -> BlobAsset` (method, since 0.4.0): Adds binary.
  - `path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - returns BlobAsset: Binary asset with a load handle that is still empty.
- `pub fn add_font(&self, engine: &Engine, family: &str, path: &str, font_face_descriptors: FontFaceDescriptors) -> AssetLoadHandle` (method, since 0.4.0): Adds a font. (once received, the engine registers it under the family name with the descriptor (weight, style, character range) at the start of the next frame. Returns a load handle)
  - The original addFont(family, path, descriptors). Original uses that gave no descriptor correspond to FontFaceDescriptors::new().
  - `engine` &Engine: Engine to register the font with. (the registration is handed to it now)
  - `family` &str: Font name.
  - `path` &str: Font file path. (relative to the asset folder on desktop, relative to asset_base_url on web)
  - `font_face_descriptors` FontFaceDescriptors: Weight, italic, character range, face key. (path if the key is empty)
  - returns AssetLoadHandle: Load handle for the font bytes. (fetched when its turn comes, finishes as a failure if it cannot be fetched)
- `pub fn add_audio(&self, path: &str) -> Rc<AudioAsset>` (method, since 0.4.0): Adds a sound. (decodes once the bytes are received. On the spot on desktop, in the background on web)
  - `path` &str: Sound file path. (relative to the asset folder on desktop, relative to asset_base_url on the web, data: URLs also work)
  - returns Rc<AudioAsset>: Audio asset that is still empty. (counts as finished only once decoding is done, can be loaded into a player in advance)

  Example: Add a sound and load it (on desktop decoding also finishes in load)

  ```rust
  use vanilla::{AssetLoader, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let asset_loader = AssetLoader::new();
  let audio_asset = asset_loader.add_audio("tests/assets/audio/wav_s16_stereo.wav");
  assert!(!audio_asset.is_loaded());
  asset_loader.load(&engine);
  assert!(audio_asset.is_loaded());
  assert!(asset_loader.is_finished());
  ```

- `pub fn add_load_handle(&self, load_handle: &AssetLoadHandle)` (method, since 0.4.0): Adds a load handle requested from outside. (in place of the original addTask, counted in the progress too)
  - It counts as loading from the moment it is added, and takes one concurrency slot until it finishes. If it finishes as a failure it goes into the failure list.
  - `load_handle` &AssetLoadHandle: Load handle requested from outside or to be finished directly. (shared)

  Example: Add a custom task to the progress and finish it

  ```rust
  use vanilla::{AssetLoadHandle, AssetLoader, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let asset_loader = AssetLoader::new();
  let generate_handle = AssetLoadHandle::create_pending("level.generate");
  asset_loader.add_load_handle(&generate_handle);
  asset_loader.load(&engine);
  assert_eq!(asset_loader.get_in_flight_count(), 1);
  assert!(!asset_loader.is_finished());
  generate_handle.finish(Ok(Vec::new()));
  asset_loader.update(&engine);
  assert_eq!(asset_loader.get_in_flight_count(), 0);
  assert!(asset_loader.is_finished());
  assert_eq!(asset_loader.get_loaded_count(), 1);
  ```

- `pub fn load(&self, engine: &Engine) -> AssetLoaderLoadHandle` (method, since 0.4.0): Starts receiving. (requests the first batch. On desktop everything finishes here. After that, call update every frame)
  - Returns a handle that can be awaited as in the original. Awaiting it waits until everything arrives and yields the failure list.
  - If nothing was added, it becomes fully loaded right here.
  - `engine` &Engine: Engine to ask for the bytes.
  - returns AssetLoaderLoadHandle: Handle that finishes with the failure list once everything arrives. (shares the receive list)
- `pub fn update(&self, engine: &Engine)` (method, since 0.4.0): Update. (passes finished sound bytes to decoding, requests the next ones as free slots allow, and reports progress and completion. Does nothing before load)
  - Fetched images are decoded here. Calls the progress notification only when something newly finished, and the completion notification once when everything first finishes.
  - `engine` &Engine: Engine to ask for the bytes.
- `pub fn set_progress_handler(&self, progress_handler: Option<AssetLoaderProgressHandler>)` (method, since 0.4.0): Sets the progress notification function. (progress, finished count, total count. Off if None)
  - This loader may be called from inside the notification function. (it is taken out while being called)
  - `progress_handler` Option<AssetLoaderProgressHandler>: Function to call when something newly finishes. (progress 0 ~ 1, finished count, total count) None turns it off.

  Example: Receive progress and completion notifications

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{AssetLoadFailure, AssetLoader, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let asset_loader = AssetLoader::new();
  asset_loader.add_text("examples/assets/atlas/icons.json");
  asset_loader.add_blob("examples/assets/missing.bin");
  let progress_list: Rc<RefCell<Vec<(f64, usize, usize)>>> = Rc::new(RefCell::new(Vec::new()));
  let progress_list_for_handler = progress_list.clone();
  asset_loader.set_progress_handler(Some(Box::new(move |progress: f64, finished_count: usize, total_count: usize| {
  	progress_list_for_handler.borrow_mut().push((progress, finished_count, total_count));
  })));
  let failed_path_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
  let failed_path_list_for_handler = failed_path_list.clone();
  asset_loader.set_complete_handler(Some(Box::new(move |failed_list: &[AssetLoadFailure]| {
  	for failure in failed_list {
  		failed_path_list_for_handler.borrow_mut().push(failure.path.clone());
  	}
  })));
  asset_loader.load(&engine);
  assert_eq!(*progress_list.borrow(), vec![(1.0, 2, 2)]);
  assert_eq!(*failed_path_list.borrow(), vec![String::from("examples/assets/missing.bin")]);
  ```

- `pub fn set_complete_handler(&self, complete_handler: Option<AssetLoaderCompleteHandler>)` (method, since 0.4.0): Sets the all-received notification function. (failure list. Off if None)
  - `complete_handler` Option<AssetLoaderCompleteHandler>: Function to call once when everything first finishes. (the failure list, an empty list if none) None turns it off.
- `pub fn get_completion_handle(&self) -> AssetLoadHandle` (method, since 0.4.0): Completion handle. (a handle that finishes when everything finishes, handed off by a scene with track_load_handle. Items added after everything finished are not waited for)
  - returns AssetLoadHandle: Load handle that finishes with empty bytes once everything added has finished (failures included).
- `pub fn get_progress(&self) -> f64` (method, since 0.4.0): Progress. (Finished count / total count, 1 if nothing was added)
  - returns f64: Progress. (0 ~ 1, failures count as finished)
- `pub fn get_total_count(&self) -> usize` (method, since 0.4.0): Total count.
  - returns usize: Number of items added. (external handles included)
- `pub fn get_finished_count(&self) -> usize` (method, since 0.4.0): Finished count. (Loaded and failed)
  - returns usize: Number of finished items.
- `pub fn get_loaded_count(&self) -> usize` (method, since 0.4.0): Loaded count. (Excluding failed)
  - returns usize: Number of items finished without failure.
- `pub fn get_failed_list(&self) -> Vec<AssetLoadFailure>` (method, since 0.4.0): Failure list. (a copy)
  - returns Vec<AssetLoadFailure>: List of items that have failed so far. (in finishing order)
- `pub fn wait_for_load(&self) -> AssetLoaderLoadFuture` (method, since 0.4.0): Future that waits for everything to arrive. (the await of the original await load(), awaited inside an engine task after calling load. Yields the failure list)
  - Calls update every frame while waiting to request the next ones. Shares the handle instead of borrowing it.
  - returns AssetLoaderLoadFuture: Future that finishes with the failure list once everything arrives.
- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether everything added has been loaded. (Including failures, true if nothing was added)
  - returns bool: true if the finished count has reached the total count.
- `pub fn get_in_flight_count(&self) -> usize` (method, since 0.4.0): Number currently in flight. (the original getInFlightCount, those picked up and started but not yet finished. Added outside handles are also counted until they finish)
  - returns usize: Number of items being loaded.
