Skip to content

Networking

Cursor Agent edited this page Nov 29, 2026 · 1 revision

Networking

A networked game has one authority, the server, and clients that send inputs and draw what the server sends back. games/arena is the worked example: two to four players, a lobby, then a race for a coin. The walked chapter is docs/guide/08-networking.md. cargo xtask guide runs its checked commands.

Crates:

Crate Role
fanalor-net UDP and WebSocket transports, including the browser; reliable and unreliable channels; typed messages; a version handshake. Untrusted input is bounded
fanalor-replication Which components replicate; snapshots and deltas inside a per-client byte budget; interpolation; prediction; interest; lag compensation
fanalor-server A dedicated server: a scene, headless, at a fixed tick. A game's server binary links this library
fanalor-core tick.net, the session a game drives

The replication wire version is part of the handshake (REPLICATION_WIRE_VERSION 3). A peer from 0.3 is refused with ProtocolMismatch at connect. Every end of a session must be built from the same channels and NetConfig::protocol.

Host and join

fn start(&mut self, tick: &mut Tick<'_>) {
    tick.net.enable_replication(ReplicationConfig::default());
    tick.net.host(&HostOptions { listen: true, ..HostOptions::default() })
        .expect("the ports are free");
}

A listen server plays and hosts: UDP 7777 for native clients, WebSocket 7778 for browsers. tick.net.join("udp://192.168.1.20:7777", NetConfig::default()) joins. A page can only join ws:// or wss://. It cannot host.

tick.net.events() reports who connected and disconnected this frame. On a listen server the host's own player is PeerId::SERVER, so one path spawns every player. Mark the entity with NetOwner(peer).

fanalor-server serves a scene that has no game code:

cargo run -p fanalor-server -- scenes/sandbox.ron
cargo run -p fanalor-server -- scenes/sandbox.ron --udp 0 --ws 0 --seconds 2

Without --udp / --ws it listens on 7777 and 7778. Without --seconds it runs until stopped. --help lists --tick, --max-clients, --protocol, --bind, and the lobby and discovery flags below.

The arena's dedicated server is that command line with the arena's game linked:

cargo run -p arena --bin arena-server -- --asset-root games/arena/assets
cargo run -p arena                 # lobby: host, find on the LAN, or join
cargo run -p arena -- --host
cargo run -p arena -- --join udp://127.0.0.1:7777

Replication

Register a component with .replicated(). Transform already is. Put Replicated on the entities that should be sent.

An entity spawned from a prefab is spawned from the same prefab on each client. Its sprite, collider, and children do not cross the network. An entity that belongs to a level the client also loaded is adopted by its id, so a coin keeps the sprite the file gave it. With replication on, a level opened by load_scene or change_scene keeps the file's ids. A client sets those replicated records aside and spawns the server's copy when it arrives. An entity the server no longer has stays gone. A copy that was asked for too early is asked for again, once a round trip. ReplicaStats::level_waiting counts what is still set aside, separate from out_of_interest.

Each client receives what changed since it last acknowledged, highest Replicated::priority first, inside ReplicationConfig::bytes_per_snapshot.

Remote entities are drawn a little in the past, between two snapshots, so they stay smooth when packets bunch. The delay is measured from the link.

Interest

ReplicationConfig {
    interest: Some(Interest::new(30.0)),
    ..ReplicationConfig::default()
}

Each client is sent entities within that radius of what it watches. By default it watches the entities it owns (NetOwner). A spectator sets points:

tick.net.set_interest_points(peer, vec![camera_position]);

The server rebuilds a grid each tick. An entity enters at the radius and leaves a little further out (Interest::hysteresis, 10% by default), so one on the edge does not flicker. A child is sent exactly when the replicated root of its hierarchy is. Your own player is always sent to you. always_relevant sends an entity to everyone. relevance_radius overrides the radius for one entity. An entity with no Transform (match state) is sent to everyone.

Leaving the radius despawns the entity on that client. Coming back spawns it again. The editor's Network window shows each client's relevant set and draws the radius.

Prediction

The client moves its own player immediately and checks the server afterwards. Write the movement once, as a function of the entity, that player's input, and the step. The server runs it from tick.net.input::<Steer>(peer). The client runs it through tick.predict. When the server's state arrives, the client rewinds to it and replays inputs the server has not seen. If both ran the same steps, nothing pops.

Keep that function on the entity's own replicated components, the input, and the step. Move the player kinematically. The replay runs the function, not the physics step.

Lag compensation

Remote players are drawn in the past, so a client aims where the target was. Mark colliders LagCompensated. On the server:

if let Some(steer) = tick.net.input::<Steer>(peer) {
    let seen = tick.net.rewound(tick.world, peer);
    if let Some(hit) = seen.ray(from, aim, range, QueryFilter::new().excluding(me)) {
        // hit.entity, where this player saw it
    }
}

rewound answers ray, cast, point, and overlap_aabb. Lag-compensated colliders are where the shooter was drawing them. Everything else stays where it is now. The rewind is capped by the lag the server measured for that player (round trip, its variation, the snapshot rate, how long the input waited) and by LagCompensation::max_rewind (half a second). A client cannot claim an older time than its link justifies, and a claim in the future is the present. History is kept for about a second (LagCompensation::history). lag_compensation: None keeps none.

Record those poses by moving the entities in fixed_update. The history is written after each fixed step. The arena's zap uses this path.

Lobby

Turn the lobby on every end, before host or join, the same way replication is enabled.

tick.net.enable_lobby(LobbyConfig {
    name: "Ada".into(),
    min_players: 2,
    max_players: 4,
    late_join: LateJoin::Refuse, // or LateJoin::Play
    ..LobbyConfig::default()
});

The server holds names, slots, ready state, and who may start. Names are cut, cleaned, and made unique. tick.net.lobby() is the room. tick.net.lobby_events() is what changed this frame (LobbyEvent::Started, Left, and the rest). The host is the listen server's own player, or on a dedicated server the first player in (then the next, if they leave). The host's leaving ends a listen lobby. start() is refused until everyone is ready and there are enough players. A dedicated server's game may start the match itself.

Lobby messages use their own channel. tick.net.received() does not contain them. A client built against another lobby is refused at the handshake. A peer that connects and never joins is dropped after the session timeout plus JOIN_GRACE (12 seconds by default; join_timeout may only lengthen that). With the lobby on, replication goes only to the lobby's players.

assets/prefabs/lobby.prefab.ron is copied into every cargo xtask new-game. LobbyScreen::open runs it until LobbyOutcome::Started. Restyle it in the editor; keep the widget names. Player names are drawn as plain text, not rich text.

fanalor-server flags: --lobby, --min-players, --max-players.

LAN discovery

A host with HostOptions::discovery set answers UDP probes on port 7779 with its name, player counts, and a fingerprint. A client calls tick.net.discover_game. tick.net.discovered() lists answers. compatible is false for another build; joining that build is refused.

A search lasts SearchOptions::timeout (1.5 seconds) and resends while it runs. SearchOptions::targets names addresses when broadcasts do not cross the network. A server answers each source a few times a second at most, and only sources on the local network (private, link-local, loopback, VPN mesh) unless Advertise::scope is DiscoveryScope::Anyone. --discovery-public on fanalor-server is that wider scope.

cargo run -p fanalor-server -- scenes/sandbox.ron --lobby --discovery 7779 --name "Desk" --game sandbox

--discovery off disables it. --name and --game set the advertised strings.

The browser has no UDP. tick.net.discover returns DiscoveryError::Unsupported. Join by address. The lobby screen greys out Host and Find on LAN there. A web build of the arena joins with index.html?join=ws://HOST:7778.

In the editor

Open the arena and set Window ▸ Network ▸ Clients on Play (up to three). Press Play. The editor hosts and plays; each client is drawn as a map of what it sees. Latency, jitter, loss, and a bandwidth cap are edited live. The Profiler's net … counters are the round trip and the traffic. The Network window also lists each client's relevant entities.

cargo test -p fanalor-net --test lobby --test lobby_peers --test discovery
cargo test -p arena --test match

Clone this wiki locally