@web-engine-dev/netcode
Game networking library with state sync, prediction, lag compensation, and rollback.
Features
- State Synchronization: Efficient entity state replication
- Client Prediction: Responsive local input handling
- Lag Compensation: Server-side hit detection rollback
- Rollback Netcode: GGPO-style rollback for fighting games
- Delta Compression: Bandwidth-efficient state updates
- Interest Management: Only send relevant data
Installation
bash
npm install @web-engine-dev/netcode
# or
pnpm add @web-engine-dev/netcodeQuick Start
typescript
import { NetworkManager, StateSync, ClientPrediction } from '@web-engine-dev/netcode';
// Server-side
const server = new NetworkManager({ role: 'server' });
server.on('connection', (client) => {
console.log('Client connected:', client.id);
});
server.on('input', (client, input, frame) => {
// Process client input
processInput(client.entityId, input);
});
// Client-side
const client = new NetworkManager({ role: 'client' });
client.connect('wss://game-server.com');
// Send input
client.sendInput({
frame: currentFrame,
horizontal: inputX,
jump: jumpPressed,
});API Overview
State Synchronization
typescript
// Server: Register networked entities
const sync = new StateSync();
sync.register(entity, {
components: ['Position', 'Velocity', 'Health'],
updateRate: 20, // Updates per second
interpolation: true,
priority: 'high',
});
// Broadcast state
server.broadcast(sync.serialize());
// Client: Apply state
client.on('state', (data) => {
sync.deserialize(data);
});Client Prediction
typescript
const prediction = new ClientPrediction({
maxPredictedFrames: 10,
reconciliationThreshold: 0.01,
});
// Local prediction
prediction.predict(input, deltaTime);
// Reconcile with server state
prediction.reconcile(serverState, serverFrame);Lag Compensation
typescript
const lagComp = new LagCompensation({
historyLength: 20, // Frames of history
maxRewind: 200, // Max rewind time (ms)
});
// Store world state
lagComp.recordState(frame, worldState);
// Rewind for hit detection
const result = lagComp.rewindAndTest(clientRTT, () => raycast(origin, direction));Rollback Netcode
typescript
const rollback = new RollbackManager({
maxRollbackFrames: 7,
inputDelay: 2,
});
// Add local input
rollback.addLocalInput(frame, input);
// Add remote input
rollback.addRemoteInput(frame, playerId, input);
// Advance with rollback support
rollback.advance(() => {
// Simulate one frame
simulate(deltaTime);
});