Character Prediction System
Short description: Unified FishNet Prediction V2 pipeline that discovers, sorts, and drives all IPredictableController subsystems through a single [Replicate]/[Reconcile] pair on the character's NetworkObject.
Table of Contents
- Overview
- Supported Platforms
- Features / Capabilities / Security Features
- Prerequisites
- Installation / Build
- Quick Start Guides
- Configuration
- Usage Examples
- Lag compensation
- Observer synchronisation
- Operational Checks
- System Architecture (Mermaid)
- Flow Diagram
- Project Structure
- License
Detailed File-Level Topology
Overview
FishNet's Prediction V2 allows only one [Replicate]/[Reconcile] pair per NetworkObject to work correctly. CharacterPredictionController solves this by acting as the single NetworkBehaviour entry point for the entire prediction pipeline. On Awake() it discovers all IPredictableController components on the same GameObject, sorts them by Order, and drives them through a unified tick cycle: PopulateInput → Replicate → CreateReconcile → Reconcile.
Subsystems (movement, buffs, cooldowns, equipment, attributes, abilities) implement IPredictableController and declare an Order value to control execution sequence. They never carry [Replicate]/[Reconcile] attributes themselves — all prediction traffic flows through the shared CharacterReplicateData and CharacterReconcileData structs, which are delta-serialized to minimize bandwidth.
Supported Platforms
| Platform | Status | Notes |
|---|---|---|
| Windows | ✅ Supported | Primary development platform |
| Linux | ✅ Supported | Server and client builds |
| WebGL | ✅ Supported | Via Unity WebGL export |
Built with Unity 6.6 (6000.6.8f1) using IL2CPP scripting backend.
Features / Capabilities / Security Features
Features
- Single prediction entry point — One
[Replicate]/[Reconcile]pair perNetworkObject, avoiding FishNet multi-behaviour prediction conflicts - Automatic controller discovery —
GetComponents<IPredictableController>()onAwake()withOrder-based sorting - Unified data structs —
CharacterReplicateData(input) andCharacterReconcileData(state) carry all subsystem data in one pipeline - Delta serialization — Bitmask-based field compression on structs, index-delta compression on arrays (
CooldownReconcileEntry[],BuffReconcileEntry[]) - Reference-equality shortcut — Cached reconcile snapshots skip delta comparison entirely when the array reference hasn't changed
- Deterministic replay — All controllers run against the same tick value (
input.GetTick()), ensuring identical results during reconcile replay - Lag compensation — Hits resolve against where the caster's client saw its peers, via a per-character position ring and a rewind scope. See Lag compensation
- Loss-detecting delta chain — A one-byte send sequence lets the reader reject a delta whose baseline it never received, instead of decoding it against the wrong one
- Observer sync without state forwarding — Observers do not simulate their peers. Position arrives via
NetworkTransform, and resources, buffs, equipment and ability casts via dedicated broadcasts
Registered Controllers
| Controller | Order | Responsibility |
|---|---|---|
KCCPlayer |
80 | Movement input, motor simulation, camera state |
BuffController |
85 | Buff tick/expiry, reconcile buff snapshots |
CooldownController |
90 | Cooldown expiry, reconcile cooldown snapshots |
EquipmentController |
93 | Equipment state, attribute modifiers, reconcile equip |
CharacterAttributeController |
95 | Resource regeneration, reconcile resource state |
AbilityController |
100 | Ability activation, spawning, RNG seed reconcile |
Security Features
- All prediction state is server-authoritative — clients cannot forge reconcile data
- Reconcile overwrites client state on mismatch, preventing prediction exploits
- Delta serializers guard against malformed packets with
MaxEntriescaps (4096; equipment 64), and every array read validates its count before allocating - Each spawn payload is length-framed, so a defensive abort seeks to the end of its own block rather than desynchronising every
NetworkBehaviourread after it — they all share one unframed buffer - The client-supplied view offset is treated as a claim, not a fact: capped at
LagCompensationTick.MaximumCompensationTicks, and clamped again by the recorded history window - Observers are never sent owner-only state — no generator state, no full cooldown tables, no inventory internals. The boundary is the
IsOwnercheck inAbilityController.RegisterObservedAbility
Prerequisites
- Unity 6.6 (6000.6.8f1) (or compatible version)
- FishNetworking with Prediction V2 support (
[Replicate]/[Reconcile]attributes) - FishMMO Shared Core —
IPredictableControllerinterface,CharacterBehaviourbase class - KinematicCharacterController — for
KinematicCharacterMotorStatein reconcile data
Installation / Build
The prediction system is an integral part of the FishMMO Unity project. There is no separate installation step.
- Clone or update the FishMMO repository.
- Open the project in Unity 6.6 (6000.6.8f1).
- The prediction system is located at
Assets/FishMMO/Shared/Implementation/Entity/Prediction/. - Ensure all FishMMO dependencies (FishNetworking, Shared Core, KinematicCharacterController) are present.
Quick Start Guides
Adding a New Predictable Controller
- Implement
IPredictableControlleron yourCharacterBehaviourorNetworkBehaviour:
public class MyController : CharacterBehaviour, IMyInterface, IPredictableController
{
public int Order => 50; // Choose order relative to other controllers
public void PopulateInput(ref CharacterReplicateData input)
{
// Write owner input into the shared struct (owner-only)
}
public void OnReplicate(ref CharacterReplicateData input, ReplicateState state, Channel channel)
{
// Simulate one tick using input data (runs on client + server)
}
public void OnCreateReconcile(ref CharacterReconcileData reconcileData)
{
// Write authoritative state into shared reconcile struct (server-only)
}
public void OnReconcile(CharacterReconcileData rd, Channel channel)
{
// Restore state from server reconcile data (client-only on mismatch)
}
}
- Add the component to the character prefab alongside
CharacterPredictionController. - Add any new fields to
CharacterReplicateDataand/orCharacterReconcileData. - Update the corresponding delta serializers if adding new fields.
Adding Fields to Replicate/Reconcile Structs
When a new subsystem needs to carry data through the prediction pipeline:
- Add the field to
CharacterReplicateData(for input) orCharacterReconcileData(for state). - Update the corresponding delta serializer (
CharacterReplicateDataDeltaSerializerorCharacterReconcileDataDeltaSerializer) to include the new field in the bitmask. - For array fields, implement
WriteArrayDelta/ReadArrayDeltamethods (seeCooldownReconcileEntryorBuffReconcileEntryfor examples).
Configuration
CharacterPredictionController
CharacterPredictionController extends NetworkBehaviour and has no inspector-exposed fields. All configuration is implicit:
| Behaviour | Description |
|---|---|
| Controller discovery | GetComponents<IPredictableController>() on Awake() — all controllers on the same GameObject are automatically found |
| Execution order | Sorted by IPredictableController.Order ascending — lower values run first |
| Tick binding | Subscribes to TimeManager.OnPreTick and OnTick on OnStartNetwork(), unsubscribes on OnStopNetwork() |
| Tick snapshots | CurrentLocalTickSnapshot, CurrentReplicateTickSnapshot and PendingReplicateTickSnapshot are published so consumers that run before this behaviour's own tick callback (ability objects, region triggers) do not observe the previous tick's value |
| Input authority | HasInputAuthority — an AI character answers "the server", everyone else "the owning client". Ownership alone cannot answer it: a monster is server-owned with no owning connection, while a pet is owned by the summoner's connection yet driven entirely by a server-side AIController. Decided by the character's type (NPC, which pets derive from), never by the presence of a brain component: the brain only exists on the server, so a component check would hand a pet's input to its owner's client. |
| Observer transport | ApplyObserverTransportMode silences the NetworkTransform only when prediction genuinely moves the character (a KCCPlayer is present) and state forwarding is on. An NPC runs the same pipeline but is moved by a NavMeshAgent, so its MotorState is default every tick and the transform is the only thing moving it. |
CharacterReplicateData
Unified per-tick input struct. Contains only input, not state.
| Field | Type | Subsystem | Description |
|---|---|---|---|
MoveAxisForward |
float |
KCC | Forward movement axis (W/S) |
MoveAxisRight |
float |
KCC | Right movement axis (A/D) |
MoveFlags |
int |
KCC | Bitmask: Jump, Crouch, Sprint (KCCMoveFlags) |
AimDirection |
Vector3 |
KCC | Unit aim vector, already quantised (see below) |
ViewOffsetTicks |
byte |
Lag comp | Whole ticks this client was rendering its peers behind server-present |
ViewOffsetFraction |
byte |
Lag comp | Sub-tick remainder of that offset, in 1/256ths of a tick |
ViewTickOffset |
ushort |
Lag comp | The exact server tick this client was DRAWING its peers at, as an offset from this input's tick (low 16 bits). Supersedes the two fields above when present |
ViewTickFraction |
byte |
Lag comp | Sub-tick part of that drawn tick, 1..255; 0 means "no exact claim" |
HeadingOffset |
short |
KCC | Yaw from the aim's heading to the body's, in quarter degrees (see Aim, body and launch line) |
ConvergenceDistance |
byte |
Ability | One-shot. Log-coded distance along the aim to the point under the crosshair; with the two below it states the launch line a projectile is simulated on. 0 = not given |
AimOriginRight / AimOriginUp |
sbyte |
Ability | One-shot. Where the launch line starts beside the eye, centimetres across the aim (held to 1 m) |
HitClaimVictim |
int |
Ability | One-shot. A character the owner's own copy of one of its ability objects hit, as network object id + 1; 0 = none (see Hit claims) |
HitClaimSpawnAge / HitClaimObject |
ushort / byte |
Ability | One-shot. Which object: input ticks since its cast spawned it, and its index in the cast |
ActivationFlags |
int |
Ability | Bitmask: IsActualData, Interrupt, IsHeld, IsConsumable, IsMount |
QueuedAbilityID |
long |
Ability | Ability or consumable template ID to activate |
EquipmentRequest |
byte |
Equipment | One packed equip/unequip request (EquipmentReplicateInput), 0 for "nothing asked" |
EquipmentIndex |
short |
Equipment | The source index in the named container for an equip; ignored for an unequip |
Delta serialized with an 8-bit bitmask, and all eight bits are allocated
(KCCPredictionDeltaSerializers): bit 0 both move axes, bit 1 heading offset, bit 2 move flags,
bit 3 the rare fields, bit 4 aim direction, bit 5 activation flags, bit 6 queued ability, bit 7 the
view claim (both forms share it). The axes ride a single signed byte each (MoveAxisCompression),
written together when either changes, and the aim direction a packed uint
(AimDirectionCompression: 16 bits of yaw, 16 of pitch).
Bit 3 opens a second flags byte for the fields that are present on perhaps one tick in a
hundred: bit 0 the equipment request, bit 1 the launch line (ConvergenceDistance and the two origin
offsets, three bytes), bit 2 a hit claim. These are one-shot: the writer sets the bit when the
input HAS the field, never when it changed, and the reader zeroes every rare field whenever bit 3 is
clear. Absent means zero, never "as the previous input". An input that follows one carrying a rare
field therefore has to reach the reader even if nothing else changed (the writer forces it), or the
reader would keep the request and run it twice. IsInertInput refuses to treat an input carrying a
launch line or a claim as an idle repeat for the same reason. A new rare field takes a bit of the
second byte; a new persistent field would mean widening the first.
The full form, which opens every packet, writes the same rare byte where it used to write the three equipment bytes unconditionally.
AimDirection replaced a full Quaternion CameraRotation. Nothing ever read the roll —
movement takes rotation * Vector3.forward to build its planar basis and the ability path takes
the same forward as its trace direction — so the quaternion carried a degree of freedom no
consumer used and that could not be represented exactly.
Quantise on the producer, before predicting. KCCPlayer.PopulateInput writes
AimDirectionCompression.Quantize(...) and MoveAxisCompression.Quantize(...) into the input
struct itself, not just onto the wire. This is input to a deterministic simulation, so the
producer must commit to the value the wire can carry — otherwise the owner predicts with one
direction while the server and observers simulate with the decoded one, and every cast diverges by
the quantisation error. Encode/Decode is a fixed point: the poles pin yaw to 0 and pitch uses
Atan2 rather than Asin, which is numerically flat near ±1.
The view claim is a client measurement the server cannot derive. See Lag compensation.
Aim, body and launch line
The camera is never at the character's eye: behind and below it in third person, half a metre to
the side over the shoulder. Three things are derived from it each tick by the owner
(KCCPlayer.ResolveOwnerAim, AimConvergence), and each travels in the form the server can check:
| What | How it is derived | Used for |
|---|---|---|
AimDirection |
From the eye at the start of the tick (KCCPlayer.TickAimOrigin) to the point under the crosshair: the camera's ray is traced from level with the eye, and the point is never nearer than 2 m |
The cast-time target trace and anything fired from the eye |
HeadingOffset |
The body faces and walks toward the same point, measured from where it is DRAWN and never nearer than 6 m; the offset is that heading less the aim's | The motor's movement basis and facing (AimConvergence.MovementRotation) |
| Launch line | The camera's own ray: it starts at the point of the ray level with the eye (the two origin offsets) and passes through the crosshair's point (ConvergenceDistance along the aim) |
The line a projectile is simulated on (AimConvergence.LaunchLine) |
The eye is the eye at the start of the tick, on every peer. The owner knows no other when it
builds the input, and the aim only reaches the crosshair's point if the shot starts from the eye it
was converged from. AbilityController (Order 100) runs after the motor has moved, so it reads the
eye KCCPlayer (Order 80) recorded first thing.
A projectile is simulated on the launch line and only DRAWN leaving the spawner. The spawner
(a point on a hand, wand or staff) is where the visuals start, on each client, as that client draws
it; it plays no part in the simulation, which is what lets it follow a cast animation that no
server plays. On the line, a projectile follows the crosshair at every range, so a shot led ahead
of a moving target passes where the crosshair was put. AbilityObject.ApplyCover keeps cover
honest: if scenery blocks the way from the eye to where the visuals join the line, the projectile
starts at the eye heading for that point and ends on the cover. An NPC has no camera and sends no
launch line: its projectile flies from its eye along its aim, which its brain took from that eye.
A stationary object (speed 0) stays at the spawner as the simulation has it.
The launch line is sent only on a tick that may spawn (AbilityController.PopulateConvergence:
a cast starting this tick, one with a tick or less to run, or a held one). A wrong guess costs
accuracy, never agreement: both peers fall back to the eye and the aim.
Equipment is input, and it rides here. EquipmentReplicateInput.TryPack packs a request into
one byte — two bits of EquipmentRequestKind, two of InventoryType (Inventory or Bank only), four
of ItemSlot — and EquipmentReplicateInput.TryUnpack refuses anything that does not name a
defined kind, container and socket. Zero is "no request" by construction, because
EquipmentRequestKind.None is zero and occupies the low bits. EquipmentController.PopulateInput
carries at most one request per tick; a second waits for the next.
An equip used to travel as a reliable broadcast the server applied at whatever tick it landed on, so
the item's attribute bonuses reached the owner only through the following reconcile and the movement
between the two was replayed at the new speed — a +15% speed item equipped mid-stride was a visible
snap. Carried on the replicate, both peers apply the change on the same tick, the reconcile confirms
rather than corrects, and a stale reconcile is undone and re-applied by the replay like any other
predicted action. The owner records each predicted move (PredictedMove: tick, item id, the
container on the other side and the index in it) so a reconcile that does not yet include the change
can put the item back exactly where it came from rather than into "the first container with room",
which the replay could not then undo.
CharacterReconcileData
Unified per-tick authoritative state struct.
| Field | Type | Subsystem | Description |
|---|---|---|---|
MotorState |
KinematicCharacterMotorState |
KCC | Full motor state (position, velocity, grounding) |
AbilityID |
long |
Ability | Currently active ability ID |
RemainingTicks |
uint |
Ability | Remaining activation ticks |
Seed |
int |
Ability | Deterministic RNG seed output |
PackedFlagsAndSlot |
int |
Ability | Packed activation flags (16-bit) + consumable slot (16-bit) |
ResourceState |
CharacterAttributeResourceState |
Attribute | Health/Mana/Stamina current + max values |
Cooldowns |
CooldownReconcileEntry[] |
Cooldown | Active cooldown snapshots (index-delta, ref-eq shortcut) |
Buffs |
BuffReconcileEntry[] |
Buff | Active buff snapshots (index-delta, ref-eq shortcut) |
Equipment |
EquipmentReconcileEntry[] |
Equipment | Equipped item snapshots (TemplateID, Slot, Seed, ItemID) — bit 10 |
Attributes |
AttributeReconcileEntry[] |
Attribute | Non-resource attribute snapshots (Value + ExternalModifier), sorted by TemplateID — bit 9 |
RngS0–RngS3 |
uint × 4 |
Ability | Full xoshiro128** RNG internal state — bit 8 |
ChargedHoldTicks |
uint |
Ability | Ticks a charged ability has been held past full charge — bit 11 |
Exposure |
ExposureReconcileEntry[] |
Weather | Weather exposure levels (16-bit quantised), sorted by TemplateID — bit 12; null when the character has no exposure states |
Thirteen of the sixteen bitmask bits are in use. When adding a field, take the next bit and update
WriteDelta and ReadDelta in lock-step, and append it to WriteCharacterReconcileData /
ReadCharacterReconcileData — they handle the same fields in the same order, and a field added to
one of them only silently misaligns every field after it.
Delta reconcile on FishNet's delta prediction
Delta reconcile runs on FishNet's delta prediction (FISHNET_DELTA_PREDICTION, set for every build
target — it changes the wire format). FishNet writes a one-byte header on every reconcile: a full
flag and a 7-bit id of a full reconcile.
- A full reconcile — the first one, one per observer added, and one at least every
min(TickRate, 60)ticks — is written with the regular serializer,WriteCharacterReconcileData. It is what a late-joining observer bootstraps from, and the periodic resync. - Every other reconcile is a delta against the last full reconcile (as readers decoded it), not
against the previous reconcile, written by
WriteDeltawithRootSerialize. A lost delta costs only itself; a lost full reconcile costs the deltas written against it, which FishNet discards (it holds no full reconcile with their id) rather than decoding against the wrong baseline, until the next full one.
Loss detection is therefore FishNet's, per behaviour. The 4.6.12 fork chained every delta onto the
previous reconcile and needed a Sequence counter, a send-time stamper hook and an absolute-snapshot
mode byte to survive loss; all three are gone. The contract the delta serializers keep: bytes iff they
return true; always write something at RootSerialize; consume the same bytes whatever the baseline
(a discarded delta is still decoded, to keep the state reader aligned); never modify the baseline,
which serves every delta for up to a second.
Delta serialized with a bitmask + per-field delta encoding. Array fields use index-delta compression with reference-equality shortcutting.
Sort contract: producers of
Attributes,Buffs, andCooldownsMUST emit entries sorted by their stable key (TemplateIDascending) so index-delta comparisons stay meaningful across ticks.
Usage Examples
Tick Execution Flow
Each TimeManager.OnTick, the controller executes:
// 1. Owner populates unified input
CharacterReplicateData input = default;
if (IsOwner)
{
for (int i = 0; i < controllers.Length; i++)
controllers[i].PopulateInput(ref input);
}
// 2. Replicate (runs on all: owner, server, replay)
Replicate(input);
// 3. Server creates reconcile
CreateReconcile();
The replicate tick is the owner's clock
input.GetTick() is the owning client's LocalTick, a counter that restarts at zero when that
client connects. The server runs the body every tick whether or not input is queued; with an empty
queue FishNet builds default data and stamps it _lastOrderedReplicatedTick + 1, and before the
owner's first input has arrived (the spawn round trip) that baseline is seeded from an estimate.
Upstream seeds it from TimeManager.LastPacketTick, which is fed by every connection's packets
and keeps only the highest tick it has ever seen — so every login after the first one a server
process has handled (a relog, a character switch, a scene transfer back, or a second player)
stamped the spawning character with an earlier session's clock, tens of thousands of ticks ahead.
FISHMMO EDIT in NetworkBehaviour.GetDefaultedLastReplicateTick: the server seeds from
Owner.PacketTick, the same estimate kept per connection. Without it
CharacterAttributeController.Regenerate's high-water mark rejected the owner's real inputs for
the whole session (stamina and mana never regenerated on any long-running server), and
BuffController/CooldownController translated their pre-replicate ticks by a garbage offset. CharacterAttributeController.AcceptReplicateTick adds a
second line of defence: a replicate that carried no real input (ReplicateState.Created unset)
cannot anchor the regen schedule until one that did has run. RegenReplicateTickSeedTests pins both.
A tick the server runs without input
When a player's input queue is empty FishNet still runs the replicate body, with default data and
without ReplicateState.Created. Nothing a player did is in that input, so nothing a player does
advances on it:
KCCPlayerdoes not step the motor.AbilityControllerdoes not count a cast down, spawn, or accept a claim (FreezesOnBlankTick). A cast is counted in the owner's INPUTS, because that is how the owner predicts it; counting blank ticks too finished it early on the server, left the owner without its projectile (a replayed tick does not spawn), and fired a cast that ended ON the blank tick with no aim. A cast that waits more thanMaximumBlankTicksInCastticks in a row is cancelled.FISHMMO EDIT in
PredictionManager.SendStateUpdate: while input is late, a state update is stamped with the tick of the last input the server RAN for the connection (ReplicateTick.RemoteTick), not that tick carried forward by the server ticks since. Upstream's stamp advanced on blank ticks while the state did not, which told the owner "this is where you were at your next tick" about a state that had not moved: one tick of its own movement pulled back per blank tick, and FishNet's start delay addsStateInterpolationmore of them before the queue runs again.The carried-forward stamp is still right for an owner that has STOPPED sending, and is kept for it: FishNet's owner goes quiet once its input is default, and the default data the server runs stands in for its next ticks. The server tells the two apart from the last input it ran (
NetworkConnection.LastInputReplicateLocalTick,PredictionManager.GetStateClientTick): an owner sends its default input before going quiet, so a queue that runs dry straight after input that was NOT default is late input. Every real FishMMO input carriesIsActualDataand so is never default; an idle owner is held by the server instead (ReplicateIdle). The exact stamp is used for at most one second of ticks, which bounds what the owner replays. Proposed upstream asfix/state-update-tick-late-input.
What remains on an underrun is the server's own pause: the character does not move there until its input arrives, and observers see it stop for those ticks.
Controller Order Example
If you need current movement/camera state to be available before buff, cooldown, attribute, and ability logic:
KCCPlayer (Order=80) → Updates position/velocity/camera state
BuffController (Order=85) → Ticks/expires buffs, applies modifiers
CooldownController (Order=90) → Expires elapsed cooldowns
CharacterAttributeController (Order=95) → Regenerates resources
AbilityController (Order=100) → Activates abilities, checks cooldowns + resources
Rules the 2026-11-14 audit added
Each closes a case where owner and server could count differently, or where a client's word was taken on trust.
The rules below are the record of it; PredictionAuditFixTests states each one as a test.
When the server may repeat an owner's input (held idle input).
- Only after the last TWO inputs it ran were repeats of each other (
TryStartHolding(requireRepeat: true)in FishNet'sNetworkBehaviour.Prediction.cs). An empty queue alone is not evidence the owner stopped: a standing player turning the camera sends a different inert input every tick, and its empty queue is LATE input. Holding there ran the missing ticks and then ran the late inputs on the same numbers. - Never during a cast, on either side (
ReplicateIdle<T>.CanHoldNow, answered byCharacterPredictionController.CastInProgress). Nothing is sent for this: each peer asks its own ability controller. The owner keeps sending every tick of a cast, and the server runs a blank tick for one whose input has not arrived, which the cast waits out (FreezesOnBlankTick). An input sent during a cast reads as inert, but repeating it is not harmless: every tick that runs counts the cast. - The first keepalives after an owner goes quiet follow 1, 2, 4, 8 and 16 ticks apart
(
ReplicateIdle.KeepaliveInterval), then everyKeepaliveTicks. - An idle owner keeps its previous view claim while nothing can use it (
KeepIdleViewClaim), so its input repeats at any frame rate. - The server drains a queue left more than one input over the buffer, one extra input a tick. Effects driven by the server's own clock (weather steps, drowning pulses, ship carry) run once per server tick.
- The start delay is what the buffer still lacks (
ReplicateIdle.StartDelay): a burst that already holdsStateInterpolation+ 1 inputs runs at once.
Casts count in tick numbers. AbilityController.AccountMissedCastTicks takes the ticks between the last
input counted and this one off the countdown first, so both peers finish on the same INPUT even when one before
it never arrived (made up for at most MaximumMissedCastTicks), and a number run twice counts once.
The tick on an input is bounded (ReplicateTickGuard, FishNet). Cooldowns, buff durations and
regeneration are timed on the owner's own tick counter, so the server bounds how far it may run AHEAD:
- For the first
SettleSecondsafter the first read, an input may be no further ahead of the first input than real time since the server gave the owner the object (Begin, fromResetState_Prediction), plus the window. This is what keeps world entry safe: the client's first frames are long, it catches their ticks up at once, and the first input read is the oldest of that burst. The first version anchored on that input and refused everything after it, which left the player stuck at the spawn point for minutes. - After that, an input more than
WindowSeconds(1 s) above the highest offset seen is refused. The reference rises by one tick eachCreepIntervalTicksand never falls. Slow is never refused. ReplicateTickGuard.Refusedcounts refusals, the server log says when an owner starts and stops being refused, and/admin simulatereports the count.
What a correction leaves alone and puts back.
- The owner does not announce buff changes (icon events, effects) while a correction is applied and replayed
(
BuffController.DefersAnnouncements, which also covers applies made by other controllers during the replay). The difference between what was last announced and the live set is announced once, on the next live tick (FlushAnnouncements). A buff that went and came back is not mentioned; one whose expiry the replay ran is. - A self-target ability's effects run again on the replayed tick (
AbilityObject.RunSelfTargetEffects), and so do the caster effects of any other ability's spawn chain (RunSpawnEffectsOnReplay), markedTickEventData.ReapplyOnly: only actions that answerBaseAction.ReappliesOnReplayrun, and only on the caster, whether the trigger or the action picks the targets. - A correction that finds the server with no cast where the owner had one also removes what that cast launched after the corrected tick.
- Weather "held" state comes from the server's buff list in the same correction.
Predictions on other characters are provisional. A debuff the caster predicts on a target is removed after
PredictedBuffConfirmationSeconds unless the server names it (BuffController.MarkPredictedByCaster). A
predicted hit that is given up puts the target's bar back (PredictedCombatEvents.OnPredictionUndone), unless
the server has sent that target's health since.
Hit claims additionally need a clear line from the swept path to the body (SceneryBetween), are measured
against a step that ends where the object stopped (TruncateLastSweep), and meet the victim's parry and shield
even when the object has already ended. The window is ClaimStepWindow = 8 steps.
A rider is carried on a tick with no input (KCCPlayer.CarryOnBlankTick), so it keeps its place on a
moving deck while its input is late.
Aim. The body's 6 m floor is measured on the ground plane (AimConvergence.BodyFloorAlongRay). The heading
offset covers the whole circle (MaxHeadingOffsetDegrees 180), so the aim is never bent to fit the body and the
body never snaps round. AimDirectionCompression.ToRotation keeps the aim's heading up to exactly vertical. The
owner's range pre-filter measures from the eye.
Lag compensation
Without compensation a hit resolves against where a character is now, while the shooter aimed at where it was rendered — its interpolation buffer plus its own latency in the past. At 6 m/s that gap runs from about 0.45 m on a same-city connection to 2.2 m at 300 ms, against ability hitboxes authored at half a metre. At any real latency the shooter's aim and the server's answer are describing different worlds.
The derivation
Write everything in fractional server ticks. The owner produces an input at server time S:
| Term | Meaning |
|---|---|
oneWay |
one-way network latency, in ticks |
interp |
LagCompensationTick.SpectatorInterpolationTicks — the client's render buffer |
queue |
PredictionManager.StateInterpolation — how long an arrived input waits before the replicate body consumes it |
- The state the owner is looking at left the server
oneWayago and is renderedinterpbehind even that, so it is watching server tickR = S − oneWay − interp. - The input crosses the network and then waits in the replicate queue, so the body runs at server
tick
A = S + oneWay + queue. - The offset subtracted is the client's claim (the full round trip plus its interpolation) plus
the queue depth the client cannot see:
A − (2·oneWay + interp + queue).
Substituting A gives S − oneWay − interp = R. Every latency term cancels exactly. That only
holds while the client's half carries the full round trip and the server's half adds the queue
depth; either mistake leaves a residue proportional to ping, which is invisible at any single
latency. LagCompensationClosedLoopTests composes both halves across a spread of round trips and
pins the identity.
The two halves
| Half | Where | What it does |
|---|---|---|
| Client | LagCompensationTick.ResolveViewOffset (called by KCCPlayer) |
Turns TimeManager.RoundTripTime and the interpolation setting into ViewOffsetTicks + ViewOffsetFraction. The server cannot derive this: FishNet exposes no per-connection latency server-side. |
| Server | LagCompensationTick.ResolveAnchor (called by TryResolve) |
Caps the claim, adds the queue depth, and subtracts from the server's own LocalTick. |
The anchor is always the server's tick. A replicate's tick is the owning client's unsynchronised counter and cannot index a history keyed by the server's — anchoring on it put every target outside the recorded window, so nothing rewound and every hit silently resolved against live positions.
The sub-tick byte is not a nicety. The whole-tick part alone quantises the rewind to a tick boundary, and an interpolated view does not sit on one. At 30 Hz and 6 m/s that is 20 cm — most of a capsule.
The rewind scope
LagCompensationRegistry.Rewind displaces every registered character in the scene to its recorded
pose, calls Physics.SyncTransforms (colliders follow transforms only at a sync point), and
restores on Dispose. Rules that hold it together:
- Nested rewinds are refused, not stacked. A nested scope would capture already-displaced positions as its restore target and strand every character in the past. An inner query runs against the outer rewind instead.
- A throw restores before it escapes. Otherwise everything displaced so far stays half a second in the past, permanently.
- Query, rank, dedupe and cap all happen inside one scope. Ranking outside it mixes a rewound world with a live one.
- The caster is excluded — it fires from where it is, not where it was.
The history ring
CharacterPositionHistory records one pose per tick on OnPostTick, into a ring sized from
maximumRewindMilliseconds (500 ms authored → 15 samples at 30 Hz). It never records while
displaced, which would persist a rewound pose as if it were real.
Resolution distinguishes two cases that look alike and are not:
- A little older than the window clamps to the oldest sample. Refusing it was a cliff, not a defence: the ceiling on how far back anyone can shoot is the recording either way, and an attacker reaches it by claiming a value just inside the window. Refusal only penalised honest high-latency clients.
- Wildly older is refused. A tick thousands out is not a latency claim at all — it is a tick domain error, and clamping it would hand back a real-looking pose for a tick nobody recorded.
500 ms RTT is the designed worst case, and the two constants deliberately disagree.
MaximumCompensationTicksis 30 while the ring holds 15 samples at 30 Hz, so past roughly 500 ms RTT the resolve clamps to the oldest sample and a player at 800 ms is compensated for about half of what the constant implies. That is intended, not an oversight:
- The clamp is the safe direction — it returns the oldest recorded pose and never falls through to a live one, so an over-window claim buys the recorded window and never more.
- The two constants answer different questions.
MaximumCompensationTicksbounds an attacker-controlled claim before it is trusted;maximumRewindMillisecondsbounds what was actually recorded. A claim capped below the ring length would be the real defect.- Rewinding further costs memory per character per scene and widens the window in which a player is shot by someone looking at a very stale world — the thing lag compensation trades against.
If the worst case ever moves, the knob is
maximumRewindMillisecondson the character prefab. Do not changeMaximumCompensationTicksto match the ring.
Who resolves hits
| Peer | Resolves? | Why |
|---|---|---|
| Server | Yes, inside a rewind to the caster's view | Authoritative |
| The caster's owner | Yes, as a prediction, uncompensated | Its world already is that rewound one, which is what makes its predicted hit and the server's agree by construction |
| A third-party observer | No | It holds every character interpolated against its own latency, so the same query answers a question nobody asked. It is told instead, by AbilityObjectHitBroadcast. |
Hit claims
The rewind reproduces the owner's view exactly while a character moves steadily and its updates arrive on time. It cannot when the owner drew something the server never had: the straight line between two position updates two ticks apart while the character turned between them, a character held at its last update because the next was late, a position on the wire's centimetre grid. No rewind can recover those, because the server does not know what a client drew.
So the owner says what it saw. When its own copy of one of its ability objects hits a character, the
next input carries a claim (HitClaimVictim, HitClaimSpawnAge, HitClaimObject). The server
(AbilityController.ApplyHitClaim, AbilityObject.TryApplyClaimedHit):
- finds the object by the tick its cast spawned on and its index in the cast;
- does nothing if its own sweep already hit that character (the usual case);
- otherwise checks one of the object's last few recorded sweeps against where the position history
puts the victim for the view the caster claimed on that step, with a tolerance of 0.1 m plus 2.5
ticks of the victim's own speed, capped at 1.5 m (
HitClaimGeometry); - applies the hit through the same path as a swept one.
An object that ended a tick or two earlier on scenery, or by running out, still answers for a few
ticks (TryApplyEndedClaim); one that spent its last hit on another character does not. A modified
client gains at most the tolerance. AbilityController.HitClaims turns the whole mechanism off, and
/admin simulate reports claims granted and refused.
Observer synchronisation
State forwarding is off for playable characters, and that is intended rather than a misconfiguration. Observers do not simulate their peers, so each subsystem has an explicit observer path:
| State | Owner | Observers |
|---|---|---|
| Position | Reconcile (MotorState) |
NetworkTransform |
| Resources | Reconcile (ResourceState) |
CharacterResourcesBroadcast, on a change-driven scheduler |
| Attributes | Reconcile (Attributes[], carrying the authoritative residual) |
CharacterAttributesBroadcast |
| Buffs | Own simulation | CharacterBuffsBroadcast (full set or delta) |
| Equipment | Own simulation + reconcile | EquipmentObservedSlotBroadcast |
| Ability casts | Own simulation | AbilityActivatedBroadcast |
| Ability hits | Own prediction, absorbed on echo | AbilityObjectHitBroadcast |
| Ability end-of-life | Own simulation | AbilityObjectDestroyedBroadcast (only for a hit-count end; lifetime expiry is identical everywhere and needs no message) |
Observed ability objects run on the playback clock. A client draws other characters in the
past, on one shared clock (NetworkTransform.PlaybackDrawTick). An observed copy of an ability
object runs on that same clock (AbilityObject.BeginObservedPlayback): its age is the clock less
the server tick it spawned on, it is hidden until the clock reaches that tick, and a hit, redirect
or end the server reports is applied when the clock reaches the tick the message was WRITTEN on
(LastPacketTick.LastRemoteTick, which a tick marker keeps exact when two ticks share a packet).
Observed cast animations wait for the clock the same way. Without a clock (nothing received yet,
timed playback off, every EditMode test) a copy is advanced by the estimated transit, as before.
AbilityObject.ObservedPlayback turns it off.
What is drawn is not what is simulated. On every client an object's visual children hang under
a Presented holder that is placed each frame from the move action's closed form at a fractional
tick (AbilityObject, region Presentation): the owner's at its own tick plus the fraction into the
next, an observer's at the playback clock. The visuals start at the caster's spawner as that client
draws it and blend onto the simulated path over HandBlendSeconds. The collider stays on the root,
at the simulated position; nothing in the presentation is read by a sweep, a hit or the server, and
nothing in these files reads a wall clock (ObserverSynchronizationProofTests).
They are broadcasts, not RPCs, sent to the observer set except the owner via
ObserverBroadcastScope. Every one of these is also written into the spawn payload in an
observer-shaped form, so a late joiner reconstructs the same visible state a peer that was present
the whole time holds.
Transform stream rules
Observers receive position through NetworkTransform, shaped per observer by
NetworkTransformDistanceLod (distance) and ObserverStreamingEntry (the viewer's full-rate cap).
Four rules keep that stream rendering as motion, and each was learned from a live "NPCs teleporting
or rubber banding" report (issue #176):
- No per-observer interval above
ObserverStreamingPolicy.MaxSendInterval(2), which mirrorsNetworkTransform._interpolationon every prefab. Both throttle tables — the prefab bands and the policy's cap bands — are clamped to it. The client waits for that many goals before it moves and again whenever its queue runs dry, and a queue overflow snaps to the newest goal; both scale with the interval.NetworkTransformLodBufferTestspins prefabs and policy together. - The first unreliable send after a reliable one goes to every observer (FISHMMO EDIT in
NetworkBehaviour.SendObserversRpc). The receiver measures it against the settle as one tick, so a filtered observer would otherwise play N ticks of motion in one at every stop-and-go. - Positions pack to 24 bits at 1 cm (FISHMMO EDIT in
NetworkTransform, multiplier 100 on every prefab). The wire grid must stay well under a walking character's per-tick displacement (5 cm at 30 Hz); the 10 cm grid tried before rendered a walk as alternating stalls and hops. - Clients have no NavMeshAgent at all. The agent arrives with the server-side brain, which
AIBrainHostadds only when the server spawns an NPC. An agent on a client would re-map the interpolated transform onto the client's NavMesh every frame.
The one thing genuinely broken by forwarding-off is a character with nothing to replicate position —
CharacterPredictionController.OnStartNetwork warns for a predicted object with no
NetworkTransform, because that presents as a content bug (a frozen character that keeps dealing
damage) rather than a networking one.
The exception: moving platforms
KCCPlatform is the one object that does forward state (_enableStateForwarding: 1 on the
scene MovingPlatform, pinned by InterestManagementWiringTests.OnlyPlatforms_ShipWithStateForwardingOn).
The scale argument above is about relaying every owner's input to every observer; an ownerless
platform has no input — its replicate is an empty struct — and the only cost is one delta-encoded
reconcile (Vector3 + goal byte + chain sequence) per observer per tick. In return FishNet runs the
platform's replicate on every client (ahead of the server by that client's ping, exactly as the
FishNet demo describes), and rolls it back and replays it in lockstep with the rider on every
reconcile, so a replayed ground probe meets the deck where it actually stood. The rider is conveyed
through KCC's attached-rigidbody seam in KinematicCharacterMotor.UpdatePhase1 (FISHMMO EDIT),
never through BaseVelocity, which the controller overwrites before the move. See issue #228.
Operational Checks
| Check | How to Verify | Expected Result |
|---|---|---|
| Controller discovery | Enter Play mode, break on Awake() |
controllers array contains all 5 controllers sorted by Order |
| State Forwarding | Inspect NetworkObject Prediction settings |
EnableStateForwarding == false on every shipped prefab (the scene MovingPlatform is the deliberate exception — see above) — the interpolated open-world mode. Observers are fed by per-controller broadcasts, not by a forwarded reconcile; see ObserverSyncMode. CharacterPredictionController.OnStartNetwork warns only when forwarding is off AND there is no NetworkTransform, because then nothing replicates position at all |
| Tick execution | Place a breakpoint in TimeManager_OnTick |
Called every server tick; PopulateInput runs only for owner |
| Replicate pipeline | Activate an ability on client | OnReplicate fires on both client and server with identical tick |
| Reconcile pipeline | Force a mismatch (server modifies ability state) | OnReconcile fires on client, restoring server state |
IsSpawned gate |
Break in CreateReconcile |
Guarded by IsServerStarted && IsSpawned; reconciles are dropped before the NetworkObject is fully spawned to avoid NREs through partially-wired subsystems |
| Delta serialization | Monitor network traffic | Unchanged ticks transmit minimal bytes (bitmask-only for structs, skipped for reference-equal arrays) |
| Replay determinism | Cause a reconcile | All controllers replay from the reconcile tick with identical results |
| Order enforcement | Log Order values in Awake() |
Sorted ascending: 80, 85, 90, 93, 95, 100 |
FISHMMO EDIT in the FishNet weaver (CodeGenerating/Extension/MethodDefinitionExtensions.CreateParameters,
CreateCopy, TypeDefinitionExtensions.GetOrCreateMethodDefinition, GeneralHelper.CreateParameter; issue #229).
For every predicted behaviour the weaver copies NetworkBehaviour.Replicate_Replay_Start(uint replayTick) into
the user assembly. Upstream built the copied parameter around FishNet.Runtime's own uint type reference
instead of an imported one. Cecil reads a parameter's custom attributes lazily through
ParameterType.Module, and its writer assigns the parameter's new Param row id before it asks
HasCustomAttributes, so the lookup went to FishNet.Runtime's attribute table at whatever row the copy
received in FishMMO.Shared. Whenever that row was an in parameter over there, its [IsReadOnly]
attribute (constructor owned by the other module) came along and the weave died with
"Member 'IsReadOnlyAttribute::.ctor()' is declared in another module and needs to be imported" — logged
by Unity as "Scripts have compiler errors" with no error CS anywhere. Whether the rows collide depends on
the parameter counts of both assemblies, which is why unrelated edits (a new helper method, an Editor
asmdef split) and different platforms flipped it. The edit imports the type, seals the attribute list
while the row id is still 0, and clones any copied attribute with an imported constructor. Re-apply after a
FishNet upgrade; the reproduction is a method with enough parameters to push the generated row onto one
of FishNet.Runtime's [IsReadOnly] rows (Param rows of Library/Bee/artifacts/*/FishNet.Runtime.dll,
the pre-weave build the resolver actually opens).
System Architecture (Mermaid)
The diagrams below describe the entire Prediction/ folder — components, the unified data structs, delta-serializer paths, and the per-tick lifecycle. They are the canonical reference; ASCII diagrams further down repeat the same information for terminal-only viewers.
1. Component & Data-Flow Topology
flowchart TB
classDef driver fill:#1f4e79,color:#fff,stroke:#0f2030,stroke-width:1px
classDef subsystem fill:#2e7d32,color:#fff,stroke:#143316,stroke-width:1px
classDef data fill:#7e57c2,color:#fff,stroke:#311b6b,stroke-width:1px
classDef serializer fill:#ef6c00,color:#fff,stroke:#7a3700,stroke-width:1px
classDef external fill:#455a64,color:#fff,stroke:#1c272c,stroke-width:1px,stroke-dasharray:3 3
subgraph NO[NetworkObject: Character]
direction TB
CPC["CharacterPredictionController\n(single [Replicate] / [Reconcile])"]:::driver
subgraph Subs["IPredictableController components (sorted by Order)"]
direction TB
KCC["KCCPlayer · Order 80"]:::subsystem
BUF["BuffController · Order 85"]:::subsystem
CD["CooldownController · Order 90"]:::subsystem
ATT["CharacterAttributeController · Order 95"]:::subsystem
ABI["AbilityController · Order 100"]:::subsystem
end
CPC --> KCC
CPC --> BUF
CPC --> CD
CPC --> ATT
CPC --> ABI
end
subgraph Shared["Unified prediction structs"]
direction LR
RD["CharacterReplicateData\n(IReplicateData)"]:::data
RC["CharacterReconcileData\n(IReconcileData)"]:::data
end
subgraph Ser["Delta serializers"]
direction LR
REP_SER["CharacterReplicateData\n(generated)"]:::serializer
REC_SER["CharacterReconcileDataDeltaSerializer\nbitmask + per-field + array delta"]:::serializer
RES_SER["CharacterAttributeResourceStateSerializer\n(7-bit bitmask)"]:::serializer
BUF_SER["BuffReconcileEntry\nWrite/ReadArrayDelta"]:::serializer
CD_SER["CooldownReconcileEntry\nWrite/ReadArrayDelta"]:::serializer
ATT_SER["AttributeReconcileEntry\nWrite/ReadArrayDelta"]:::serializer
KCC_SER["KCCPredictionDeltaSerializers\n(MotorState 13 live bits)"]:::serializer
end
subgraph Sep["Separate NetworkObjects (own predicted pair)"]
direction TB
PLAT["KCCPlatform"]:::external
REG["Region · server-only\n(OnTick LocalTick)"]:::external
end
KCC -- "PopulateInput / OnReplicate / OnReconcile" --> RD
ABI -- "PopulateInput / OnReplicate / OnReconcile" --> RD
BUF -- "OnCreateReconcile / OnReconcile" --> RC
CD -- "OnCreateReconcile / OnReconcile" --> RC
ATT -- "OnCreateReconcile / OnReconcile" --> RC
KCC -- "OnCreateReconcile / OnReconcile" --> RC
ABI -- "OnCreateReconcile / OnReconcile (RNG + flags)" --> RC
RD --> REP_SER
RC --> REC_SER
REC_SER --> RES_SER
REC_SER --> BUF_SER
REC_SER --> CD_SER
REC_SER --> ATT_SER
REC_SER --> KCC_SER
REP_SER -. "wire (Unreliable Channel)" .-> CPC
REC_SER -. "wire (Unreliable Channel)" .-> CPC
2. Per-Tick Lifecycle (sequence)
sequenceDiagram
autonumber
participant TM as TimeManager
participant CPC as CharacterPredictionController
participant Subs as Subsystems (Order 80,85,90,95,100)
participant Net as FishNet wire
participant Cli as Owning client
TM->>CPC: OnTick
alt IsOwner
loop for each subsystem (asc Order)
CPC->>Subs: PopulateInput(ref CharacterReplicateData)
end
end
CPC->>CPC: Replicate(input)
loop for each subsystem (asc Order)
CPC->>Subs: OnReplicate(ref input, state, channel)
end
opt IsServerStarted && IsSpawned
CPC->>CPC: CreateReconcile()
loop for each subsystem (asc Order)
CPC->>Subs: OnCreateReconcile(ref CharacterReconcileData)
end
CPC->>Net: Reconcile(data) [DeltaSerializer]
Net-->>Cli: snapshot bytes
end
Cli->>CPC: [Reconcile] entry (on mismatch)
loop for each subsystem (asc Order)
CPC->>Subs: OnReconcile(rd, channel)
end
Cli->>CPC: Replay [reconcileTick … currentTick]
Note over CPC,Subs: Each replayed tick re-runs<br/>OnReplicate with cached inputs<br/>under state.ContainsReplayed()
3. CharacterReconcileData Layout & Delta Strategy
flowchart LR
classDef field fill:#37474f,color:#fff,stroke:#101a1f,stroke-width:1px
classDef arr fill:#5d4037,color:#fff,stroke:#1b0f0c,stroke-width:1px
classDef serial fill:#ef6c00,color:#fff,stroke:#7a3700,stroke-width:1px
RC([CharacterReconcileData])
RC --> MS["MotorState\n13 live bits of a 16-bit mask"]:::field
RC --> RS["ResourceState\n(7-bit bitmask: HP/MP/Stamina + max + NextRegenTick)"]:::field
RC --> AID["AbilityID + RemainingTicks + Seed"]:::field
RC --> PFS["PackedFlagsAndSlot (int32)\nlow 16 = AbilityActivationFlags\nhigh 16 = consumable slot (signed)"]:::field
RC --> RNG["RngS0..RngS3 (xoshiro128**)"]:::field
RC --> COOL["Cooldowns[]"]:::arr
RC --> BUFF["Buffs[]"]:::arr
RC --> ATTR["Attributes[]\n(non-resource: Value + ExternalModifier)"]:::arr
MS --> KCC_SER["KCCPredictionDeltaSerializers"]:::serial
RS --> RES_SER["CharacterAttributeResourceStateSerializer"]:::serial
COOL --> CD_SER["CooldownReconcileEntry.Write/ReadArrayDelta"]:::serial
BUFF --> BUF_SER["BuffReconcileEntry.Write/ReadArrayDelta"]:::serial
ATTR --> ATT_SER["AttributeReconcileEntry.Write/ReadArrayDelta"]:::serial
subgraph Compression["Array compression rules"]
direction TB
R1["ReferenceEquals(prev,next) → 0 bytes"]
R2["Equal length, partial change → packed 16-bit header (high bit = delta) + (index, entry) pairs"]
R3["Length change or forceWrite → packed header + full array"]
R4["MaxEntries = 4096 with stream-preserving drain on overflow"]
end
CD_SER --- Compression
BUF_SER --- Compression
ATT_SER --- Compression
4. Folder & Cross-Folder Dependencies
flowchart LR
classDef folder fill:#263238,color:#fff,stroke:#000
subgraph PRED["Prediction/ (this folder)"]
direction TB
DRV["Driver:\nCharacterPredictionController,\nCharacterReplicateData,\nCharacterReconcileData,\nCharacterReconcileDataDeltaSerializer,\nCharacterTickExtensions"]:::folder
K["KCC/"]:::folder
B["Buff/"]:::folder
A["CharacterAttribute/"]:::folder
AB["Ability/"]:::folder
ABCD["Ability/Cooldown/"]:::folder
ABACT["Ability/Activation/"]:::folder
ABSN["Ability/Snapshot/"]:::folder
ABTPL["Ability/Template/"]:::folder
R["Region/"]:::folder
end
subgraph EXT["Outside this folder"]
direction TB
IF["Shared/Core/Entity/Prediction/\nIPredictableController, ICooldownController,\nIAbilityController"]:::folder
FN["FishNet.Object.Prediction"]:::folder
KCCPkg["KinematicCharacterController package"]:::folder
end
DRV --> K
DRV --> B
DRV --> A
DRV --> AB
AB --> ABCD
AB --> ABACT
AB --> ABSN
AB --> ABTPL
A -. "AttributeReconcileEntry rides DRV's CharacterReconcileData" .- DRV
R -. "server-only triggers; not part of the predicted character pipeline" .- DRV
DRV --> IF
DRV --> FN
K --> KCCPkg
Flow Diagram
High-Level Overview
flowchart LR
Input[Local input] --> Predict[Client predict]
Predict --> State[Local state]
Server[Server tick] -->|snapshot| Reconcile[Reconcile]
Reconcile --> Predict
Predict --> Replay[Replay unacked inputs]
Replay --> State
Per-Tick Pipeline
TimeManager.OnTick()
│
▼
┌──────────────────────────────────────────────────┐
│ PopulateInput (Owner only) │
│ ┌─ KCCPlayer.PopulateInput (Order=80) │
│ ├─ BuffController.PopulateInput (Order=85) │ ← no-op
│ ├─ CooldownController.PopulateInput (Order=90) │ ← no-op
│ ├─ EquipmentController.PopulateInput(Order=93) │ ← no-op
│ ├─ CharacterAttributeController (Order=95) │ ← no-op
│ └─ AbilityController.PopulateInput (Order=100) │
│ │
│ Result: CharacterReplicateData populated │
└─────────────────────────┬────────────────────────┘
│
▼
┌──────────────────────────────────────────────────┐
│ [Replicate] (Owner + Server + Replay) │
│ ┌─ KCCPlayer.OnReplicate → Motor sim │
│ ├─ BuffController.OnReplicate → Tick() │
│ ├─ CooldownController.OnReplicate → Expire() │
│ ├─ CharacterAttributeController → Regen() │
│ └─ AbilityController.OnReplicate → Activate │
└─────────────────────────┬────────────────────────┘
│
▼
┌──────────────────────────────────────────────────┐
│ CreateReconcile (Server only) │
│ ┌─ KCCPlayer.OnCreateReconcile → MotorState│
│ ├─ BuffController.OnCreateReconcile → Buffs[] │
│ ├─ CooldownController → Cooldowns │
│ ├─ CharacterAttributeController → Resources │
│ └─ AbilityController → Ability+RNG│
│ │
│ Result: CharacterReconcileData sent to client │
└─────────────────────────┬────────────────────────┘
│
▼ (on mismatch)
┌──────────────────────────────────────────────────┐
│ [Reconcile] (Client only) │
│ ┌─ KCCPlayer.OnReconcile → Restore │
│ ├─ BuffController.OnReconcile → Restore │
│ ├─ CooldownController.OnReconcile → Restore │
│ ├─ CharacterAttributeController → Restore │
│ └─ AbilityController.OnReconcile → Restore │
│ │
│ Then: Replay all ticks from reconcile→current │
└──────────────────────────────────────────────────┘
Delta Serialization
CharacterReplicateData: 8-bit byte bitmask (fully allocated; bit 3 opens a second byte of rare one-shot fields) → only changed fields written
CharacterReconcileData: ushort bitmask, 12 of 16 bits in use → per-field delta encoding
├── KinematicCharacterMotorState: ushort bitmask, 13 live bits (bit 4 retired, left as a gap)
├── CharacterAttributeResourceState: 7-bit byte bitmask
├── CooldownReconcileEntry[]: index-delta compression (reference-equality shortcut)
├── BuffReconcileEntry[]: index-delta compression (reference-equality shortcut)
├── EquipmentReconcileEntry[]: index-delta compression (reference-equality shortcut)
├── AttributeReconcileEntry[]: index-delta compression (reference-equality shortcut)
└── RNG state (RngS0–S3): 4 × uint, only when changed
Project Structure
Directory Structure
Prediction/
├── CharacterPredictionController.cs # Unified prediction driver (NetworkBehaviour, sole [Replicate]/[Reconcile])
├── CharacterReplicateData.cs # Shared per-tick input struct [UseGlobalCustomSerializer]
├── CharacterReconcileData.cs # Shared per-tick state struct [UseGlobalCustomSerializer]
├── CharacterReconcileDataDeltaSerializer.cs # Bitmask-based delta serializer for reconcile data
├── CharacterTickExtensions.cs # ICharacter.GetLocalTick() helper (extension class — invisible to a type-level scan, not dead)
├── PredictionTick.cs # A tick that can only be produced from a replicate input, so the compiler enforces tick sourcing
├── AimDirectionCompression.cs # Yaw/pitch packing for CharacterReplicateData.AimDirection; Encode/Decode is a fixed point
├── MoveAxisCompression.cs # Signed-byte packing for the movement axes
├── CharacterAimOrigin.cs # Derives the aim origin from the motor (never replicated — it is reconstructible)
├── AimConvergence.cs # Aim from the eye to the crosshair's point, the body's heading offset, and the launch line a projectile is simulated on
├── PayloadVisibility.cs # Chooses the owner or observer spawn-payload shape for a connection
├── ObserverSyncMode.cs # Whether a NetworkObject's observers consume reconcile or broadcasts
├── NetworkTransformDistanceLod.cs # Per-observer send-rate shaping for the NetworkTransform
├── Ability/ # Ability system (see Ability/README.md)
│ ├── Ability.cs # Runtime ability instance
│ ├── AbilityController.cs # IPredictableController (Order=100), partials below
│ ├── AbilityController.Activation.cs # Activation pipeline
│ ├── AbilityController.Knowledge.cs # Known ability / event templates
│ ├── AbilityController.Networking.cs # Knowledge broadcasts (NOT state replication)
│ ├── AbilityObject.cs # Spawned ability instance (projectile / hit volume)
│ ├── AbilityObjectSnapshot.cs # Detached object snapshot (outlives caster)
│ ├── AbilityObjectSweep.cs # Swept-volume hit gathering (overlap at the start + cast along the segment), distance-ordered
│ ├── PredictedAbilityStateHistory.cs # Owner-side per-tick (seed, abilityID) record the reconcile compares against
│ ├── AbilityPrefabColliderCache.cs # Caches colliders per ability prefab to avoid GetComponent per spawn
│ ├── AbilityContainerAllocator.cs # Allocates deterministic container IDs for spawned objects
│ ├── AbilitySummary.cs # AbilityStatBlock + the one composition behind every ability tooltip
│ ├── AbilityActivationFlags.cs # 16-bit flags packed into CharacterReconcileData.PackedFlagsAndSlot
│ ├── Activation/ # AbilityActivationReplicateData (per-ability input shape)
│ ├── Cooldown/ # Cooldown system (see Ability/Cooldown/README.md)
│ ├── Snapshot/ # SnapshotCharacter / SnapshotAttributeController
│ └── Template/ # AbilityTemplate, AbilityType, AbilitySpawnTarget, Pet*, Events/
├── Buff/ # Buff system (see Buff/README.md)
│ ├── Buff.cs # Per-buff state holder
│ ├── BuffController.cs # IPredictableController (Order=85)
│ ├── BuffReconcileEntry.cs # (TemplateID, ExpiryTick, NextTickTick, Stacks, TickCount, CumulativeTickMultiplier, RemainingCharges) + array-delta
│ ├── ObservedBuffEntry.cs # Display-only observer strip entry (7-byte wire) + ObservedBuffStatement provenance
│ ├── DamageMitigation.cs # Block / absorb / deflect resolution consulted when a hit lands
│ ├── ShieldVolume.cs # Authored shield shape, tested in the character's OWN space
│ └── Template/ # AttributeBuffTemplate, CompositeBuffTemplate, etc.
├── Equipment/ # Equipment rides the replicate
│ ├── EquipmentController.cs # IPredictableController (Order=93)
│ ├── EquipmentReconcileEntry.cs # Per-slot authoritative snapshot + array-delta
│ └── EquipmentReplicateInput.cs # TryPack/TryUnpack for the one-byte equip/unequip request on CharacterReplicateData
├── CharacterAttribute/ # Attribute system (see CharacterAttribute/README.md)
│ ├── CharacterAttributeController.cs # IPredictableController (Order=95)
│ ├── CharacterAttribute.cs # Non-resource attribute runtime
│ ├── CharacterResourceAttribute.cs # Health / Mana / Stamina runtime
│ ├── CharacterAttributeResourceState.cs # 7-field snapshot struct
│ ├── CharacterAttributeResourceStateSerializer.cs # Regular + delta serializers (BeforeSceneLoad registration)
│ ├── AttributeReconcileEntry.cs # Non-resource attribute snapshot + array-delta
│ ├── ModifierSource.cs # The attributed-modifier ledger key: (Kind, Id, Index)
│ ├── CharacterDamageController.cs # Damage / heal / kill pipeline
│ ├── CombatEventCoalescer.cs # Merges one tick's hits sharing (source, kind, damage type) into one report
│ ├── PredictedCombatEvents.cs # Client-side predicted damage/heal labels: settled by the server's report, re-texted by an Evade/Immune refusal, greyed out when no report comes
│ ├── ObservedResourcePushScheduler.cs # Decides when an observer resource push is due (in-combat vs out-of-combat interval)
│ └── Template/ # CharacterAttributeTemplate, formulas, damage/resistance
├── KCC/ # Kinematic Character Controller
│ ├── KCCPlayer.cs # IPredictableController (Order=80) — movement prediction
│ ├── KCCController.cs # Motor simulation (ICharacterController)
│ ├── KCCCamera.cs # Third-person camera controller
│ ├── KCCPlatform.cs # Moving platform prediction (separate NetworkObject — own [Replicate]/[Reconcile])
│ ├── KCCInputReplicateData.cs # KCC-specific replicate data (used internally)
│ ├── KCCMoveFlags.cs # Movement flag enum (Jump, Crouch, Sprint)
│ ├── KCCPlatformDeltaSerializers.cs # Delta serializers for the moving-platform pipeline
│ └── KCCPredictionDeltaSerializers.cs # Delta serializers for motor state + replicate data
├── LagCompensation/ # Rewind-to-the-caster's-view (see "Lag compensation" above)
│ ├── LagCompensationTick.cs # BOTH halves of the derivation, as pure functions: ResolveViewOffset (client) and ResolveAnchor (server)
│ ├── LagCompensationRegistry.cs # The rewind scope: displace every character, sync, restore. Refuses nesting.
│ ├── CharacterPositionHistory.cs # Per-character pose ring, sized from maximumRewindMilliseconds
│ ├── LagCompensatedQuery.cs # OverlapSphereNearest / RaycastNearest — query, rank, dedupe and cap all inside ONE scope
│ ├── RewindTarget.cs # A tick plus a sub-tick fraction, clamped
│ └── HitClaimGeometry.cs # The tolerance and segment-to-capsule distance a hit the owner claims is checked with
├── ObserverStreaming/ # Per-observer range and full-rate cap
│ ├── ObserverStreamingRegistry.cs # Registration and per-observer decisions
│ ├── ObserverStreamingPolicy.cs # Density-scaled range and budget policy
│ ├── ObserverStreamingEntry.cs # Per-object streaming state
│ ├── ObserverClassification.cs # The classification an object is budgeted and ranged under
│ ├── ClassifiedDistanceCondition.cs # FishNet observer condition: per-classification runtime range
│ └── ObserverBudgetCondition.cs # FishNet observer condition implementing the per-classification budget
└── Region/ # Region trigger system (server-authoritative; NOT part of the predicted character pipeline)
├── Region.cs # NetworkBehaviour with NetworkTrigger; OnRegionEnter/Stay/Exit Trigger lists
├── RegionGeometry.cs # Authored region shape
├── RegionMembership.cs # Which region owns a character when regions nest
└── FogSettings.cs # Per-region fog configuration data
Related Files
Shared/Core/Entity/Prediction/IPredictableController.cs # Interface all controllers implement
Shared/Core/Entity/Prediction/Ability/Cooldown/ICooldownController.cs # Cooldown controller interface
Shared/Core/Entity/Prediction/Ability/IAbilityController.cs # Ability controller interface
Inheritance Hierarchy
NetworkBehaviour
└── CharacterPredictionController # Drives the unified pipeline
IPredictableController # Implemented by all subsystem controllers
├── KCCPlayer (Order=80)
├── BuffController (Order=85)
├── CooldownController (Order=90)
├── EquipmentController (Order=93)
├── CharacterAttributeController (Order=95)
└── AbilityController (Order=100)
License
This project is subject to the FishMMO project license.