# core/task (vanilla-engine 0.4.0)

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

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.

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

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).

Example: A task with nothing to wait for finishes where it is entrusted, and a task waiting on a Promise remains

```rust
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);
```

Example: Await another task finishing

```rust
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");
	});
}
```

- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether it is finished. (ran to completion or was dropped)
  - returns bool: True if the task ran to completion or was dropped.

## EngineContext (struct)

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.

Example: Request asset bytes and wait (desktop reads on the spot and finishes on the first poll where it is entrusted)

```rust
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);
```

- `pub fn with<R>(&mut self, engine_function: impl FnOnce(&Engine) -> R) -> R` (method, since 0.4.0): 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_function` impl FnOnce(&Engine) -> R: Closure that works with the engine. (returns the value it returned as is, cannot hold references)
  - returns R: The value the closure returned.
- `pub fn with_graphic<R>(&mut self, graphic_function: impl FnOnce(&Engine, &mut Graphic) -> R) -> Option<R>` (method, since 0.4.0): 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_function` impl FnOnce(&Engine, &mut Graphic) -> R: Closure that works with the engine and graphic.
  - returns Option<R>: 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)

## SceneContext (struct)

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.

Example: Wait 1 second in a scene task, then change a scene value

```rust
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;
			});
		});
	}
}
```

- `pub fn get_scene_id(&self) -> SceneId` (method, since 0.4.0): Scene handle of this task.
  - returns SceneId: Handle of the scene that entrusted the task. (a handle pointing to no scene if entrusted before load_scene)
- `pub fn with<R>(&mut self, scene_function: impl FnOnce(&mut S, &Engine) -> R) -> R` (method, since 0.4.0): 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_function` impl FnOnce(&mut S, &Engine) -> R: Closure that works with that scene (type S) and the engine. (references cannot be put in the returned value)
  - returns R: The value the closure returned.
- `pub fn with_graphic<R>(&mut self, graphic_function: impl FnOnce(&mut S, &Engine, &mut Graphic) -> R) -> Option<R>` (method, since 0.4.0): 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_function` impl FnOnce(&mut S, &Engine, &mut Graphic) -> R: Closure that works with that scene, the engine and the graphic.
  - returns Option<R>: 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)

## Promise (struct) (Future, std::fmt::Debug)

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.

Example: Waits before being resolved, and finishes with the value once resolved

```rust
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));
```

Example: Turn a callback API into an awaitable one

```rust
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
}
```

- `pub fn create() -> (Promise<T>, PromiseResolver<T>)` (static, since 0.4.0): Creates. (gives a future and a resolve handle as a pair)
  - returns (Promise<T>, PromiseResolver<T>): Pair of (Promise to wait on, resolve handle).
- `pub fn resolved(value: T) -> Promise<T>` (static, since 0.4.0): An already resolved Promise. (the original Promise.resolve(value))
  - `value` T: Resolved value.
  - returns Promise<T>: A Promise that finishes with that value on the first poll.

## PromiseResolver (struct) (std::fmt::Debug)

Handle that resolves a Promise. (in place of the original resolve function, resolve takes the handle so it can resolve only once)

Example: Resolve work that can fail with reject

```rust
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"))));
```

- `pub fn resolve(self, value: T)` (method, since 0.4.0): Resolves. (wakes the waiting task. Wakes after releasing the borrow, so even if the waker polls immediately it does not double borrow)
  - `value` T: Value the Promise finishes with. (takes the handle so it can resolve only once)
- `pub fn reject(self, error: E)` (method, since 0.4.0): Resolves as a failure. (in place of the original reject(reason), `Promise<Result<T, E>>` finishes with Err(reason))
  - `error` E: Failure reason. (resolved wrapped in Err)
