Skip to main content

Crate ggrs

Crate ggrs 

Source
Expand description

§GGRS

GGRS (good game rollback system) is a reimagination of the GGPO network SDK written in Rust. Instead of the callback-style API from the original library, GGRS returns a list of GgrsRequests for you to fulfill each frame.

§How It Works

Rollback networking lets your game run at full speed using only local input, predicting what remote players are doing. When real remote inputs arrive, GGRS detects any misprediction, rolls the game back to the last correct state, and re-simulates forward. To support this, your game needs to be able to:

  1. Save its state to a GameStateCell on request.
  2. Load a previously saved state from a GameStateCell on request.
  3. Advance by one frame given a set of player inputs.

GGRS handles everything else: input exchange, prediction, rollback scheduling, time synchronization, and desync detection.

§Quick Start

§1. Implement Config

use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Input { pub left: bool, pub right: bool, pub jump: bool }

pub struct GameState { /* ... */ }

pub struct GgrsConfig;
impl ggrs::Config for GgrsConfig {
    type Input = Input;
    type InputPredictor = ggrs::PredictRepeatLast;
    type State = GameState;
    type Address = std::net::SocketAddr;
}

§2. Build a Session

let socket = UdpNonBlockingSocket::bind_to_port(7000).unwrap();
let mut session = SessionBuilder::<GgrsConfig>::new()
    .with_num_players(2).unwrap()
    .with_input_delay(2)
    .add_player(PlayerType::Local, 0).unwrap()
    .add_player(PlayerType::Remote("127.0.0.1:7001".parse().unwrap()), 1).unwrap()
    .start_p2p_session(socket).unwrap();

§3. Drive the Game Loop

Each tick, poll the network, drain events, then advance the frame:

session.poll_remote_clients();
for event in session.events() { /* handle GgrsEvents */ }
session.add_local_input(local_handle, my_input).unwrap();
match session.advance_frame() {
    Ok(requests) => {
        for request in requests {
            // handle SaveGameState, LoadGameState, AdvanceFrame — in order
        }
    }
    Err(GgrsError::PredictionThreshold) => { /* skip frame */ }
    Err(e) => panic!("{e}"),
}

§Session Types

TypeUse case
P2PSessionMain multiplayer session; connects peers directly.
SpectatorSessionWatch a game without contributing input.
SyncTestSessionLocal determinism testing; no network required.

All session types are constructed with SessionBuilder.

§Feature Flags

  • sync-send: Adds Send + Sync bounds to Config, NonBlockingSocket, and session types. Enable this if you need to share sessions across threads.
  • wasm-bindgen: Enables WASM support. Required when targeting wasm32 with browser APIs.

§Further Reading

See the docs/ folder for guides on sessions, the main loop, requests and events, time synchronization, and more.

Structs§

GameStateAccessor
A read-only accessor for the T that the user previously saved into a GameStateCell.
GameStateCell
An Arc<Mutex> that you can save()/load() a T to/from. These will be handed to the user as part of a GgrsRequest.
Message
A messages that NonBlockingSocket sends and receives. When implementing NonBlockingSocket, you should deserialize received messages into this Message type and pass them.
NetworkStats
Statistics about the quality of the network connection to a remote peer.
P2PSession
A P2PSession provides all functionality to connect to remote clients in a peer-to-peer fashion, exchange inputs and handle the gamestate by saving, loading and advancing.
PredictDefault
An input predictor that always predicts that the next input for any given player will be the Default input, regardless of what the previous input was.
PredictRepeatLast
An InputPredictor that predicts that the next input for any player will be identical to the last received input for that player.
SessionBuilder
The SessionBuilder builds all GGRS Sessions. After setting all appropriate values, use SessionBuilder::start_yxz_session(...) to consume the builder and create a Session of desired type.
SpectatorSession
Connects to a remote host in a peer-to-peer fashion without contributing input.
SyncTestSession
A session for verifying that your game logic is deterministic, without any network involvement.
UdpNonBlockingSocket
A simple non-blocking UDP socket tu use with GGRS Sessions. Listens to 0.0.0.0 on a given port.

Enums§

DesyncDetection
Desync detection by comparing checksums between peers.
GgrsError
This enum contains all error messages this library can return. Most API functions will generally return a Result<(), GgrsError>.
GgrsEvent
Notifications that you can receive from the session. Handling them is up to the user.
GgrsRequest
Requests that you can receive from the session. Handling them is mandatory.
InputStatus
InputStatus will always be given together with player inputs when requested to advance the frame.
PlayerType
Defines the three types of players that GGRS considers:
SessionState
A session is always in one of these states. You can query the current state of a session via current_state.

Constants§

NULL_FRAME
Internally, -1 represents no frame / invalid frame.

Traits§

Config
Compile time parameterization for sessions.
InputPredictor
An InputPredictor allows GGRS to predict the next input for a player based on previous input received.
NonBlockingSocket
Custom transport layer for GGRS sessions.

Type Aliases§

Frame
A frame is a single step of execution.
PlayerHandle
Each player is identified by a player handle.