core/asset
애셋.
- 원본은 new ImageAsset() 뒤에 await asset.load(경로) 로 읽는다. 러스트 판도 load(engine, 경로) 가 읽기를 요청하고 읽기 손잡이(AssetLoadHandle)를 돌려주며, 손잡이는 애셋을 빌리지 않는 나눠 든 상태라 엔진 작업 안에서 그대로 await 한다. (scene_context.with(|씬, 엔진| 씬.애셋.load(엔진, 경로)).await) 바이트가 다 오면 상태가 loaded 가 되고, await 는 읽은 바이트나 실패 까닭(원본 reject 자리)으로 끝난다. 이미 load 한 애셋은 wait_for_load().await 로도 기다린다. 그림 손잡이(ImageAsset::load)는 원본 img.onload 처럼 풀기까지 끝나야 끝나고, 풀지 못하면 실패로 끝난다. 데스크탑은 요청하는 자리에서 파일을 바로 읽어 끝내고, 웹은 fetch 가 끝난 뒤 다음 프레임들 사이에 끝난다.
- await 없이 쓰는 꼴도 그대로 된다: 씬은 create 에서 애셋을 요청하고 scene_base.track_asset 으로 맡겨 두면, 맡긴 애셋이 다 읽힌 뒤 엔진이 initialize 를 부른다. (원본처럼 다 읽힌 뒤 0.3초 더 기다린다) 그동안은 원본처럼 draw_on_load 로 로딩 화면을 그린다.
- 중앙 리소스 매니저는 원본처럼 두지 않는다. 애셋은 씬이 멤버로 든다.
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.
AssetLoadHandlestruct traits Clone, std::fmt::Debug, IntoFuture
읽기 손잡이. (요청한 쪽과 읽는 쪽이 나눠 든다)
- 복제하면 같은 읽기 상태를 나눠 든다. 읽는 쪽이 finish 로 끝내면 복제한 손잡이 모두가 끝난 것을 본다.
- 엔진 작업 안에서 손잡이를 그대로 await 하면 읽은 바이트나 실패 까닭으로 끝난다. (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)
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");생성. (읽는 중)
Constructor. (loading)
- asset_path&str
- 요청 경로. (손잡이에 적어 둔다)Requested path. (recorded on the handle)
반환ReturnsAssetLoadHandle 읽는 중인 새 손잡이. (읽는 쪽이 finish 로 끝낸다)A new handle in the loading state. (the loading side ends it with finish)
생성. (이미 가진 바이트로 바로 끝난 것)
Constructor. (finished immediately with bytes already at hand)
- asset_path&str
- 요청 경로. (손잡이에 적어 둔다)Requested path. (recorded on the handle)
- bytesVec<u8>
- 이미 가진 바이트.Bytes already at hand.
반환ReturnsAssetLoadHandle 이미 다 읽힌 손잡이.A handle already fully loaded.
요청 경로.
Requested path.
반환Returns&str 만들 때 준 경로.The path given at creation.
같은 읽기를 가리키는 손잡이인지. (복제한 손잡이끼리는 같다)
Whether the handle points to the same load. (cloned handles are the same)
- other&AssetLoadHandle
- 견줄 손잡이.Handle to compare with.
반환Returnsbool 같은 읽기 상태를 나눠 들면 true.true if they share the same load state.
다 읽혔는지.
Whether it is fully loaded.
반환Returnsbool 바이트가 다 왔으면 true.true if all the bytes have arrived.
실패했는지.
Whether it failed.
반환Returnsbool 실패로 끝났으면 true.true if it ended in failure.
끝났는지. (읽혔거나 실패했거나)
Whether it is finished. (loaded or failed)
반환Returnsbool 읽혔거나 실패했으면 true. 읽는 중이면 false.true if loaded or failed. false while loading.
읽은 바이트. (다 읽혔을 때만)
The loaded bytes. (only when fully loaded)
반환ReturnsOption<Rc<Vec<u8>>> 읽은 바이트. (나눠 든 Rc) 읽는 중이거나 실패했으면 None.The loaded bytes. (a shared Rc) None while loading or if failed.
실패 까닭.
Failure reason.
반환ReturnsOption<String> 실패 까닭. 실패하지 않았으면 None.Failure reason. None if it did not fail.
미리 풀어 둔 그림 설정과 반환. (같은 손잡이를 나눠 든 ImageAsset 이 다시 풀지 않게)
- 아직 올리지 않은 그림으로 맡긴다. (씬 로딩 화면 동안 Graphic::prepare_loaded_images 가 올린다, 원본 DecodedImageStore)
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)
- imageRc<Image>
- 받은 바이트를 풀어 둔 그림.Image decoded from the received bytes.
미리 풀어 둔 그림 반환.
Returns the pre-decoded image.
반환ReturnsOption<Rc<Image>> 풀어 둔 그림. 없으면 None.The decoded image. None if none.
응답의 content-type 설정과 반환. (웹 플랫폼이 fetch 응답 머리를 적는다, 원본 response.headers.get("content-type") 자리)
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_typeOption<String>
- 응답의 content-type. 없으면 None.The response's content-type. None if none.
응답의 content-type 반환.
Returns the response's content-type.
반환ReturnsOption<String> 적어 둔 content-type. (데스크탑은 data: 주소면 그 형, 파일이면 None) 적지 않았으면 None.The recorded content-type. (on desktop, the type for a data: URL, None for a file) None if not recorded.
그림으로 풀어야 끝나는 손잡이로 하기. (ImageAsset 이 부른다, 원본 img.onload 처럼 await 가 풀기까지 기다린다)
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)
JSON 으로 풀려야 끝나는 손잡이로 하기. (JsonAsset 이 부른다, 원본 JsonAsset.load 처럼 받기나 해석이 실패하면 await 가 실패로 끝난다)
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)
읽기 끝냄. (읽는 쪽이 부른다)
Finishes the load. (called by the loading side)
- resultResult<Vec<u8>, String>
- 읽은 바이트, 실패면 Err(까닭). (실패면 표준 에러에 까닭을 찍는다)The loaded bytes, or Err(reason) on failure. (on failure, the reason is printed to standard error)
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());AssetLoadFuturestruct traits Clone, Debug, Future
다 읽히기를 기다리는 퓨처. (읽은 바이트, 실패하면 까닭. 원본 await asset.load() 자리)
- 엔진 작업 안에서 await 한다. 아직이면 다음 프레임에 다시 본다.
- 보통은 손잡이를 그대로 await 하거나 Asset::wait_for_load 로 얻는다.
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.
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());생성. (손잡이가 없으면 요청 전이라 바로 실패로 끝난다)
Constructor. (with no handle, nothing was requested, so it ends in failure immediately)
- load_handleOption<AssetLoadHandle>
- 기다릴 읽기 손잡이. None 이면 처음 볼 때 Err 로 끝난다.Load handle to wait on. If None, ends with Err when first checked.
반환ReturnsAssetLoadFuture 새 퓨처.A new future.
AssetBasestruct traits Clone, Debug
애셋 공통 상태. (원본 Asset 의 asset_path, asset_type)
- 애셋 타입과 읽기 손잡이를 든다. 애셋 구조체가 필드로 들고 Asset 트레이트로 돌려준다.
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.
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());생성.
Constructor.
- asset_typeAssetType
- 애셋 타입.Asset type.
반환ReturnsAssetBase 읽기를 요청하기 전의 공통 상태.Common state before a load is requested.
짝Counterpart: vanilla.js Asset.constructor
애셋 타입.
Asset type.
반환ReturnsAssetType 만들 때 준 애셋 타입.The asset type given at creation.
짝Counterpart: vanilla.js Asset.getAssetType
읽기 요청. (엔진에게 바이트를 부탁하고 읽기 손잡이를 돌려준다. 이미 요청했으면 다시 하지 않고 그 손잡이를 돌려준다)
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_base_url 기준, data: 주소도 된다)Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
반환ReturnsAssetLoadHandle 읽기 손잡이. (await 하면 읽은 바이트나 실패 까닭으로 끝난다)Load handle. (awaiting it ends with the loaded bytes or the failure reason)
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#읽기 요청. (is_no_cache 면 웹은 브라우저 캐시를 쓰지 않는다, 이미 요청했으면 다시 하지 않고 그 손잡이를 돌려준다)
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_base_url 기준, data: 주소도 된다)Asset path. (relative to the asset folder on desktop, to asset_base_url on the web; data: URLs also work)
- is_no_cachebool
- true 면 웹에서 브라우저 캐시를 쓰지 않는다. (데스크탑은 늘 파일을 새로 읽어 켠 것과 같다)If true, the browser cache is not used on the web. (desktop always reads the file anew, which is the same as on)
반환ReturnsAssetLoadHandle 읽기 손잡이.Load handle.
이미 가진 바이트로 읽기. (내장 자료나 직접 받은 것, 읽기 손잡이를 돌려준다)
- 이미 요청한 손잡이가 있어도 새 손잡이로 바꾼다.
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.
- bytesVec<u8>
- 애셋 바이트.Asset bytes.
반환ReturnsAssetLoadHandle 이미 다 읽힌 읽기 손잡이.An already fully loaded load handle.
남이 채울 읽기 손잡이로 읽기. (AssetLoader 가 차례를 기다리게 한 뒤 바이트를 채운다. 이미 요청했으면 바꾸지 않는다)
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_handleAssetLoadHandle
- 남이 채울 읽기 손잡이.Load handle that someone else fills.
내리기. (원본 unload)
Unload. (the original unload)
짝Counterpart: vanilla.js Asset.unload
읽기 손잡이.
Load handle.
반환ReturnsOption<&AssetLoadHandle> 읽기 손잡이. 요청 전이거나 내렸으면 None.Load handle. None before a request or after unloading.
요청 경로. (요청 전이면 빈 글)
Request path. (empty string before a request)
반환Returns&str 요청 경로. 요청 전이면 빈 글.Request path. Empty string before a request.
짝Counterpart: vanilla.js Asset.getAssetPath
바이트가 다 왔는지.
Whether all bytes have arrived.
반환Returnsbool 바이트가 다 왔으면 true. 요청 전이면 false.true if all bytes have arrived. false before a request.
짝Counterpart: vanilla.js Asset.isLoaded
읽은 바이트.
Loaded bytes.
반환ReturnsOption<Rc<Vec<u8>>> 읽은 바이트. 요청 전이거나 읽는 중이거나 실패했으면 None.Loaded bytes. None before a request, while loading, or on failure.
Assettrait
애셋 트레이트. (씬의 track_asset 이 읽기 손잡이를 꺼낼 때 쓴다)
- 구현체는 AssetBase 를 들고 get_asset_base, get_asset_base_mut 만 채운다. 나머지는 AssetBase 를 읽는 기본 구현이다.
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.
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");공통 상태.
Common state.
반환Returns&AssetBase 구현체가 든 AssetBase.The AssetBase held by the implementor.
공통 상태. (변경용)
Common state. (mutable)
반환Returns&mut AssetBase 구현체가 든 AssetBase. (변경용)The AssetBase held by the implementor. (mutable)
다 읽혔는지.
Whether it is fully loaded.
반환Returnsbool 바이트가 다 왔으면 true.true if all the bytes have arrived.
짝Counterpart: vanilla.js Asset.isLoaded
요청 경로.
Requested path.
반환Returns&str 요청 경로. 요청 전이면 빈 글.Request path. Empty string before a request.
짝Counterpart: vanilla.js Asset.getAssetPath
다 읽히기를 기다리는 퓨처. (load 가 돌려준 손잡이를 await 하는 것과 같다, 이미 load 한 애셋을 뒤에 엔진 작업 안에서 기다릴 때 쓴다)
- 퓨처는 애셋을 빌리지 않아서 씬이 든 애셋에도 쓸 수 있다. 요청 전이면 바로 실패로 끝난다.
- 끝나면 읽은 바이트, 실패하면 까닭이다. (원본은 거부된다) 그림 풀기와 JSON 풀기는 애셋의 get_image, get_data 가 한다.
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.
반환ReturnsAssetLoadFuture 다 읽히면 읽은 바이트로, 실패하거나 요청 전이면 까닭으로 끝나는 퓨처.Future that ends with the loaded bytes when fully loaded, or with the reason on failure or before a request.
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());AssetTypeenum traits Clone, Copy, Debug, PartialEq, Eq
애셋 타입. (원본 AssetType)
Asset type. (the original AssetType)
| 이름Name | 설명Description |
|---|---|
None | 정하지 않음. (원본 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)Visual. (the original visual) |
AssetLoadStateenum traits Clone, Debug
읽기 상태.
Load state.
| 이름Name | 값Value | 설명Description |
|---|---|---|
Pending | 읽는 중.Loading. | |
Loaded | Loaded(Rc<Vec<u8>>) | 다 읽음. (읽은 바이트)Loaded. (the loaded bytes) |
Failed | Failed(String) | 실패. (까닭 글)Failed. (reason string) |