core/task
작업. (async/await 로 쓴 게임 코드를 엔진이 프레임마다 이어 돌린다. 러스트 판에만 있는 파일)
- 원본은 브라우저가 Promise 를 돌리고, async 함수는 await 에서 멈췄다가 Promise 가 풀리면 이어 간다. 러스트 판은 엔진이 스레드 하나짜리 실행기를 품는다. Engine::spawn_task, spawn_scene_task 는 원본 async 함수를 부를 때처럼 맡기는 그 자리에서 첫 await 까지 한 번 폴링하고, 남은 작업은 프레임마다(시간과 입력을 갱신한 뒤, 씬의 tick 앞) 깨어난 것만 폴링한다. (&Engine 만 있는 자리에서는 spawn_deferred_task, spawn_deferred_scene_task 로 맡기고 다음 폴링 차례에 처음 돈다) 외부 런타임은 쓰지 않고, 데스크탑과 웹이 같은 코드로 돈다. 퓨처는 Send 가 아니어도 된다. (Rc 를 들어도 된다, 웹은 스레드가 없다)
- 깨우기: 원본 마이크로태스크 줄처럼 깨운 차례대로 줄(TaskWakeQueue)에 넣고, 폴링 차례에 줄이 빌 때까지 앞에서부터 폴링한다. 그래서 한 작업이 Promise 를 풀거나 끝나면 그것을 기다리던 작업은 원본처럼 같은 차례에 풀린 차례대로 이어 간다. 작업이 폴링되는 도중에 스스로를 깨우면(엔진의 상태를 보는 퓨처: 애셋 손잡이, wait::seconds, wait::next_frame 같은 것) 다음 프레임 줄에 넣는다. (원본에서 그런 Promise 는 브라우저 일이 끝난 다음 태스크에 풀리므로 같은 프레임 안에서 다시 보지 않는다) Promise 는 resolve 가, TaskHandle 은 그 작업이 끝날 때, 웹 Promise 를 감싼 JsFuture 는 브라우저가 풀 때 깨운다. Waker 는 Send + Sync 라 줄은 Arc 와 Mutex, 표시는 원자 값으로 든다. (웹은 스레드가 없어도 같은 코드다)
- 엔진과 씬에 닿기: 퓨처는 &mut 를 await 너머로 쥘 수 없다. 작업은 컨텍스트(EngineContext, SceneContext)를 받고, with(|씬, 엔진| ...) 클로저 안에서만 엔진과 씬을 빌린다. 클로저는 동기라 그 안에서 await 할 수 없고, 클로저가 받는 참조의 수명은 클로저마다 새로 매겨져(
for<'a>) 돌려주는 값(R)에 담을 수 없으니 참조가 클로저 밖으로 새지 못한다. 컨텍스트는 복제할 수 없고 with 가 &mut self 를 받아서, 한 작업 안에서 with 를 겹쳐 부르는 코드는 컴파일되지 않는다. - 건전성: 폴링하는 동안만 스레드 지역 칸(TASK_ACCESS)에 엔진과 그 작업의 씬을 가리키는 포인터를 둔다. 1. 엔진은 &'static Engine 이다. (Engine::new 가 프로그램 끝까지 사는 자리에 둔다) 엔진 함수는 모두 &self 라 with 안팎과 Engine::get_engine 이 같은 엔진을 겹쳐 써도 된다. 2. 씬 포인터는 실행기가 &mut 로 쥔 씬 목록의 한 칸에서 만든다. 폴링이 끝날 때까지 실행기는 그 &mut 를 다시 쓰지 않고, 폴링이 끝나면(패닉으로 풀릴 때도) 칸을 앞의 값으로 되돌린다. 그래서 포인터는 쓰는 동안 늘 살아 있고, 실행기 쪽 빌림과 겹치지 않는다. 맡기는 자리의 첫 폴링은 spawn 이 받은 &mut 씬에서 만든다. 첫 폴링이 끝나면 다시 빈 칸으로 돌린다. 그래픽은 엔진이 들어 따로 포인터를 두지 않는다. with_graphic 은 Engine::with_graphic 으로 그래픽을 엔진에서 잠깐 꺼내 넘기고 돌려 넣는다. (그래서 맡기는 자리의 첫 구간도 그래픽을 받는다. 엔진이 그리기 함수에 그래픽을 내어 준 동안 맡긴 작업은 그래픽이 엔진에 없어 None) 폴링하는 작업 목록은 엔진에서 꺼내 둔 지역 값이라 엔진을 빌려도 닿지 않는다. (그동안 맡긴 새 작업은 엔진의 따로 둔 목록에 쌓인다) 3. with 는 칸에서 포인터를 꺼내(take) 쓰고 끝나면 되돌린다. 그동안 칸이 비어 있어서, 어떤 길로든 두 번째 &mut 를 만들 수 없다. (작업 바깥에서 부르거나, 안에서 겹쳐 부르거나, 다른 씬의 컨텍스트를 몰래 넘겨 부르면 이중 빌림 대신 까닭을 적은 패닉이 난다) 4. 씬은 Any 로 그 컨텍스트의 타입인지 확인하고, 씬 핸들이 그 작업의 씬인지도 확인한다.
- 씬을 내려도 원본처럼 그 씬의 작업은 이어 돈다. 엔진은 작업이 남은 씬 값을 작업이 다 끝날 때까지 살려 두고(목록에서는 빠져 tick, draw 를 받지 않는다) with 는 그 씬을 계속 준다. 작업이 다 끝나면 destroy 를 부르고 버린다.
- Promise: 원본 new Promise((resolve, reject) => ...) 자리다. Promise::create 가 퓨처와 resolve 손잡이를 짝으로 준다. 원본 reject 는
Promise<Result<T, E>>의 reject(까닭)다. (예외 대신 Result) 손잡이를 버리고 풀지 않으면 원본처럼 끝나지 않는다.
Tasks. (the engine continues game code written with async/await every frame. A file only in the Rust version)
- In the original the browser runs Promises, and an async function pauses at await and continues when the Promise resolves. In the Rust version the engine contains a single-threaded executor. Engine::spawn_task, spawn_scene_task, like calling an original async function, poll once up to the first await right where it is entrusted, and the remaining tasks are polled every frame (after updating time and input, before the scene's tick) only if woken. (where there is only &Engine, entrust with spawn_deferred_task, spawn_deferred_scene_task and it runs for the first time on the next polling turn) No external runtime is used, and desktop and web run the same code. Futures need not be Send. (they may hold Rc, the web has no threads)
- Waking: like the original microtask queue, woken tasks go into a queue (TaskWakeQueue) in the order woken, and on the polling turn they are polled from the front until the queue is empty. So when a task resolves a Promise or finishes, the tasks waiting on it continue in the same turn in the order resolved, as in the original. If a task wakes itself while being polled (futures that watch engine state: asset handles, wait::seconds, wait::next_frame and such), it goes into the next frame's queue. (in the original such Promises resolve in the task after the browser work finishes, so they are not checked again within the same frame) A Promise is woken by resolve, a TaskHandle when that task finishes, and a JsFuture wrapping a web Promise when the browser resolves it. Waker is Send + Sync, so the queue is held in Arc and Mutex and the flags in atomic values. (the same code on the web even without threads)
- Reaching the engine and scene: a future cannot hold &mut across an await. A task receives a context (EngineContext, SceneContext), and borrows the engine and scene only inside a with(|scene, engine| ...) closure. The closure is synchronous so it cannot await inside, and the lifetime of the references the closure receives is assigned fresh for each closure (
for<'a>) and cannot be put in the returned value (R), so references cannot leak out of the closure. The context cannot be cloned and with takes &mut self, so code that calls with nested within one task does not compile. - Soundness: only while polling, a thread-local slot (TASK_ACCESS) holds pointers to the engine and that task's scene. 1. The engine is &'static Engine. (Engine::new puts it in a place that lives until the program ends) All engine functions are &self, so inside and outside with and Engine::get_engine may use the same engine overlapping. 2. The scene pointer is made from one slot of the scene list the executor holds as &mut. Until polling ends the executor does not use that &mut again, and when polling finishes (even when unwinding from a panic) it restores the slot to its previous value. So the pointers are always alive while used and do not overlap borrows on the executor side. The first poll at the spawning place is made from the &mut scene spawn received. When the first poll ends the slot is set back to empty. The graphic is held by the engine, so no separate pointer is kept for it. with_graphic takes the graphic out of the engine for a moment with Engine::with_graphic, passes it, and puts it back. (so the first segment at the spawn site also gets the graphic. A task spawned while the engine has lent the graphic to a drawing function gets None, because the graphic is not in the engine) The task list being polled is a local value taken out of the engine, so borrowing the engine does not reach it. (new tasks entrusted meanwhile pile up in a separate list in the engine) 3. with takes the pointers out of the slot (take) and restores them when done. The slot is empty meanwhile, so a second &mut cannot be made by any path. (calling from outside a task, calling nested inside, or sneaking in another scene's context panics with a stated reason instead of double borrowing) 4. The scene is checked with Any to be of the context's type, and the scene handle is checked to be that task's scene.
- Even when a scene is unloaded, its tasks keep running as in the original. The engine keeps a scene value with remaining tasks alive until they all finish (it leaves the list and receives no tick, draw) and with keeps giving that scene. When all tasks finish, it calls destroy and drops it.
- Promise: in place of the original new Promise((resolve, reject) => ...). Promise::create gives a future and a resolve handle as a pair. The original reject is reject(reason) on
Promise<Result<T, E>>. (Result instead of exceptions) If the handle is dropped without resolving, it never finishes, as in the original.
TaskHandlestruct traits Clone, Debug, Future
작업 손잡이. (spawn_task, spawn_scene_task 가 돌려준다. 원본 async 함수가 돌려주는 Promise 자리)
- 끝났는지 묻거나(is_finished), 다른 작업에서 await 하거나, 씬이 track_task 로 맡겨 다 끝날 때까지 initialize 를 미룬다.
- 작업을 버렸을 때(그 씬을 내렸을 때)도 끝난 것으로 친다.
Task handle. (returned by spawn_task, spawn_scene_task. In place of the Promise an original async function returns)
- Ask whether it is finished (is_finished), await it from another task, or have a scene entrust it with track_task to delay initialize until it finishes.
- Also counts as finished when the task is dropped (when that scene is unloaded).
use vanilla::{Engine, EngineConfiguration, Promise, TaskHandle};
let engine = Engine::new(EngineConfiguration::new());
let finished_task_handle: TaskHandle = engine.spawn_task(|_engine_context| async move {});
assert!(finished_task_handle.is_finished());
let (promise, promise_resolver) = Promise::<u32>::create();
let waiting_task_handle = engine.spawn_task(|_engine_context| async move {
let value = promise.await;
println!("{}", value);
});
assert!(!waiting_task_handle.is_finished());
promise_resolver.resolve(7);use vanilla::{wait, Engine};
fn spawn_chain(engine: &Engine) {
let first_task_handle = engine.spawn_task(|_engine_context| async move {
wait::seconds(1.0).await;
});
engine.spawn_task(move |_engine_context| async move {
first_task_handle.await;
println!("after first task");
});
}끝났는지. (다 돌았거나 버려졌거나)
Whether it is finished. (ran to completion or was dropped)
반환Returnsbool 작업이 다 돌았거나 버려졌으면 true.True if the task ran to completion or was dropped.
EngineContextstruct
엔진 작업의 컨텍스트. (Engine::spawn_task 가 작업 함수에 넘긴다. with 안에서만 엔진을 빌린다)
- 복제할 수 없고 스레드를 건너지 않는다.
Context of an engine task. (Engine::spawn_task passes it to the task function. Borrows the engine only inside with)
- Cannot be cloned and does not cross threads.
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, EngineContext};
let engine = Engine::new(EngineConfiguration::new());
let byte_count = Rc::new(Cell::new(0));
let task_byte_count = byte_count.clone();
let task_handle = engine.spawn_task(move |mut engine_context: EngineContext| async move {
let load_handle = engine_context.with(|engine| engine.request_asset_bytes("examples/assets/atlas/icons.json"));
if let Ok(bytes) = load_handle.await {
task_byte_count.set(bytes.len());
}
});
assert!(task_handle.is_finished());
assert!(byte_count.get() > 0);엔진 빌리기. (클로저가 도는 동안만, 클로저 안에서는 await 할 수 없다)
- 엔진이 이 작업을 폴링하는 동안에만 부를 수 있다. (다른 곳에서 부르면 패닉)
Borrows the engine. (only while the closure runs, cannot await inside the closure)
- Can be called only while the engine is polling this task. (panics if called elsewhere)
- engine_functionimpl FnOnce(&Engine) -> R
- 엔진을 받아 일하는 클로저. (돌려준 값을 그대로 돌려준다, 참조는 담을 수 없다)Closure that works with the engine. (returns the value it returned as is, cannot hold references)
반환ReturnsR 클로저가 돌려준 값.The value the closure returned.
pub fn with_graphic<R>(&mut self, graphic_function: impl FnOnce(&Engine, &mut Graphic) -> R) -> Option<R>#엔진과 그래픽 빌리기. (GL 이 있어야 하는 일, Engine::with_graphic 처럼 그래픽을 엔진에서 잠깐 꺼내 넘긴다)
- with 처럼 엔진이 이 작업을 폴링하는 동안에만 부를 수 있다. (다른 곳에서 부르면 패닉) 맡기는 자리의 첫 구간도 그래픽을 받는다.
- 클로저 안에서는 engine.get_graphic() 이 None 이고, 인자로 받은 graphic 을 쓴다.
Borrows the engine and graphic. (for work that needs GL, takes the graphic out of the engine for a moment like Engine::with_graphic)
- Like with, can be called only while the engine is polling this task. (panics if called elsewhere) The first segment at the spawn site also gets the graphic.
- Inside the closure engine.get_graphic() is None, and you use the graphic argument.
- graphic_functionimpl FnOnce(&Engine, &mut Graphic) -> R
- 엔진과 그래픽을 받아 일하는 클로저.Closure that works with the engine and graphic.
반환ReturnsOption<R> 클로저가 돌려준 값. (그래픽을 붙이기 전이거나, 그리기 함수 안에서 맡겨 엔진이 그래픽을 그 함수에 내어 준 동안이면 클로저를 부르지 않고 None)The value the closure returned. (None without calling the closure before the graphic is attached, or while the engine has lent the graphic to a drawing function because the task was spawned inside it)
SceneContextstruct
씬 작업의 컨텍스트. (Engine::spawn_scene_task 가 작업 함수에 넘긴다. with 안에서만 그 씬과 엔진을 빌린다)
- 씬은 S 타입 그대로 받는다. (원본 async 함수 안의 this 자리)
- 복제할 수 없고 스레드를 건너지 않는다.
Context of a scene task. (Engine::spawn_scene_task passes it to the task function. Borrows that scene and the engine only inside with)
- The scene is received as type S as is. (in place of this inside an original async function)
- Cannot be cloned and does not cross threads.
use vanilla::{wait, Engine, Scene, SceneBase, SceneContext};
struct TitleScene {
scene_base: SceneBase,
is_logo_shown: bool,
}
impl Scene for TitleScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn initialize(&mut self, engine: &Engine) {
engine.spawn_scene_task(self, |mut scene_context: SceneContext<TitleScene>| async move {
wait::seconds(1.0).await;
scene_context.with(|scene, _engine| {
scene.is_logo_shown = true;
});
});
}
}이 작업의 씬 핸들.
Scene handle of this task.
반환ReturnsSceneId 작업을 맡긴 씬의 핸들. (load_scene 전에 맡겼으면 어느 씬도 가리키지 않는 핸들)Handle of the scene that entrusted the task. (a handle pointing to no scene if entrusted before load_scene)
씬과 엔진 빌리기. (클로저가 도는 동안만, 클로저 안에서는 await 할 수 없다)
- 엔진이 이 작업을 폴링하는 동안에만 부를 수 있다. (다른 곳에서 부르면 패닉)
Borrows the scene and engine. (only while the closure runs, cannot await inside the closure)
- Can be called only while the engine is polling this task. (panics if called elsewhere)
- scene_functionimpl FnOnce(&mut S, &Engine) -> R
- 그 씬(S 타입)과 엔진을 받아 일하는 클로저. (참조는 돌려줄 값에 담을 수 없다)Closure that works with that scene (type S) and the engine. (references cannot be put in the returned value)
반환ReturnsR 클로저가 돌려준 값.The value the closure returned.
pub fn with_graphic<R>(&mut self, graphic_function: impl FnOnce(&mut S, &Engine, &mut Graphic) -> R) -> Option<R>#씬과 엔진과 그래픽 빌리기. (GL 이 있어야 하는 일, Engine::with_graphic 처럼 그래픽을 엔진에서 잠깐 꺼내 넘긴다)
- with 처럼 엔진이 이 작업을 폴링하는 동안에만 부를 수 있다. (다른 곳에서 부르면 패닉) 맡기는 자리의 첫 구간도 그래픽을 받는다.
- 클로저 안에서는 engine.get_graphic() 이 None 이고, 인자로 받은 graphic 을 쓴다.
Borrows the scene, engine and graphic. (for work that needs GL, takes the graphic out of the engine for a moment like Engine::with_graphic)
- Like with, can be called only while the engine is polling this task. (panics if called elsewhere) The first segment at the spawn site also gets the graphic.
- Inside the closure engine.get_graphic() is None, and you use the graphic argument.
- graphic_functionimpl FnOnce(&mut S, &Engine, &mut Graphic) -> R
- 그 씬과 엔진과 그래픽을 받아 일하는 클로저.Closure that works with that scene, the engine and the graphic.
반환ReturnsOption<R> 클로저가 돌려준 값. (그래픽을 붙이기 전이거나, 그리기 함수 안에서 맡겨 엔진이 그래픽을 그 함수에 내어 준 동안이면 클로저를 부르지 않고 None)The value the closure returned. (None without calling the closure before the graphic is attached, or while the engine has lent the graphic to a drawing function because the task was spawned inside it)
Promisestruct traits Future, std::fmt::Debug
Promise. (원본 new Promise((resolve, reject) => ...) 자리, PromiseResolver::resolve 로 풀리면 그 값으로 끝나는 퓨처)
- 콜백으로 끝을 알리는 API 를 await 할 수 있게 바꿀 때 쓴다. (read_clipboard_text_async, request_frame_capture_async 같은 것)
- 실패할 수 있는 일은
Promise<Result<T, E>>로 두고 resolve(Ok(값)) 또는 reject(까닭)로 푼다. (원본 reject 와 await 의 예외 자리) - 손잡이를 버리고 풀지 않으면 원본처럼 끝나지 않는다.
Promise. (in place of the original new Promise((resolve, reject) => ...), a future that finishes with the value when resolved via PromiseResolver::resolve)
- Used to turn APIs that report completion through callbacks into awaitable ones. (read_clipboard_text_async, request_frame_capture_async and such)
- Work that can fail is made a
Promise<Result<T, E>>and resolved with resolve(Ok(value)) or reject(reason). (in place of the original reject and await's exception) - If the handle is dropped without resolving, it never finishes, as in the original.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use vanilla::Promise;
let (mut promise, promise_resolver) = Promise::<u32>::create();
let mut context = Context::from_waker(Waker::noop());
assert_eq!(Pin::new(&mut promise).poll(&mut context), Poll::Pending);
promise_resolver.resolve(7);
assert_eq!(Pin::new(&mut promise).poll(&mut context), Poll::Ready(7));use vanilla::{Engine, Promise};
fn read_clipboard_promise(engine: &Engine) -> Promise<String> {
let (clipboard_promise, clipboard_resolver) = Promise::create();
engine.read_clipboard_text_with_callback(move |clipboard_text| {
clipboard_resolver.resolve(clipboard_text);
});
clipboard_promise
}생성. (퓨처와 푸는 손잡이를 짝으로 준다)
Creates. (gives a future and a resolve handle as a pair)
반환Returns(Promise<T>, PromiseResolver<T>) (기다릴 Promise, 푸는 손잡이) 짝.Pair of (Promise to wait on, resolve handle).
이미 풀린 Promise. (원본 Promise.resolve(값))
An already resolved Promise. (the original Promise.resolve(value))
- valueT
- 풀린 값.Resolved value.
반환ReturnsPromise<T> 처음 폴링에 그 값으로 끝나는 Promise.A Promise that finishes with that value on the first poll.
PromiseResolverstruct traits std::fmt::Debug
Promise 를 푸는 손잡이. (원본 resolve 함수 자리, 한 번만 풀 수 있게 resolve 가 손잡이를 가져간다)
Handle that resolves a Promise. (in place of the original resolve function, resolve takes the handle so it can resolve only once)
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use vanilla::{Promise, PromiseResolver};
let (mut promise, promise_resolver): (Promise<Result<u32, String>>, PromiseResolver<Result<u32, String>>) = Promise::create();
promise_resolver.reject(String::from("timeout"));
let mut context = Context::from_waker(Waker::noop());
assert_eq!(Pin::new(&mut promise).poll(&mut context), Poll::Ready(Err(String::from("timeout"))));풀기. (기다리는 작업을 깨운다. 빌림을 놓은 뒤 깨워서, 깨우는 쪽이 바로 폴링해도 겹쳐 빌리지 않는다)
Resolves. (wakes the waiting task. Wakes after releasing the borrow, so even if the waker polls immediately it does not double borrow)
- valueT
- Promise 가 끝날 값. (손잡이를 가져가 한 번만 풀 수 있다)Value the Promise finishes with. (takes the handle so it can resolve only once)
실패로 풀기. (원본 reject(까닭) 자리, Promise<Result<T, E>> 가 Err(까닭)으로 끝난다)
Resolves as a failure. (in place of the original reject(reason), Promise<Result<T, E>> finishes with Err(reason))
- errorE
- 실패 까닭. (Err 로 감싸 푼다)Failure reason. (resolved wrapped in Err)