RoomDefinition: stepper property

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The stepper property of a room definition is the simulation step the room and its clients share. The room runs it each tick with the players’ inputs, and clients run the same step to predict.

Value

A Stepper, made with defineStepper(). It needs a tickRate.

Exceptions

defineRoom() throws an Error for a stepper in a room without a tickRate, and the types reject it too.

Description

Each tick, after applying owner writes through writes, the room runs the stepper’s step with the room’s entities as its world, a map of each player’s input for this tick, dt and the tick. Then it runs onTick(), sends the state update, and acknowledges the inputs it applied. A bot’s tick sets its input before the stepper runs.

The stepper’s parseInput runs on the room only, on each input as it arrives; throw there to drop a bad one. Its save and load keep a cache of its own, such as a physics engine’s world, in room state: save runs every 30 seconds, on hibernate and on drain, and load on wake, before onWake(). One stepper object serves every room in a room host, so key such caches by world.

An error in the stepper stops the room, and its connections close with close code 4007.

Examples

Shared movement

// shared.ts
import { defineSchema, defineStepper, entity } from "@irtio/room";

export const Boat = entity("boat", { owner: "string", x: "f32" });
export const schema = defineSchema({ entities: [Boat] });

export const stepper = defineStepper<number>({
  parseInput(raw) {
    if (raw !== -1 && raw !== 0 && raw !== 1) throw new TypeError("input is -1, 0 or 1");
    return raw;
  },
  step(world, inputs, dt) {
    for (const boat of world.all(Boat)) boat.x += (inputs.get(boat.owner) ?? 0) * 3 * dt;
  },
});
// room.ts
import { defineRoom } from "@irtio/room";
import { Boat, schema, stepper } from "./shared.js";

export default defineRoom({
  schema,
  tickRate: 30,
  stepper,
  onJoin(room, connection) {
    const mine = [...room.entities.all(Boat)].some((b) => b.owner === connection.player);
    if (!mine) room.entities.create(Boat, { owner: connection.player });
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
stepper0.10.10.10.1