openrtc-netcode
v3.3.1
Published
A small lobby, mesh, message, and replicated-state netcode layer built on OpenRTC.
Maintainers
Readme
openrtc-netcode
Multiplayer state and simulation primitives over an activated OpenRTC room.
The adapter observes Room.members for membership; Room.peers remains a
retained lifecycle projection and is not used as a match roster. Netcode peer
IDs are the current node bindings in that roster; device-only sparse entries
are not fabricated into routable game peers. Use a small mesh or an admitted
authority topology whose required game peers have routes.
OpenRTC owns authenticated membership, logical connections, admission, carriers
and recovery. Netcode owns game protocol, authority, replication and actions;
it never dials peers or installs connection repair timers.
This source implements wire v2, intended for the coordinated 3.0.0 train.
It is not compatible with published v1 peers (including 2.9.7/2.9.8). Upgrade a
whole match together. protocol:error reports incompatible frames and
waitForPeer() rejects incompatible negotiation or timeout. Package versions
remain unchanged until the complete release train qualifies; see the repository
netcode audit's release-readiness record. No new release is implied by this file.
import { OpenRTC } from 'openrtc';
import { createNetcode } from 'openrtc-netcode';
const rtc = OpenRTC({ apiKey: 'pk_live_...', transports: { webrtc: true } });
const room = await rtc.rooms.join('match', {
access: 'capability', membership: 'ephemeral', maxPeers: 8,
});
const game = createNetcode({
room, tickRate: 60, codec: 'quantized',
authority: { mode: 'owner', hostOwnedKinds: ['crate'] },
replication: { bytesPerSecond: 96 * 1024, maxStateAgeMs: 250 },
motionThresholds: { position: 0.002, rotationRadians: 0.002, maxSilenceMs: 1000 },
});
game.on('protocol:error', ({ peerId, reason }) => console.warn(peerId, reason));
await game.joinLobby(room.id);
const player = await game.objects.spawn({
kind: 'player', transform: { position: { x: 0, y: 1, z: 0 } },
});Authority and lifetime
mode: 'owner' permits each peer to publish its own objects and NetVars.
Give each NetVar key one agreed owner; namespace per-player keys by peer ID.
Declaring the same default-local key independently on several peers does not
create shared write authority. Use
this for cooperative worlds whose players are trusted to control their avatars.
hostOwnedKinds restricts shared physics kinds to the current host.
mode: 'host' restricts every object and NetVar writer to the host; clients send
validated actions or inputs to that host. A trusted dedicated Node authority is
appropriate for competitive rules. Encryption authenticates a writer; application
handlers must still validate speed, reach, cooldowns, resources and game rules.
Without hostId, the host is the lexicographically smallest current member ID,
including the local peer. A joining lower ID can therefore change the host.
A host change retires old host-owned entities and, in host mode, old host NetVars;
the new host initializes its scene/state. This is a reset policy, not seamless
physics migration. Authenticated hello epochs fence delayed host packets, and
host-owned objects receive a fresh incarnation when authority resets. Pending
actions to a retired authority reject with an unknown effect outcome. Stable
action IDs and receipt windows remain valid for unchanged recipients in the
same peer session. Suspended producers cannot publish into a later authority
period. Receipts echo the original action sequence; delayed results cannot
settle a later request that reuses a stable ID after recipient retirement.
Pin the same admitted hostId on every client when continuity
requires a designated authority. If that peer leaves, choose a new match or
explicit application migration; this library does not appoint an impersonator.
owner: 'lobby-owner' on an owner-mode NetVar binds the current host.
Declarations made before joining bind when the first host is resolved; they
then stay bound to that peer. Remote placeholders do not compete with the
authoritative owner's initial revision.
Object IDs are always owner-prefixed (${peerId}:...). Omit id for a generated
ID containing a random store instance. Ownership transfer is unsupported.
Writers cannot supply revision or incarnation; every mutation increments a
safe-integer revision. The match session fences old owner incarnations; host-owned kinds also bind
their incarnation to the authenticated authority epoch. tick
is simulation time; updatedAt is informational and never orders mutations.
Equal revisions use canonical JSON order; removal wins an equal-version tie.
Unapproved mutations produce no accepted-state events.
Live entities and deletion versions share a 10,000-ID lifetime bound and 7 MiB serialized byte budget per store; an entry
may not exceed 220 KiB. NetVars have 4096 keys, 4 MiB total and 240 KiB per value.
Retain tombstones until match retirement to prevent stale resurrection. Exhaustion
rejects explicitly; start a new match rather than evicting deletion authority.
Authoritative peer departure retires that peer's entities, state and receipts.
Leaving resets match data and rejects queued work. Old NetVar handles reject;
define a new handle in the next match. stop() releases netcode observers,
channels and microphone ownership; it does not stop a borrowed OpenRTC runtime.
After leaving a borrowed Room, activate a fresh Room capability before reusing it.
Simulation and rendering
import { SnapshotBuffer, InputPrediction, LagHistory } from 'openrtc-netcode';
// Drive from the engine's fixed simulation loop, independently of rendering.
game.clock.advance(frameDeltaSeconds, (_tick, fixedDelta) => simulate(fixedDelta));
game.flushReplication();
const buffer = new SnapshotBuffer({ tickRate: 60, hermite: true });
const object = game.objects.read(player.id); // deeply frozen; no clone allocation
if (object) buffer.push({
epoch: object.incarnation, tick: object.tick, revision: object.revision,
transform: object.transform, linearVelocity: object.physics?.linearVelocity,
teleport: object.teleport,
});
buffer.sample(performance.now() / 1000, pooledTransform);Push each accepted entity revision once. Buffers estimate arrival offset and jitter, interpolate authoritative ticks with linear/Hermite position and quaternion slerp, and cap extrapolation (120 ms by default). Epoch changes and teleports reset interpolation; retired epochs cannot restore old poses. Use monotonic arrival time, never sender wall time. Sleeping/teleport flags are explicit. The fixed clock caps catch-up to eight ticks and records dropped ticks.
InputPrediction<State, Input> stores bounded sequenced inputs; reconcile()
applies an authoritative acknowledged sequence and replays only pending inputs.
Supply the deterministic movement step and reset at authority epochs. It does
not make arbitrary rigid-body engines deterministic or provide anti-cheat.
LagHistory<State> retains bounded authoritative ticks for game-owned rewind
queries, rejects out-of-window requests, and never accepts a client's claimed
hit as authority. Clamp rewind to your measured latency and game policy.
Read entity IDs with objects.ids(kind) and poses with objects.read(id) from
the render loop. get/list/snapshot clone for general application use; avoid
calling them for every entity every rendered frame. React consumers should use
useNetworkObjectIds and imperative pose reads. Single-entity and small
collection hooks remain available for ordinary UI.
Replication, interest and receipts
Each peer has its own motion queue: one in-flight batch, one pending value per
entity, token budget, priority and state expiry. A blocked peer does not stall
other recipients. Call flushReplication() from the game loop to replenish
budgets/expire pending state. replicationStats(peerId) exposes bytes, age,
supersession and expiry. Successful motion submission can mean replacement or
expiry; it is not an application acknowledgement. There is no retry/redial timer.
interest(peerId, object) controls the exact reliable view sent to each peer;
call refreshInterest() after an interest-only change. Snapshots are bounded
pages applied atomically, and motion is bound to a view revision. Interest hides
entities; it does not grant authority. Avoid expensive all-world scans in an
interest callback; use your spatial index and relevant peer region.
priority(peerId, object) affects budget selection. Optional motion thresholds
suppress tiny changes relative to the last transmitted pose, with a max-silence
refresh when the application next publishes. Static metadata/scale changes and
teleports still replicate. Defaults are bounded, not universal game tuning.
The JSON codec sends lossless indexed moving fields. Both codecs keep static identity, metadata and scale in the reliable baseline. The quantized codec sends 59-byte motion records plus a 5-byte header (64 bytes for one object), before base64/envelope/transport overhead. Positions use millimetres (about ±2,147 km), velocities centi-units (about ±327 units/s), and normalized quaternion components use int16. Out-of-range values reject; choose JSON for larger ranges. Reliable baselines carry static metadata and scale. Batches contain at most 1,024 records, frames at most 256 KiB, and assembled snapshots at most 8 MiB. No binary delta depends on an unacknowledged previous motion packet. The Rust crate validates JSON envelopes; its packed motion field is opaque rather than a second binary implementation.
game.handleAction('crate:interact', (payload, { from, signal }) => {
if (signal.aborted) throw new Error('Retired match');
validateReachAndCooldown(from, payload);
return applyAuthoritativeImpulse(payload);
});
const receipt = await game.request(hostId, 'crate:interact', { crateId }, {
id: 'immutable-input-123', timeoutMs: 5000,
});Action receipts acknowledge the handler result. A timeout means the outcome is unknown: reuse the same immutable stable ID to query a retained result, never invent a new ID to retry an uncertain effect. Generated action IDs continue in long matches. Sequences have a 256-action window per authenticated sender session; expired or evicted results reject without replaying the effect. At most 256 custom stable IDs are retained per caller match. Active effects are capped at 8 per peer/64 globally; payload/result limits are 16 KiB and full receipt data is capped at 4 MiB. Handlers must honor their AbortSignal; the library cannot undo external side effects. No durable exactly-once guarantee spans process loss.
Reliable control and replaceable motion use distinct logical channels.
Targeted actions also bind the recipient session so a delayed request cannot
execute against a restarted peer. send()/broadcast() use reliable control delivery and reject missing routes;
they acknowledge transport submission, not a gameplay effect. Voice adds tracks
to existing logical connections and fences late microphone capture on stop.
BroadcastChannel fallback was removed because it could forge authenticated
peer identity. Test local games through a real explicit OpenRTC emulator lane.
Technique references and qualification
The chosen separation of fixed simulation, authoritative physics, delayed interpolation and bounded extrapolation follows the documented approaches in Unity authoritative physics, Unity interpolation, and Valve networking. Game genre, authority topology, physical transport and bandwidth determine the right rates and budgets. Local fake-runtime tests prove protocol contracts; source-built browsers, native hosts, real networks and adverse-load measurements are separate qualification. Reliable carriers can still have transport-level head-of-line latency; application coalescing does not turn them into datagrams.
