# core/asset (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/asset/

Assets.
- The original loads with await asset.load(path) after new ImageAsset(). In the Rust version too, load(engine, path) requests the load and returns a load handle (AssetLoadHandle),
  and the handle is shared state that does not borrow the asset, so it is awaited as is inside an engine task. (scene_context.with(|scene, engine| scene.asset.load(engine, path)).await)
  When all the bytes arrive, the state becomes loaded, and the await ends with the loaded bytes or the failure reason (in place of the original reject). An asset already loaded can also be waited on with wait_for_load().await.
  An image handle (ImageAsset::load) ends only once decoding finishes, like the original img.onload, and ends in failure if it cannot be decoded.
  On desktop the file is read right where it is requested and finishes; on the web it finishes between later frames after the fetch ends.
- The form used without await works as before: if the scene requests assets in create and hands them over with scene_base.track_asset, the engine calls initialize after the handed-over assets are all loaded.
  (waits 0.3 seconds more after everything is loaded, as in the original) Meanwhile, as in the original, draw_on_load draws the loading screen.
- There is no central resource manager, as in the original. Assets are held by the scene as members.

## AssetLoadHandle (struct) (Clone, std::fmt::Debug, IntoFuture)

Load handle. (shared between the requesting side and the loading side)
- Cloning shares the same load state. When the loading side ends it with finish, all cloned handles see it as finished.
- Awaiting the handle as is inside an engine task ends with the loaded bytes or the failure reason. (IntoFuture)

Example: Share a loading handle and finish it from one side

```rust
use vanilla::AssetLoadHandle;

let load_handle = AssetLoadHandle::create_pending("level.json");
let shared_handle = load_handle.clone();
assert!(!load_handle.is_finished());
shared_handle.finish(Ok(b"{}".to_vec()));
assert!(load_handle.is_loaded());
assert!(load_handle.is_same_load(&shared_handle));
assert_eq!(load_handle.get_bytes().expect("bytes").as_slice(), b"{}");
assert_eq!(load_handle.get_asset_path(), "level.json");
```

- `pub fn create_pending(asset_path: &str) -> AssetLoadHandle` (static, since 0.3.2): Constructor. (loading)
  - `asset_path` &str: Requested path. (recorded on the handle)
  - returns AssetLoadHandle: A new handle in the loading state. (the loading side ends it with finish)
- `pub fn create_loaded(asset_path: &str, bytes: Vec<u8>) -> AssetLoadHandle` (static, since 0.3.2): Constructor. (finished immediately with bytes already at hand)
  - `asset_path` &str: Requested path. (recorded on the handle)
  - `bytes` Vec<u8>: Bytes already at hand.
  - returns AssetLoadHandle: A handle already fully loaded.
- `pub fn get_asset_path(&self) -> &str` (method, since 0.3.2): Requested path.
  - returns &str: The path given at creation.
- `pub fn is_same_load(&self, other: &AssetLoadHandle) -> bool` (method, since 0.4.0): Whether the handle points to the same load. (cloned handles are the same)
  - `other` &AssetLoadHandle: Handle to compare with.
  - returns bool: true if they share the same load state.
- `pub fn is_loaded(&self) -> bool` (method, since 0.3.2): Whether it is fully loaded.
  - returns bool: true if all the bytes have arrived.
- `pub fn is_failed(&self) -> bool` (method, since 0.3.2): Whether it failed.
  - returns bool: true if it ended in failure.
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): Whether it is finished. (loaded or failed)
  - returns bool: true if loaded or failed. false while loading.
- `pub fn get_bytes(&self) -> Option<Rc<Vec<u8>>>` (method, since 0.3.2): The loaded bytes. (only when fully loaded)
  - returns Option<Rc<Vec<u8>>>: The loaded bytes. (a shared `Rc`) None while loading or if failed.
- `pub fn get_error_message(&self) -> Option<String>` (method, since 0.3.2): Failure reason.
  - returns Option<String>: Failure reason. None if it did not fail.
- `pub fn set_decoded_image(&self, image: Rc<Image>)` (method, since 0.4.0): Sets and returns the image decoded in advance. (so ImageAsset instances sharing the same handle do not decode again)
  - Stores it as an image not uploaded yet. (Graphic::prepare_loaded_images uploads it during the scene loading screen, the original DecodedImageStore)
  - `image` Rc<Image>: Image decoded from the received bytes.
- `pub fn get_decoded_image(&self) -> Option<Rc<Image>>` (method, since 0.4.0): Returns the pre-decoded image.
  - returns Option<Rc<Image>>: The decoded image. None if none.
- `pub fn set_content_type(&self, content_type: Option<String>)` (method, since 0.4.0): Sets and returns the response's content-type. (the web platform records the fetch response header, in place of the original response.headers.get("content-type"))
  - `content_type` Option<String>: The response's content-type. None if none.
- `pub fn get_content_type(&self) -> Option<String>` (method, since 0.4.0): Returns the response's content-type.
  - returns Option<String>: The recorded content-type. (on desktop, the type for a data: URL, None for a file) None if not recorded.
- `pub fn request_image_decode(&self)` (method, since 0.4.0): Makes it a handle that finishes only once decoded as an image. (called by ImageAsset; like the original img.onload, the await waits until decoding)
- `pub fn request_json_parse(&self)` (method, since 0.4.0): Uses a handle that finishes only when it resolves as JSON. (called by JsonAsset; as in the original JsonAsset.load, the await ends in failure if fetching or parsing fails)
- `pub fn finish(&self, result: Result<Vec<u8>, String>)` (method, since 0.3.2): Finishes the load. (called by the loading side)
  - `result` Result<Vec<u8>, String>: The loaded bytes, or Err(reason) on failure. (on failure, the reason is printed to standard error)

  Example: Finishing in failure leaves the reason

  ```rust
  use vanilla::AssetLoadHandle;
  
  let load_handle = AssetLoadHandle::create_pending("missing.png");
  load_handle.finish(Err(String::from("not found")));
  assert!(load_handle.is_failed());
  assert!(load_handle.is_finished());
  assert_eq!(load_handle.get_error_message(), Some(String::from("not found")));
  assert!(load_handle.get_bytes().is_none());
  ```

## AssetLoadFuture (struct) (Clone, Debug, Future)

Future that waits until fully loaded. (the loaded bytes, or the reason on failure. In place of the original await asset.load())
- Awaited inside an engine task. If not ready yet, checks again the next frame.
- Usually obtained by awaiting the handle as is or with Asset::wait_for_load.

Example: Wait on a load handle inside an engine task

```rust
use vanilla::{AssetLoadFuture, AssetLoadHandle, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let load_handle = AssetLoadHandle::create_loaded("greeting.txt", b"hello".to_vec());
let task_handle = engine.spawn_task(|_engine_context| async move {
	let bytes = AssetLoadFuture::new(Some(load_handle)).await.expect("loaded");
	assert_eq!(bytes.as_slice(), b"hello");
	assert!(AssetLoadFuture::new(None).await.is_err());
});
assert!(task_handle.is_finished());
```

- `pub fn new(load_handle: Option<AssetLoadHandle>) -> AssetLoadFuture` (constructor, since 0.4.0): Constructor. (with no handle, nothing was requested, so it ends in failure immediately)
  - `load_handle` Option<AssetLoadHandle>: Load handle to wait on. If None, ends with Err when first checked.
  - returns AssetLoadFuture: A new future.

## AssetBase (struct) (Clone, Debug)

Common asset state. (asset_path and asset_type of the original Asset)
- Holds the asset type and the load handle. Asset structs hold it as a field and return it through the Asset trait.

Example: Load from bytes at hand and unload

```rust
use vanilla::{AssetBase, AssetType};

let mut asset_base = AssetBase::new(AssetType::Text);
assert!(!asset_base.is_loaded());
assert_eq!(asset_base.get_asset_path(), "");
asset_base.load_from_bytes("note.txt", b"hello".to_vec());
assert!(asset_base.is_loaded());
assert_eq!(asset_base.get_asset_path(), "note.txt");
assert_eq!(asset_base.get_asset_type(), AssetType::Text);
asset_base.unload();
assert!(asset_base.get_load_handle().is_none());
```

- `pub fn new(asset_type: AssetType) -> AssetBase` (constructor, since 0.3.2): Constructor.
  - `asset_type` AssetType: Asset type.
  - returns AssetBase: Common state before a load is requested.
- `pub fn get_asset_type(&self) -> AssetType` (method, since 0.3.2): Asset type.
  - returns AssetType: The asset type given at creation.
- `pub fn request_load(&mut self, engine: &Engine, asset_path: &str) -> AssetLoadHandle` (method, since 0.3.2): Requests a load. (asks the engine for the bytes and returns a load handle. If already requested, does not request again and returns that handle)
  - `engine` &Engine: Engine to ask for the bytes.
  - `asset_path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - returns AssetLoadHandle: Load handle. (awaiting it ends with the loaded bytes or the failure reason)

  Example: On desktop a data: URL is read right there, and requesting again returns the first handle

  ```rust
  use vanilla::{AssetBase, AssetType, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut asset_base = AssetBase::new(AssetType::Text);
  let load_handle = asset_base.request_load(&engine, "data:,hello");
  assert!(load_handle.is_loaded());
  let again_handle = asset_base.request_load(&engine, "data:,other");
  assert!(again_handle.is_same_load(&load_handle));
  assert_eq!(asset_base.get_bytes().expect("bytes").as_slice(), b"hello");
  ```

- `pub fn request_load_with_cache(&mut self, engine: &Engine, asset_path: &str, is_no_cache: bool) -> AssetLoadHandle` (method, since 0.4.0): Requests a load. (if is_no_cache, the web does not use the browser cache; if already requested, does not request again and returns that handle)
  - `engine` &Engine: Engine to ask for the bytes.
  - `asset_path` &str: Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
  - `is_no_cache` bool: If true, the browser cache is not used on the web. (desktop always reads the file anew, which is the same as on)
  - returns AssetLoadHandle: Load handle.
- `pub fn load_from_bytes(&mut self, asset_path: &str, bytes: Vec<u8>) -> AssetLoadHandle` (method, since 0.3.2): Loads from bytes already at hand. (built-in data or something received directly; returns a load handle)
  - Replaces any handle already requested with a new one.
  - `asset_path` &str: Path to record.
  - `bytes` Vec<u8>: Asset bytes.
  - returns AssetLoadHandle: An already fully loaded load handle.
- `pub fn load_from_handle(&mut self, load_handle: AssetLoadHandle)` (method, since 0.4.0): Loads with a load handle that someone else fills. (AssetLoader queues it and then fills in the bytes. Does not change it if already requested)
  - `load_handle` AssetLoadHandle: Load handle that someone else fills.
- `pub fn unload(&mut self)` (method, since 0.3.2): Unload. (the original unload)
- `pub fn get_load_handle(&self) -> Option<&AssetLoadHandle>` (method, since 0.3.2): Load handle.
  - returns Option<&AssetLoadHandle>: Load handle. None before a request or after unloading.
- `pub fn get_asset_path(&self) -> &str` (method, since 0.3.2): Request path. (empty string before a request)
  - returns &str: Request path. Empty string before a request.
- `pub fn is_loaded(&self) -> bool` (method, since 0.3.2): Whether all bytes have arrived.
  - returns bool: true if all bytes have arrived. false before a request.
- `pub fn get_bytes(&self) -> Option<Rc<Vec<u8>>>` (method, since 0.3.2): Loaded bytes.
  - returns Option<Rc<Vec<u8>>>: Loaded bytes. None before a request, while loading, or on failure.

## Asset (trait)

Asset trait. (used by the scene's track_asset to take out the load handle)
- Implementors hold an AssetBase and fill in only get_asset_base and get_asset_base_mut. The rest are default implementations that read the AssetBase.

Example: A custom asset type

```rust
use vanilla::{Asset, AssetBase, AssetType};

struct NoteAsset {
	asset_base: AssetBase,
}

impl Asset for NoteAsset {
	fn get_asset_base(&self) -> &AssetBase {
		&self.asset_base
	}

	fn get_asset_base_mut(&mut self) -> &mut AssetBase {
		&mut self.asset_base
	}
}

let mut note_asset = NoteAsset {
	asset_base: AssetBase::new(AssetType::Text),
};
note_asset.get_asset_base_mut().load_from_bytes("note.txt", b"hello".to_vec());
assert!(note_asset.is_loaded());
assert_eq!(note_asset.get_asset_path(), "note.txt");
```

- `fn get_asset_base(&self) -> &AssetBase` (method, since 0.3.2): Common state.
  - returns &AssetBase: The AssetBase held by the implementor.
- `fn get_asset_base_mut(&mut self) -> &mut AssetBase` (method, since 0.3.2): Common state. (mutable)
  - returns &mut AssetBase: The AssetBase held by the implementor. (mutable)
- `fn is_loaded(&self) -> bool` (method, since 0.3.2): Whether it is fully loaded.
  - returns bool: true if all the bytes have arrived.
- `fn get_asset_path(&self) -> &str` (method, since 0.3.2): Requested path.
  - returns &str: Request path. Empty string before a request.
- `fn wait_for_load(&self) -> AssetLoadFuture` (method, since 0.4.0): Future that waits until fully loaded. (same as awaiting the handle returned by load, used to wait later inside an engine task for an asset already loaded)
  - The future does not borrow the asset, so it also works on assets held by a scene. Before a request it ends in failure right away.
  - On finish it gives the loaded bytes, on failure the reason. (the original rejects) Image decoding and JSON parsing are done by the asset's get_image and get_data.
  - returns AssetLoadFuture: Future that ends with the loaded bytes when fully loaded, or with the reason on failure or before a request.

  Example: Wait in an engine task for a text asset loaded from owned bytes

  ```rust
  use vanilla::{Asset, Engine, EngineConfiguration, TextAsset};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut text_asset = TextAsset::new();
  text_asset.load_from_bytes("note.txt", b"hello".to_vec());
  let load_future = text_asset.wait_for_load();
  let empty_future = TextAsset::new().wait_for_load();
  let task_handle = engine.spawn_task(|_engine_context| async move {
  	let bytes = load_future.await.expect("loaded");
  	assert_eq!(bytes.as_slice(), b"hello");
  	assert!(empty_future.await.is_err());
  });
  assert!(task_handle.is_finished());
  ```

## AssetType (enum) (Clone, Copy, Debug, PartialEq, Eq)

Asset type. (the original AssetType)

- `None`: Unspecified. (the original none)
- `Image`: Image.
- `Audio`: Sound.
- `Json`: JSON.
- `Text`: Text.
- `Font`: Font.
- `Blob`: Byte blob.
- `Bunch`: A bundle of several assets.
- `Visual`: Visual. (the original visual)

## AssetLoadState (enum) (Clone, Debug)

Load state.

- `Pending`: Loading.
- `Loaded` = `Loaded(Rc<Vec<u8>>)`: Loaded. (the loaded bytes)
- `Failed` = `Failed(String)`: Failed. (reason string)
