Status doc for refactoring the current player-specific netcode into a generalized framework, then extracting that framework as a standalone Godot addon. Resume here after compact.
These came out of the design discussion and are not up for debate without explicit revisit:
- Composition over inheritance. Networked entities are any
Nodetype (CharacterBody3D, RigidBody3D, StaticBody3D, Node). Netcode lifecycle lives inNetPredictor/NetReplicator/NetReliablecomponent child nodes. Noextends NetPredictedEntitybase class. - Typed Resource state + command. User authors
PlayerState extends NetStateandPlayerInput extends NetCommandas pure data Resources with@export varfields only. Zero metadata in those.gdfiles. - Inspector-authored schema.
NetSchemais aResourcesaved as.tres(or inline on the NetPredictor node). Carries: state/command class refs, tick + snapshot rates, per-field metadata (quantization, predict flag, no_interp), correction channels, child node refs for SM / AnimTree replication. All network metadata lives here, not in code. - No custom
@annotations. Confirmed impossible without engine fork (valid_annotationsis a hard-codedstatic HashMapingdscript_parser.cpp). Editor-first authoring uses@export+ dropdowns, not custom annotations. - Single transport (GNS via Rust). Reliable and unreliable both ride the existing
NetworkDriverover GNS lanes. No second networking runtime. - Server-authoritative, all entities. No client authority for now. Lag compensation lives on the server via historical state buffer + rewind.
- Soft-determinism.
move_and_slideis not bit-deterministic across Win/Mac/Linux. Accept residual drift; snap-correct via correction channels. Same model CS2 uses in practice. - Configurable tick rate. No hard-coded 128Hz.
tick_hzandsnapshot_hzare schema settings; interp window is a float multiplier on snapshot interval (not enum 0/1/2). - Addon-ready. All framework code targets being extracted to
addons/netcode/. Game-side code imports fromaddons/netcode/...only.
┌──────────────────────────────────────────────────────────────────────┐
│ Game scene (project-specific) │
│ │
│ Player (CharacterBody3D) │
│ ├── CameraController, AnimationTree, SMs, etc. │
│ └── NetPredictor ← framework component │
│ root = ".." │
│ schema = preload("res://schemas/player_predicted.tres") │
│ │
│ Door (StaticBody3D) │
│ └── NetReplicator │
│ schema = preload("res://schemas/door_replicated.tres") │
│ │
│ Inventory (Node) │
│ └── NetReliable │
│ schema = preload("res://schemas/inventory_reliable.tres") │
└─────────────────────────────┬────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────┐
│ addons/netcode/ (the addon) │
│ │
│ components/ │
│ NetPredictor.gd — predicted entities │
│ NetReplicator.gd — replicate-only entities │
│ NetReliable.gd — reliable RPC / state │
│ │
│ resources/ │
│ NetSchema.gd — main config Resource │
│ NetState.gd — base class for state Resources │
│ NetCommand.gd — base class for command Resources │
│ NetFieldConfig.gd — per-field metadata │
│ NetCorrection.gd — reconcile channel │
│ NetChildRef.gd — child SM / AnimTree refs │
│ │
│ core/ (autoloads) │
│ NetSession.gd — peers, ids, handshake │
│ NetReplication.gd — entity registry, snapshot dispatch │
│ NetTimeline.gd — server tick clock, interp window │
│ NetReliableHub.gd — reliable RPC routing │
│ NetDebug.gd — overlay, graphs │
│ │
│ editor/ │
│ NetSchemaInspectorPlugin.gd — dropdowns, generate-fields button │
│ │
│ rust/ (gdextension binary, prebuilt per-platform) │
│ NetworkDriver (GNS sockets) │
│ SequenceRingBuffer, JitterBuffer, PacketSequence │
│ Schema-driven snapshot codec (delta encoding, quantization) │
│ │
│ netcode.gdextension │
│ plugin.cfg │
└──────────────────────────────────────────────────────────────────────┘
LIVE TICK (local authority):
NetPredictor._physics_process(delta)
├─ cmd = NetCommand.new()
├─ root._gather_command(cmd) # user code
├─ root._simulate(_shadow_state, cmd, delta) # user code
├─ _apply_corrections(delta) # smooths render toward shadow
└─ root._apply_state(_render_state) # user code: writes node properties
SERVER TICK:
NetPredictor._tick_server(delta)
├─ frames = _server_input_queue.consume()
├─ for frame: root._simulate(_shadow_state, frame.packet, frame.delta)
├─ root._apply_state(_shadow_state)
└─ broadcast NetStatePacket (delta-encoded vs per-client baseline)
RECONCILE (authority receives server snapshot):
NetPredictor.handle_state_packet(packet)
├─ _shadow_state = packet.state # snap shadow to server
├─ prune acked inputs
├─ for unacked: root._simulate(_shadow_state, cmd, dt) # replay
└─ _apply_corrections; root._apply_state
PROXY TICK (remote entity on client):
NetPredictor._tick_proxy(delta)
├─ render_us = NetTimeline.render_time_us() # now - interp_window
├─ pair = _state_buffer.get_interpolation_pair(render_us)
├─ interp_state = lerp(pair.from, pair.to, alpha) per field
├─ root._apply_state(interp_state)
└─ root._visualize(delta, interp_state) # one-shot SFX/VFX
_shadow_state and _render_state are typed Resource instances of schema.state_class. The user's _simulate mutates the typed Resource directly — state.pos = .... Framework encodes/decodes via reflection against schema.state_fields configs.
-
State Resource (
player_state.gd)class_name PlayerState extends NetState @export var pos: Vector3 @export var velocity: Vector3 @export var look: Vector2
-
Command Resource (
player_input.gd)class_name PlayerInput extends NetCommand @export var move_fb: float @export var move_lr: float @export var look: Vector2 @export var jump: bool # …
-
Entity controller — extends anything (CharacterBody3D, RigidBody3D, Node)
class_name PlayerController extends CharacterBody3D func _seed_state(state: PlayerState) -> void: ... func _gather_command(cmd: PlayerInput) -> void: ... func _simulate(state: PlayerState, cmd: PlayerInput, delta: float) -> void: ... func _apply_state(state: PlayerState) -> void: ... func _visualize(delta: float, state: PlayerState) -> void: pass # optional
-
Schema
.tres— authored in inspector. References state/command classes, lists field configs, correction channels, rates. -
Scene — add
NetPredictoras child, setrootandschema.
No code references the netcode addon except the type names of base classes (NetState, NetCommand) and component nodes. Hot-swappable.
| Component | Purpose | Use cases |
|---|---|---|
NetPredictor |
Client-side prediction + server-side authority + replay | Player, car, grenade, turret |
NetReplicator |
Server-auth snapshot replication, no prediction | Doors, lights, AI, world props |
NetReliable |
Reliable RPCs + reliable field replication | Inventory, scoreboard, match state |
Same scene pattern (child node with root + schema) for all three.
addons/netcode/
├── plugin.cfg
├── netcode.gd (EditorPlugin entry)
├── netcode.gdextension (Rust binary refs per-platform)
├── bin/
│ ├── libnetcode.linux.x86_64.so
│ ├── libnetcode.windows.x86_64.dll
│ └── libnetcode.macos.universal.dylib
├── components/
│ ├── net_predictor.gd
│ ├── net_replicator.gd
│ └── net_reliable.gd
├── resources/
│ ├── net_schema.gd
│ ├── net_state.gd
│ ├── net_command.gd
│ ├── net_field_config.gd
│ ├── net_correction.gd
│ └── net_child_ref.gd
├── core/
│ ├── net_session.gd (autoload)
│ ├── net_replication.gd (autoload)
│ ├── net_timeline.gd (autoload)
│ ├── net_reliable_hub.gd (autoload)
│ └── net_debug.gd (autoload)
├── editor/
│ ├── net_schema_inspector_plugin.gd
│ └── icons/
└── docs/
└── README.md
res://
├── entities/
│ ├── player/
│ │ ├── player_controller.gd
│ │ ├── player_state.gd
│ │ ├── player_input.gd
│ │ └── player.tscn (Player + NetPredictor child)
│ └── …
├── netcode_config/ (project's chosen schemas)
│ └── schemas/
│ ├── player_predicted.tres
│ ├── car_predicted.tres
│ └── …
└── game-specific stuff (UI, levels, etc.)
The Rust crate stays at rust/ in the project repo during development. For the addon distribution:
- Build prebuilt binaries via CI (
build-rustjob already exists in.github/workflows/godot-google-ci.yml) - Copy
librust.*fromrust/target/release/toaddons/netcode/bin/with platform-suffixed names - Optional: open-source the Rust crate separately (
netcode-gns-rs) so addon users can rebuild if needed
For the game project itself, keep rust/ and the addon's bin/ in sync via a make-addon script.
- No GDScript autoload dependencies on project code. Autoloads in
addons/netcode/core/may only reference other addon files. - Project's
project.godotautoload section registers the addon's autoloads under fixed names:NetSession,NetReplication,NetTimeline,NetReliableHub,NetDebug. - Rust binary is the only platform-dependent piece. Ship one
.dylib/.so/.dllper supported platform.
- Code: MIT or Apache-2.0 (permissive, addon market expects this)
- Rust binary: same as crate
- Discuss commercial dual-license later if pursuing sale; for now permissive FOSS is fine
Each phase ships independently. Test after every phase before moving to the next.
Deliverables:
- Add server tick clock (
u32monotonic at 128Hz) + handshake sync intoNetworkTransport/NetSession - Add
NetTimelineautoload withtick_hz,snapshot_hz,interp_window_ratio,render_time_us() - Move tick rate constants out of hard-coded
128references; read from autoload
Why first: every later phase depends on a server tick. Easy win, no breaking changes.
Files touched:
rust/src/network_driver.rs(add tick clock packet field)godot/autoload/network/network_transport.gd- new:
godot/addons/netcode/core/net_timeline.gd(or temporary location, will move in phase 7)
Deliverables:
PlayerInputPacketcarries last 3-6 inputs not just current- Server dedupes by sequence_id
- Drop inputs older than
MAX_INPUT_AGE_TICKS(200ms @ 128Hz = 26 ticks; expose as schema config later)
Why now: ~20 lines of work, big loss-resilience win, totally orthogonal to refactor.
Deliverables:
- Create
NetPredictor.gdcomponent with current player reconcile logic intact (still hardcoded horizontal/vertical for now) - Move
_unacked_inputs,_player_state_buffer,_server_input_queue,game_*shadow vars fromplayer.gdintoNetPredictor - Player becomes thin: gather + simulate + apply_state. Schema not yet introduced.
Why now: pure refactor, no schema yet, just relocates code. Validates the composition model on current behavior.
Deliverables:
NetStatebase Resource classNetCommandbase Resource classPlayerState extends NetStatewith@export var pos/velocity/lookPlayerInput extends NetCommandwith@export varfields (move from currentPlayerInputPacket)NetPredictorreflects on state class viaget_property_list(), allocates instances- Wire codec in Rust still uses hand-defined
define_packet!for now; will swap in phase 6
Why now: Decouples user code from packet types. After this phase, user touches only typed Resources.
Deliverables:
NetSchemaResource +NetFieldConfig+NetCorrection- First
.tres:player_predicted.treswith horizontal/vertical/look corrections NetPredictor._apply_correctionsreads from schema instead of hard-codedSNAP_THRESHOLD_*- Player controller's reconcile tunables get deleted from the script; they live in the .tres
Why now: Last refactor before delta encoding. After this, everything user-tunable is in .tres.
Deliverables:
- New Rust
SchemaDescriptortype built from a registered schema at runtime - Replace per-packet
define_packet!withNetStatePacket { schema_id, entity_id, last_input_seq, dirty_mask, payload_bytes } - Quantization handled per
NetFieldConfig.quant - Delta encoding + per-client baselines (biggest bandwidth win)
- Client ACKs via
last_received_tickfield in input packets
Why now: Biggest perf win, but depends on schemas existing.
Deliverables:
- Move all
Net*files intogodot/addons/netcode/ - Rename:
network_transport.gd→addons/netcode/core/net_session.gd(or similar) - Project's
project.godotautoload section rewritten to point at addon paths - Build script:
make-addon.shthat copies Rust libs fromrust/target/release/toaddons/netcode/bin/ plugin.cfg,netcode.gdextensionfiles- Verify the addon works in a fresh empty Godot project (smoke test)
Why now: All the refactoring is done. Pure file moves + path updates.
Deliverables:
NetChildRefschema entries auto-registerMovementStateMachine,PeekStateMachine,AnimationTreeNetStateMachinewrapper adopts current logic/visual dual-pointer pattern- AnimationTree parameter list configured in schema; framework reads
tree.get(path)on auth, writes on proxies - Delete
crouch_progress/prone_progress/peek_progressfields fromPlayerState(auto-derived from active state's@net var progress)
Why now: Big cleanup of player-specific packet fields. Validates the auto-sync layer end to end.
Deliverables:
NetReliablecomponentNetReliableHubautoload for routing- Inventory entity as the first user
- Idempotency keys + bundling
- Spawn-ordering against snapshots (snapshots carry
min_spawn_seq, buffered until satisfied)
Why now: Inventory work unblocks all UI-driven game features.
Deliverables:
- Per-entity historical state ring buffer on server (last ~250ms, 32 ticks @ 128Hz)
LagCompensator.rewind_to(client_tick)snapshot restore- Hit detection wrapper that auto-rewinds opponents
- Configurable per-server max rewind window (anti-cheat hardening)
Why now: Needed before serious shooter playtesting. Foundation for hit detection.
Skip until 16+ player tests show bandwidth pressure. PeerVisibilityFilter-style per-peer field gating.
Replace gns-rs link with Steamworks SDK SteamNetworkingSockets when Steam launch nears. Same API surface, gains SDR routing. No application code changes.
- Target: 16-player shooter, 120ms ping, ~2% loss, no visible stuttering.
- Tickrate: 128Hz physics, 64Hz snapshot send (configurable).
- Bandwidth ceiling per client downstream: ~250 Kbps after delta encoding (~190 Kbps typical).
- Interp window default: 1.0 × snapshot interval (= 15.6ms @ 64Hz).
- Lag-comp window: 250ms.
- Reliable RPC budget: <5/s/client steady state.
| Feature | netfox | This plan |
|---|---|---|
| Inheritance lock | None (RollbackSynchronizer is child node) |
None (NetPredictor is child node) — convergent design |
| Field declaration | Array[String] of NodePath:property |
@export var on typed Resource + .tres field configs |
| Type safety | Runtime string resolution | Typed @export, IDE autocomplete |
| Transport | ENet via MultiplayerAPI | GNS (Rust) |
| Quantization | None | Per-field via NetFieldConfig.quant |
| Delta encoding | Yes (enable_diff_states) |
Yes (phase 6) |
| Lag compensation | No | Yes (phase 10) |
| Interp window | Fixed | Float multiplier, runtime-adjustable |
| Schema authoring | Inspector array of strings | Inspector + .tres Resources with dropdowns |
| Market position | Free, GDScript, casual coop | High-perf shooter, Rust dep OK |
Convergent on the architecture; differentiated on performance ceiling and type safety.
- Sub-axis correction field syntax:
"pos.xz"vs"pos.x"+"pos.z"as separate entries vs a packed enum. Going with"pos.xz"for now (parser splits on.). NetStatesnapshot copy — deep copy viaduplicate()? Faster custom path? Profile before optimizing.- Animation tree parameter discovery — runtime via
AnimationTree.get_property_list()vs editor scan baking. Probably runtime is fine; ~50 params at most. - State machine state-id stability — currently uses child index. Need a stable ordinal (explicit
state_idexport on each State?) to survive reordering nodes in editor. - Multi-NetPredictor per entity — useful for layered prediction (e.g., player + held-weapon state)? Or one schema per entity, period? Lean: one per entity for v1.
- Spawn replication — server sends
EntitySpawnPacketreliable, includes entity_id + scene path + initial state. Snapshot stream carriesmin_spawn_seqto enforce ordering. - Schema versioning — wire format hash baked into handshake so mismatched schemas refuse to connect rather than corrupt state.
When resuming the refactor:
- Commit / verify current code state is clean (or stash pre-existing player.gd/scene changes)
- Create branch
refactor/netcode-foundations - Phase 1: server tick clock +
NetTimelineautoload - Validate against current single-player + multi-client connect flow
- Phase 2: input redundancy
- Phase 3: extract
NetPredictor(largest single PR; player.gd halves in size) - Continue down the phase list
Stop after each phase, smoke test, commit. Phase 3 is the riskiest because it's the structural pivot; everything after follows the pattern set there.
- GNS via Rust — gold-standard transport, untouched
define_packet!macro — keeps existing for handshake/spawn packets; new schema-driven codec is additiveSequenceRingBuffer,JitterBuffer,PacketSequence— Rust primitives reused as-is- Logic/visual state machine dual-pointer — preserved as
NetStateMachine, replay-safe semantics intact - Per-axis reconcile — generalized to declarative correction channels, math unchanged
- Scene-tree organization — minimally affected; NetPredictor adds one child node per networked entity