Byte Engine Docs

Script gameplay with tasks

Write a character's or a round's behavior as async tasks that your tick polls, so it waits for ticks, timers, and messages instead of keeping a state machine.

Write gameplay that happens in steps, such as a character that walks until it dies and lies down until it revives, as an async function. A task runtime polls these functions from your tick. Each one waits for what it needs next: the next tick, an amount of game time, or a message such as a button press or a ray query's answer. The state between the steps is where the function is, so you don't keep flags such as dead or pending_jump.

Keep continuous math, such as easing a camera, as ordinary per-tick code inside a task's loop. Tasks help most with the flow around it.

Choose the task state

Choose the state your tasks need to reach while they run, such as the world scope, the decoded controls, and your systems. GraphicsApplication owns the runtime on its world scope, so a task spawned on an entity ends when the world deletes the entity:

struct Scene {
	world: MessageScope,
	controls: Controls,
	animation: AnimationSystem,
}

The runtime lends the state to tasks by type, so it can't borrow anything that lives shorter than the application.

Spawn tasks

Call spawn_on on the application's runtime for an entity's behavior, and spawn for everything else. The closure receives the handle the task waits and spawns children through:

app.runtime().spawn_on(character, |tasks| player(tasks, character));
app.runtime().spawn(|tasks| gun(tasks, camera));

A task can spawn more tasks, such as one per shot it fires. They run in the same poll.

Poll from your tick

The application advances task time before your simulation callback. Poll the tasks after every stage whose messages they wait for. Your systems' messages reach the tasks through the world's channels, so the tick only steps and polls:

fn tick(&mut self, app: &mut GraphicsApplication, time: Time) {
	app.runtime().poll(&mut self.scene);

	self.scene.animation.step(time, app.alley_mut());
	app.runtime().poll(&mut self.scene);
}

Wait for time and channel messages

Inside a task, await what the next step needs. Make a listener on any world channel and await recv, or recv_where to skip the messages that aren't for this task:

async fn walk(tasks: &Tasks<Scene>, body: &mut Character, root_motion: &mut DefaultListener<RootMotionUpdate>) -> Infallible {
	loop {
		let delta = tasks.tick().await;
		let requested = tasks.with(|scene| body.select_state(&scene.controls, delta)).await;
		tasks.with(|scene| scene.world.set(requested).on(body.handle)).await;
		let motion = root_motion.recv_where(|update| update.handle() == body.handle).await;
		body.apply_root_motion(motion);
	}
}

Create the listener when the task starts, before its first await, as in world.channel::<RootMotionUpdate>().listener(). A listener keeps every message sent on its channel from then on until the task reads it, including the ones sent while the task waited for something else.

  • tick resolves at the next tick with the game time since the wait began, so a task that waited a few ticks for something else moves by all of them.
  • sleep resolves once that much game time has passed. Pausing with a zero delta holds every sleep.
  • every makes an interval whose next resolves at a fixed rate of game time. See Run work at a fixed rate.
  • recv resolves with the listener's next message. Every message on the channel wakes every task that awaits it, so give many tasks their own channels rather than one they all filter.
  • with reaches the state you passed to Runtime::poll. Keep the borrow inside the closure.
  • now returns the game time, which every task reads the same during a tick.

Read time only through the runtime. Each task that read the system clock would see a different time, and pausing or slowing the game wouldn't reach it.

Run work at a fixed rate

Run work that doesn't need every tick, such as re-planning an agent's route, on an interval. Make the interval before the task's loop, and await its next in the loop or as an each wait:

let mut think = tasks.every(MediaTime::from_millis(100)).phase(offset);

perform! {
	when shot(&mut answers) => {
		character.die();
		break;
	}

	each delta = think.next() => {
		let velocity = tasks.with(|scene| plan(scene, &mut character, delta)).await;
		character.steer(velocity);
	}
}

shot, plan, and the character's methods are your own.

  • next resolves with the game time since the previous fire, so movement that scales by delta stays correct at any rate.
  • The deadlines stay one period apart from when you made the interval. A wait that loses the selection keeps its deadline for the next one.
  • When the task was busy past several deadlines, the interval fires once and then keeps its schedule, so it never catches up in a burst.
  • Give each entity a different phase within the period, such as its index times the period over the number of entities, so their work lands on different ticks instead of the same one.
  • Call set_period to change the rate, for example to make agents far from the player think less often.

An interval fires at most once per simulation step. Use tick for work that must run every step.

Choose activities with events and ticks

Use perform! from byte_engine::gameplay::tasks to keep the player's alternatives visible. Write when for an event and each for repeated updates. Put actions that can happen together in the same branch, in order. Use always for a shared step before each selection. The step also runs before the first selection, so it can await the initial animation pose:

let mut actions = world.channel::<ActionEvent>().listener();
let mut shooting = world.channel::<ActionEvent>().listener();

perform! {
	always {
		player.character.advance().await;
		if player.alive {
			and! {
				player.follow();
				when pressed(&mut shooting, shoot) => {
					player.shoot();
				}
			}
		}
	}

	when pressed(&mut actions, kill) => {
		player.alive = !player.alive;
		if player.alive {
			// Discard presses received while dead.
			while shooting.read().is_some() {}
		} else {
			player.character.die();
		}
	}

	each delta = player.tasks.tick() => {
		player.delta_seconds = delta.as_seconds_f32();
		if player.alive {
			player.walk().await;
		}
	}
}

The action functions and methods in this example are your own. Each does one update. Import and! from byte_engine::gameplay::tasks to group these activities. It awaits them in written order: movement finishes before the camera follows, and shooting uses the updated camera. Each call can borrow the same mutable player state. A wait pauses the group until it can continue.

Inside and!, when checks its event once without waiting. A ready event runs its activities; a pending event skips them and lets the group continue. The body uses the same activity syntax as the rest of and!, with each call awaited automatically. Once selected, its activities can suspend the group. The event future is dropped after the check, so use cancellation-safe waits and retain their listeners between updates. Give independent events separate listeners so one event's filtering doesn't consume another event's messages.

The shared step applies animation in either mode. Movement intent, camera following, and shooting run only while alive. A movement branch sends its request; the next shared step applies the resulting pose before the camera and shooting use the new position.

The shared step and branches borrow the same state in sequence. always doesn't run in parallel with a branch or while a nested performance is active. An await in the shared step pauses selection until it completes. Nest a performance inside a branch when you want to replace all outer activities, including its shared step, until the inner performance ends.

The first ready wait in written order selects the branch. Its actions finish before the next selection, so an await inside a branch pauses the whole performance until that action can continue. The macro handles fusion of the wait futures. You can also use the original select_biased! branch syntax when you need direct control of those futures.

pressed is your own helper that awaits the action's next true event with recv_where. A listener whose wait loses the race keeps its messages, so the next await reads them.

When a branch ends its tick wait in the middle of a tick, the next tick the task awaits in that poll resolves at once with the same time. A kill press that wins the selection therefore doesn't cost the each branch a tick.

Use combinators that poll every branch on each poll, such as select! and join!. A wait that its task stops polling ends, so a combinator that polls only the branches that woke loses the others' waits.

The application advances task time once per simulation step. With tick_stepped_with, task time advances in the simulation callback and stays unchanged in the frame callback. Poll tasks with the state type their Tasks handles name, since with finds the state by its type.

Rust API

On this page