GoldSrc Networking, Part 3: The Server -- Lag Compensation, Client Movement, Speedhacking
How a GoldSrc server builds each client's view of the world: the snapshot ring, PVS culling, full vs delta packets, baselines, usercmd processing, and lag compensation. Part 3 of a four-part reverse-engineering series.
A CS 1.6 server has an entire game world with 32 players loaded in memory, and about 20 packets per second to broadcast all of this to clients. How does it transfer all of this state efficiently? And also how can it make the gameplay experience of 100, 200, 300-ping clients smooth by using lag compensation?
This part focuses more on what happens on the server and the application-level communication with client&server. We'll discuss entity packing, PVS, what is server-sided lag compensation, player movement, how does fps affect movement, and how this was so bad in older versions of the game but eventually got fixed later.
Here's a little TL;DR of the part 2, which covers everything below the game code:
Recap: In Part 2 we covered how bytes are encoded and delivered and how each layer in the networking stack works with the packet data. In order to understand the underlying mechanics such as delta compression which is used here, I recommend checking it out.
GoldSrc Networking series -- Part 3 of 4:
- Part 1 -- The High-Level Overview: history, the client-server model, and the five-layer stack.
- Part 2 -- Transmission: how bytes actually cross the wire -- UDP and
SPLITPACKET, the NetChannel's one-bit reliability, bit serialization, and the delta encoder. - 👉 (this article) Part 3 -- The Server: Lag Compensation, Client Movement, Speedhacking: entity snapshots, PVS culling, baselines, usercmd processing, and rewinding the world for hit registration.
- Part 4 -- The Client: Prediction & Interpolation: reconstructing snapshots, predicting movement, and interpolating other players.
This part is, again as the previous part, packed tightly with a lot of information, so following it completely might be hard. On the other hand, I believe that the information written here will serve as a technical reference for people wanting to study how each part of the server stack works.
Just a small note; the code snippets are based out of reverse-engineering of the game.
Let's jump in!
Introduction¶
Before we fully dive into the internals, I'd like to walk through some of the basic facts about the architecture of the server-side code in GoldSrc.
The server code is built around several source files:
sv_main.c: The biggest file in the engine, spanning 10,000 LOC, contains the main server logic. It has code that works with the snapshot ring buffer, calculating PVS, entity deltas/baselines, ping, and more.sv_user.c: This file works with usercmd parsing (movement data), and lag compensation.sv_phys.c: Contains world and object physics. This includes gravity, water levels, pushables, etc.
There are some other server files dealing with server logs, ip filtering, etc., which we'll not cover here.
The server logic is far heavier than the client-side logic or even client-side rendering. When running a server with 32 clients, the server is doing processing for every client separately. Every client holds movement state, history snapshots, even the netchan_t data discussed in the 2nd part.
Differences Between Quake1 & 2¶
Almost every concept or technology mentioned in this part is greatly based on QuakeWorld. The per-client snapshot history, the PVS and PAS culling, the delta-compressed entity packet, and even the delta-compressed usercmd stream with backup commands were implemented in QuakeWorld.
GoldSrc built on top of it, fixed bugs, and improved it for competitive gameplay. One of the additions are instanced baselines where many entities of the same classname share one baseline. GoldSrc also added lag-compensation, which Quake never implemented (even in newer releases).
Server to Client Communication¶
Before we dive into the internals I'd like to assess the mechanism of how server communicates with clients first.
Everything the server sends to a client goes over the NetChannel (see Part 2). The payload inside a packet is a stream of messages. Each message starts with a one-byte type and then its data, and the client reads the stream front to back, forwarding each message to its handler function based on that type byte. The built-in types are the svc_ (server-to-client) commands: svc_time, svc_clientdata, svc_packetentities, svc_pings, svc_sound, svc_print and so on.
A message is sent one of two ways. Reliable messages are resent by the NetChannel until the client acks them, which is used for data that mustn't be lost, like spawn baselines and user info. Unreliable datagrams are sent once with no retransmission, used for anything that gets regenerated every frame, mainly the entity snapshot where a stale position isn't worth resending.
The list of svc_ messages is protocol-fixed, but the game DLL can add its own messages on top, which is how mod HUDs like ammo, health and the kill feed get updated. These are called UserMessages. A custom message is announced to the client once and then sent by an assigned index, but it goes through the same stream as everything else.
The two messages that matter most for this part are svc_clientdata and svc_packetentities / svc_deltapacketentities. Together they carry the per-client world state we're about to build.
How Often the Server Sends: Update Rate and Choke¶
The server doesn't build an update every server frame. Each client has its own send interval, next_messageinterval, and the server builds that client's snapshot only once next_messagetime has passed. The engine's fallback is 0.05 seconds, the 20 packets per second from the opening paragraph.
The client asks for a different rate by putting cl_updaterate in its userinfo string. The server converts it to an interval and then clamps it into the window the operator allows:
cl->next_messageinterval = 1.0f / (float)i; // i is the client's cl_updaterate
SV_CheckUpdateRate(&cl->next_messageinterval);
SV_CheckUpdateRate bounds the interval by sv_maxupdaterate (default 30) and sv_minupdaterate (default 10), so with stock cvars a client gets somewhere between 10 and 30 updates per second no matter what it asks for. This interval is also the delay the client waits before its own next send, which is why it shows up again in the ping calculation below.
There is a second reason an update may not be built: the rate limit. Each channel has a bytes-per-second budget, and when a client's budget is exhausted the update for that frame is skipped instead of queued. The server counts those skips and tells the client about them with an svc_choke message. A skipped update like this is a choke. It leaves a hole in that client's snapshot history, so the term comes up again when we walk the ring back for lag compensation. The mechanism itself is covered in Part 2.
Client to Server Communication¶
The same way server talks to client, client also can talk to the server, of course. It uses the opposite of a server command: a client command. Also called clc_, the client implements many client-to-server messages such as clc_move, clc_voicedata, clc_delta, clc_cvarvalue, etc.
clc_move is amongst the most important, because it's the most frequently sent message (along clc_delta), almost each frame.
The Server Frame¶
This subsection discusses what happens in a server frame. The server frame is quite similar to a client frame but offers its own nuances.
Unlike the client frame, the server needs to deduce PVS - Potentially Visible Set for each client it runs simulation for. This is used as a base for the delta snapshot that is sent to clients. The PVS is computed once per client, from that client's view position, and then every entity in the world is tested against it. If an entity is outside of a client's PVS, it's not sent to that client as part of the delta update1.
After PVS is computed, each player's state is stored in a per-client ring. This ring contains N snapshots, which are then used in e.g. Lag Compensation.
Once the new state is produced, it is delta-encoded against an older reference state, and only that delta (an origin change, a health update) is sent to the client.
Then the movement code is run for each client. The clients send movement packets to the server and the server performs the moves, updates entity state.
Lastly, lag compensation is performed at the end of a frame for hit registration. More on that below.
The Snapshot Ring¶
The server holds a buffer of 64 elements that acts as a history of snapshots for each client. This number of elements is 64 when hosting a normal server, and in single-player, this value is 8 because packet loss is basically zero and there isn't a need for more history snapshots.
The buffer is circular, hence the name snapshot ring. The engine calls one entry a frame and its type is client_frame_t, but this article says snapshot for a ring entry and keeps frame for a simulation tick. They aren't the same thing: a snapshot is written only when that client is due an update.
The netchan sequence indexes used to address the ring are:
outgoing_sequence: The present client snapshot.incoming_acknowledged: The snapshot the client ack'd.delta_sequence: The snapshot the client asked the server to delta against.
These indexes are continuously used to access the snapshot data on the server side. delta_sequence and diffing against a baseline are covered later.
The data structure for one snapshot is client_frame_t and it looks like this:
typedef struct
{
double senttime; // realtime when this update was sent
float ping_time; // realtime - senttime when the client ack'd it; -1 until then
clientdata_t clientdata; // the player's own state (health, origin, ...)
weapon_data_t weapondata[MAX_CLIENT_WEAPONS]; // 64 weapon slots
packet_entities_t entities; // the entities visible to this client this frame
} client_frame_t;
The senttime is the server's timestamp, and clientdata is filled by the GameDLL in the UpdateClientData function and weapondata is filled by GetWeaponData GameDLL callback function. This data is then sent to the clients using svc_clientdata, and then the entity snapshot using svc_packetentities.
Calculation of ping_time¶
The ping_time is calculated using the last client's acknowledged message's timestamp minus the updaterate interval (e.g. 0.05s).
So this is basically the time it took for the update to get acknowledged by the client and send back to the server (S->C->S with ack) + the next_messageinterval the client use as intentional delay.
sequenceDiagram
autonumber
participant S as Server
participant C as Client
rect rgba(61, 90, 128, 0.18)
Note over S: Update current snapshot's senttime<br/> to current time
activate S
S->>C: Send to client #100
activate C
Note over C: waits next_messageinterval<br/>before its next send
C->>S: Send to server (acked)
deactivate C
Note over S: Calculate ping_time:<br/>ping_time = realtime − senttime − next_messageinterval
deactivate S
end
Visualization of packet RTT including next_messageinterval which the client waits before sending a packet.
Calculation of Scoreboard Ping & Packet Loss¶
Ping data about each player is sent separately and calculated by the server. Issued via the svc_pings message. The ping per player is calculated based on ping_time, averaged across several historical state records, if available.
The packet loss shown on the scoreboard is client-owned data. The client measures it from gaps in the server's update sequence and reports it as a byte inside each clc_move movement packet. The server reads that byte in SV_ParseMove and stores it in host_client->packet_loss; SV_EmitPings then echoes it back out to everyone via svc_pings (alongside the server-computed ping). The server does not compute its own loss figure from sequence numbers; it only relays what the client reports.
This is needed because the server cannot measure server-to-client loss on its own. The server only knows which packets it sent, not which ones the client received. The client is the only side that sees the missing sequence numbers, so it computes the loss and sends it to the server.
Per-Entity Hot Heap Allocation¶
Each client has a PVS of entities it can see during that frame. This list, calculated each frame, is also heap-allocated each frame, resulting in very hot heap allocations.
This is a tradeoff between memory and performance. QuakeWorld statically reserved its packet-entity array (64 entities per client). GoldSrc raised that cap to 256, so keeping the static approach would mean reserving 256 entity states per client per frame, which for the current entity_state_t (a snapshot for an entity in time containing viewangles, origin, model, and other data) would cost around 178 MB of RAM:
$$ M = N_{p} \cdot N_{f} \cdot 256 \cdot sizeof(entity_state_t) $$
Where $N_{p}$ is the player count, $N_{f}$ is the size of the snapshot ring, and 256 is the limit of packet-entities per client. Given $N_{p}=32$, $N_{f}=64$, $M$ would be roughly equal to:
$$ M = 32 \cdot 64 \cdot 256 \cdot 340 \approx 178 MB $$
And for an early 2000s Linux server, this is a lot.
Deciding What to Send: PVS Culling¶
PVS stands for Potentially Visible Set and it's the defining factor of what entities will be sent to each client. This set is recomputed each frame, and determines the entities that the client can potentially see in that frame. Along with this, PAS (Potentially Audible Set) is also computed -- for game sounds.
Each frame the server performs the following:
- Picks the current snapshot from the ring:
frame = &client->frames[outgoing_sequence & SV_UPDATE_MASK]. - Function exported by GameDLL is called to deduce the PVS and PAS:
pfnSetupVisibility. - The server loops over every active/alive edict that frame. For each, another GameDLL function is called:
pfnAddToFullPack. This function is another filter which ultimately decides whether the entity will be included in this client's snapshot.
The "Fat" PVS¶
The engine's own visibility helper is SV_FatPVS. It doesn't just look up the single BSP leaf the player's origin sits in, it descends the tree from that point and ORs together the precomputed leaf PVS of every leaf the point can be in:
dt = DotProduct(org, p->normal) - p->dist;
if (dt > 8.0f)
{
node = node->children[0]; // clearly in front of the plane
}
else if (dt >= -8.0f) // within 8 units of it:
{
SV_AddToFatPVS(org, node->children[0]); // recurse into the front side
node = node->children[1]; // and keep walking the back side
}
else
{
node = node->children[1]; // clearly behind
}
The ±8 unit band around each splitting plane is what makes the set "fat". If the view origin lands inside it, both sides get included. Without the slop, a player standing on a leaf boundary, or just view-bobbing across one while walking, would have entities flicker in and out as the origin crossed the plane. SV_FatPAS does the same walk for the audible set.
The 256-Entity Cliff¶
Whatever survives pfnAddToFullPack accumulates into a list hard-capped at MAX_PACKET_ENTITIES, which is 256. When it fills up, the loop stops:
// already added too much
if (curPack->num_entities >= MAX_PACKET_ENTITIES)
{
Con_DPrintf("Too many entities in visible packet list.\n");
break;
}
Everything past the cap is silently dropped for that client, for that frame, and the Con_DPrintf shows up only with developer output on. There is no priority scheme at this layer: the loop walks edicts in index order, so the entities that survive are the ones spawned earliest. A busy map with 32 players, a pile of dropped weapons and a few dozen grenades and gibs can push a crowded corner past 256 visible edicts, and the entities at the end of the list are dropped.
Full Packets vs Deltas¶
In order to transfer entity data GoldSrc uses entity state. This entity state is delta-encoded. Delta encoding was introduced in Part 2.
Four terms are commonly used in the code:
- delta update: A difference between two states.
- full update: A delta update diffed against a zeroed state, so every field is sent and nothing is diffed away.
- baseline: An entity's starting state, fully occupied. Every field is set, so it works as a "from" side when there's no previous state to diff against.
- instanced baseline: A baseline shared by all entities of the same classname, so many identical entities can reference one baseline instead of each carrying its own.
If delta-compressing is enabled on client, which it is by default (cl_nodelta 0/1), it requests the server to send entity delta updates instead of full updates to not flood the server2.
A reference snapshot is picked by the client for the server to delta from. This data is fully client-controlled. It is usually the last server outgoing sequence number that the client has received. The client stores this value in cl.validsequence.
In CL_Move function3 the client issues a clc_delta command with the cl.validsequence value for the server to send the delta packet from. If the client doesn't request a clc_delta or cl.validsequence is 0, server sends a fullpacket by default:
// BTW: pSenderClient is unused in 8684. Actually not sure when it was used.
void SV_ParseDelta(client_t* pSenderClient)
{
// host_client is the client_t structure; a "client" from servers perspective.
host_client->delta_sequence = MSG_ReadByte();
}
Then on the server in SV_CreatePacketEntities:
// This is the frame that we are going to delta update from
fromframe = &client->frames[client->delta_sequence & SV_UPDATE_MASK];
from = &fromframe->entities;
oldmax = from->num_entities;
MSG_WriteByte(msg, svc_deltapacketentities); // This is a delta update
MSG_WriteShort(msg, to->num_entities);
MSG_WriteByte(msg, client->delta_sequence);
And the client parses them in CL_ParsePacketEntities. Simple, right?
Packet Entities Header¶
Each packet entity update that client receives each frame contains a bit-packet header. This is among the most fragile places where the protocol uses bit-packing. One bit off and the entire upcoming buffer is offset. There's a complex logic that can cause an offset like this, and while reversing this code, I can remember this being a result of a lot of headaches 😄.
The header is written by SV_WriteDeltaHeader. It tells the client which entity the following delta body belongs to, and how to decode that body, using as few bits as possible. The function implements some clever optimization tricks, so let's cover them.
The entity number is sent as a difference, not as an absolute value. Entity numbers inside a snapshot are sorted ascending, and most of them are consecutive: 1, 2, 3, 4 and so on. So instead of writing the full 11-bit entity index every time, the header writes delta = num - previous_num, where previous_num is the number of the last entity written:
delta = num - *numbase;
if (full)
{
// full update: is this simply the next consecutive entity?
MSG_WriteBits(delta == 1 ? 1 : 0, 1);
}
else
{
// delta update: the first bit is the remove flag instead
MSG_WriteBits(remove ? 1 : 0, 1);
}
In a full update the most common case is delta == 1, meaning the very next entity in sequence. This covers up one bit, instead of sending the actual entity index, which would take at best 6 bits and at worst 11 bits. This is a ~7..12-bit save per entity, in best case.
If the delta != 1 however, then the actual value needs to be sent. 6 bits are used for delta values up to 63 or, for a large index or backward jump, 11 bits are spent.
In a delta update that first bit is instead used as a remove flag. A delta update describes what changed since the reference snapshot the client acknowledged. The remove flag indicates an entity that was deleted on the server. Remove is only part of a delta update.
Additionally, a full update has no reference snapshot, it is built from an empty list. The client rebuilds its entire entity list from scratch out of that single packet, so anything listed exists and anything not listed does not exist.
Packet Entity Parsing¶
Once the entity is identified by the index, a few more single-bit flags describe the data that follows:
custom: whether this is a custom entity (explained next). This one bit picks which delta table the client decodes the body with.- new instanced baseline: present only if the map has instanced baselines. If set, a 6-bit index follows.
- baseline offset: full updates only. If set, a 6-bit offset follows, pointing at an earlier entity in the same packet to diff against instead of at a baseline. The server picks whichever earlier entity of the same type produces the smallest delta. A long row of identical props is then nearly free.
Custom entities: Every entity has an entityType field, and the engine has a delta table for each type. One for players, one for regular entities, and one for custom entities such as beams. The custom bit in the header selects the custom-entity table; players are separated from regular entities by their entity number, which is always at or below maxclients. Each table describes the fields the client uses to decode the body. See Part 2 for how delta compression and delta tables work.
The actual data is then read out of the delta-compressed data and stored in an entity state.
Three-Way Merge¶
Little bit more information about how the entity index, once decoded, is treated. This logic is complicated, so let's go through it step by step.
The problem we're trying to solve is to deduce 3 cases. Whether an entity is already existing and only needs delta update (1), is deleted (2), or is a new entity (3). The code works with two snapshots:
- from: the snapshot the client acknowledged, the reference we delta against. For a full update this list is empty.
- to: the snapshot we are building right now, the state the client should end up holding.
Both snapshots contain entity lists sorted ascending by entity index, therefore the scan over indices can be linear. The server walks both lists and decides what to send (one of the three cases).
from is the snapshot the client wants to delta from, and to is the final snapshot. oldnum and newnum are entity index accumulators (cursors). When one list runs out, its index is set to a sentinel value of 9999 so the other list can finish cleanly to the end. Then the three cases are deduced by these 3 conditions:
newindex = (newnum >= newmax) ? 9999 : to->entities[newnum].number;
oldindex = (oldnum >= oldmax) ? 9999 : from->entities[oldnum].number;
if (newindex == oldindex) { /* 1. same entity -> delta */ }
if (newindex > oldindex) { /* 2. entity gone -> remove header */ }
if (newindex < oldindex) { /* 3. new entity -> from baseline */ }
In each case, the payload that follows is different, and the client has to mirror this same logic in order to read correct values; this is what makes this implementation so fragile. One entity index off and everything is corrupt.
newindex == oldindex, the entity is in both frames. It existed last frame and still exists this frame. The server writes its header and then a delta of the new state against the old state. Both cursors advance.newindex > oldindex, the entity is gone. It was in the reference snapshot but not in the new one, because it left the PVS, died, or was removed. The server writes only a header with the remove flag set, no body follows. Only the old cursor advances.newindex < oldindex, a new entity. It's in the new snapshot but wasn't in the reference, so there is no previous state to diff against. It's written as a delta from its baseline instead (see Baselines). Only the new cursor advances.
flowchart TD
A["Start: oldnum = 0, newnum = 0"] --> B{"Both lists<br/>exhausted?"}
B -- yes --> Z["Write 16-bit zero<br/>terminator — done"]
B -- no --> C["Read newindex + oldindex<br/>(9999 if that list is exhausted)"]
C --> D{"Compare<br/>newindex vs oldindex"}
D -- "same number" --> E["1. Delta new state<br/>against old;<br/>advance BOTH"]
D -- "new > old" --> F["2. Remove header; only<br/>advance OLD"]
D -- "new < old" --> G["3. New from baseline;<br/>advance NEW"]
E --> H(( ))
F --> H
G --> H
H -.-> B
Flowchart of the core packet-entities loop on the server side. Payload optimization is implemented to lower the bandwidth. Not much scalable though.
The loop keeps going until both cursors are exhausted, then the list is closed with a 16-bit zero. Entity number 0 is always worldspawn and never appears in a packet entity list, so a 0 index is an unambiguous "end of entities" marker for the client.
This structure is also what separates the two message types. A full update has no from list, so cases 1 and 2 can never happen; every entity takes path 3 and is written from a baseline. A delta update covers all 3 cases. Delta updates to an entity are the most common updates; following new entities and removal of existing ones, which are rare in comparison.
Baselines¶
Baseline is an entity's starting state. The baseline is prepared by the GameDLL at startup for each entity in SV_CreateBaseline. The GameDLL's pfnCreateBaseline function is called on all edicts and saved into sv.baselines[i].
Consequently, this information is also sent to the client, so that it knows how to work with baselines as well. This happens via the svc_spawnbaseline server message and the payload is constructed in the same function.
Instanced Baselines¶
The idea about baselines is that many identical entities don't need each their own per-edict baseline. Instead they can all reference one shared baseline for that classname. Upon creating packet entities, the SV_CreatePacketEntities function prefers instanced baselines (if sv_instancedbaseline cvar is on) over regular baselines.
Reading Player Input: usercmds¶
The world state is held by the server. The server physically moves all entities. The clients only send their movement inputs (WASD+aim). Each such movement input is sent via a single usercmd_t structure, which contains buttons, viewangles, and more.
CL_Move¶
The client can send at most one movement packet per frame (i.e. one clc_move / frame). The server has an anti-flood check for this, added later to prevent cheating.
The movement is sent in the CL_Move function via clc_move. Depending on the value of cl_cmdrate (if non-zero), the movement packet is sent or not. The movement packet contains two integers:
numbackup: Number of movement packets to be resent during this send.newcmds: New commands. These contain our newly generated movement. For example a key we've pressed just this last frame.
The backup commands exist because of packet loss. The movement data is sent through an unreliable channel. And therefore, packet loss is expected. Even more so in the 90s, nowadays it's little bit less relevant. Therefore, if a packet would get lost, the next packet would still contain the N amount of backup packets from previous frames.
In order to completely lose a movement packet, the following would need to be true:
- Either we have
cl_cmdbackupset to 0. - Or more packets have been lost in a row than the value of
cl_cmdbackup.
The following snippet sends the numcmds user commands to the server. newcmds is usually 1, one new command generated this frame, but it can be higher when the framerate exceeds cl_cmdrate: movement packets are then not sent every frame, while user commands keep being generated every frame and accumulate in between. cl_cmdrate is the command-packet rate in packets per second. So at high fps a single packet can carry more than one usercmd.
usercmd_t cmdbaseline; // baseline to compare against
Q_memset(&cmdbaseline, NULL, sizeof(usercmd_t));
int numcmds = newcmds + numbackup - 1;
from = &cmdbaseline;
for (i = numcmds; i >= 0; i--)
{
// outgoing_sequence is the current (latest) frame
// CL_UPDATE_MASK loops the counter around so that it doesn't overflow
to = &cl.commands[(cls.netchan.outgoing_sequence - i) & CL_UPDATE_MASK].cmd;
MSG_WriteUsercmd(&buf, to, from);
from = to;
}
How Many Commands Are Sent¶
newcmds isn't written to the message raw. Just before it's transmitted, it gets clamped and the clamp depends on the server's build number:
// How many real commands have queued up
newcmds = cls.netchan.outgoing_sequence - cls.lastoutgoingcommand;
newcmds = cls.build_num < 5971 ? V_min(newcmds, CMD_MAXBACKUP_OLD)
: V_min(newcmds, (CMD_MAXBACKUP - 2) - numbackup);
The reason for the cap is on the server side. SV_ParseMove reads numbackup and numcmds straight off the packet, adds them into a total count totalcmds, and decodes that many commands into a fixed usercmd_t cmds[] array (64 entries). If totalcmds reaches CMD_MAXBACKUP - 1, the client gets kicked out with a CMD_MAXBACKUP hit error message. So in order to prevent this from happening, the client clamps the value before transmitting. The number is clamped to CMD_MAXBACKUP - 2 (62 slots). Therefore, in the worst case, totalcmds will be 62.
Note that this cap silently ignores user input. The code iterates from the oldest command to the newest, because the server works from the oldest packet to the newest.
And why does this build-specific check need to exist? cls.build_num is the server's build number, sent to the client in the connect acknowledgment. Servers older than build 5971 -- roughly the end of February 2013 -- predate the larger command buffer, so a modern client talking to one throttles itself to a flat CMD_MAXBACKUP_OLD of 16 and never announces more commands than the old server is prepared to hold.
Movement Command Duration usercmd_t::msec¶
msec is the command's duration in milliseconds, and it's used to tell the server "this command took this long". It's important for the server to know this, since it'll be running the world physics with this frame time.
Imagine you send three consecutive commands. Client sends one command per frame. The msec field is client's frametime. The server then looks at these three commands, and replays them in order. That means running the server-sided movement logic on each command, using this client's timeframe.
More commands the client sends, the more movement logic executions will the client get. This is also the artefact of why is it that with higher fps the client can air-accelerate more. It's simply because more commands are sent, hence more are replayed on the server.
A command longer than 50 ms (so anything from a client below 20 fps) is not run as it arrived. SV_RunCmd halves its msec and calls itself twice:
if (cmd.msec > 50)
{
// Split the time in half so we can actually work with this. Do this
// until we can run the usercmd.
cmd.msec = (byte)(ucmd->msec / 2.0);
SV_RunCmd(&cmd, random_seed);
cmd.msec = (byte)(ucmd->msec / 2.0);
cmd.impulse = 0; // don't fire the weapon twice
SV_RunCmd(&cmd, random_seed);
return;
}
Because it recurses, the halving repeats until every sub-command is under the threshold: a 200 ms command from a 5 fps client is split into four 50 ms steps rather than two 100 ms ones. This is done for simulation stability, and the split preserves the total time. The second half clears impulse so that actions like weapon fire is triggered only once.
Note the cast: the halves are (byte)(msec / 2.0), so an odd duration loses a millisecond in the split. It's the same truncation as the one below, just in the other direction and far rarer.
flowchart LR
A["Client: 'here are 3 inputs,<br/>16 + 16 + 18 ms of my time'"] --> B["Server rewinds<br/>50 ms into the past"]
subgraph replay["Replay, in order"]
direction LR
C["input 1<br/>16 ms"] --> D["input 2<br/>16 ms"] --> E["input 3<br/>18 ms"]
end
B --> C
E --> F["Player is caught up<br/>with the rest of the world"]
The server rewinds to the time of the starting command, then replays each input for exactly as long as the client said it lasted.
The Frametime Remainder¶
Since msec is an integer, at 128 fps the real frametime is 7:
$$ msec = \lfloor \frac{1}{128} \cdot 1000 \rfloor = 7 $$
Having msec as a byte, the value gets truncated and the remainder is lost. In this case, 0.81 ms per frame is ignored. At 128 commands per real second that accumulates: the server counts only 896 ms of our simulation time while a full second passed, about 104 ms less than it really did. This results in the movement being generally 'slower', because the server does:
$$ distance = velocity \times dt $$
where $dt$ is the msec value, but rounded.
As you can see on the following table, the canonical fps values for "smooth" gameplay are the ones with no fractional millisecond left over once converted to a frame time:
| fps | frame time (ms) | sent as msec |
lost per frame |
|---|---|---|---|
| 60 | 16.667 | 16 | 0.667 ms |
| 100 | 10.0 | 10 | 0 |
| 125 | 8.0 | 8 | 0 |
| 128 | 7.8125 | 7 | 0.8125 ms |
| 144 | 6.944 | 6 | 0.944 ms |
| 250 | 4.0 | 4 | 0 |
| 501 | 1.996 | 1 | 0.996 ms |
This creates a "saw-like" pattern over the fps values and the time you lose with each fps value. Over 500 fps this recurring pattern stops, because the truncated msec never gets above 1:
$$ msec = \left\lfloor \frac{1000}{fps} \right\rfloor = \left\lfloor \frac{1000}{501} \right\rfloor = \lfloor 1.996 \rfloor = 1\ ms $$
The error is then:
$$ error = (\frac{1}{501} \cdot 1000)-1 = 0.996 ms $$
Given that the client sends $fps$ amount of movement packets to the server, this error per 1 real second accumulates to $0.996*501$:
$$ error_{1s}=0.996*501=498.996 ms $$
This error (blue) is plotted against fps values:

Movement time lost to the msec truncation, plotted across framerates from 20 to 1000.
This artefact has been "fixed" in newer versions of the game. This is done by having an accumulator that accumulates the error on the client, and if it exceeds 1.0, simply 1 is added to msec value sent, to not lose the extra millisecond. This ultimately gets rid of the msec loss, since the loss is at max 1ms, rather than e.g. 500ms at worst.
static double frametime_remainder = 0;
double dmsec = host_frametime * 1000.0;
int msec = (int)dmsec; // take the base part without a fraction.
frametime_remainder += dmsec - msec; // increment by the fraction
if (frametime_remainder > 1.0)
{
frametime_remainder--; // reset
msec++; // INCREMENT the msec artificially, to "fix" the rounding issue
}
msec = V_min(msec, 255);
pcmd->cmd.msec = msec;
You might be asking... but why is msec a byte, instead of, let's say, a float? That would definitely fix the problem with the rounding, right? Yes, however, the cost is the network bandwidth. And this has to do with the delta compression. Basically, a float would take more space than a byte. Is it worth it? IMO, absolutely, then this "fixing" mechanism wouldn't be needed at all.
See the following for more information:
- https://github.com/ValveSoftware/halflife/issues/1940#issuecomment-13052903
- https://www.fortress-forever.com/fpsreport/
Where is the Error Noticeable?¶
If you've ever played the 4554 (or older) versions of the game, you might remember that with high fps values, while jumping and landing on ground, and then accelerating, it was painfully slow. Compared to e.g. 100 fps, which was much faster. The higher fps values compared to that were like slowmotion.
Let's now look at a practical example by examining a solid artefact in the player movement code introduced by this remainder error.
The msec value is ultimately used to run playermove code. It also is in the player acceleration formula. Every command grants the player an amount of velocity proportional to it:
$$ \Delta v = accel \cdot dt \cdot wishspeed $$
So a smaller value of $dt$ makes the resulting speed smaller. This is further noticeable when the server thinks you're running at different framerate than you are, because of the loss of remainder in the msec value that accumulates over frames.
So a truncated value affects two things. The same $dt$ that grants the velocity is also the one the server integrates your position with -- origin += velocity * dt -- so you gain less velocity per command, and you also move less with the velocity you have. At 600 fps a frame takes 1.667 ms, but due to the error, the server thinks it was only 1 ms:
$$ \Delta v_{real} = 5 \cdot 0.001667 \cdot 250 = 2.08 $$
$$ \Delta v_{sent} = 5 \cdot 0.001 \cdot 250 = 1.25 $$
This error is pretty big.
This can be further visualized by transcribing the friction and acceleration out of pm_shared.c implementation with the CS 1.6 defaults -- acceleration 5, friction 4, stopspeed 75 -- and a 250 u/s maxspeed. The horizontal axis is real time, since a frame always consumes the same slice of it no matter what the client claims:

Ground acceleration from a standstill, with and without the msec truncation, at 128, 144, 300 and 600 fps.
A player with fps on an exact divisor of 1000 reaches the cap in a little over four tenths of a second. At 128 fps the truncating client needs closer to half a second, and at 600 fps it needs more than two thirds of one. At the halfway mark it is still well short of the cap, when everybody else has been running at full speed for a tenth of a second already.
Notice that the plotted speed is identical in every panel. The acceleration step is capped by however much speed is still missing, so the velocity vector settles on the target running speed regardless of the frametime.
That ceiling is only true inside the simulation though. The server integrates your position with the same claimed time it accelerated you with, so at 600 fps you only spend 0.6 of a second moving per real second: the velocity variable is 250 u/s while the real speed is 150 u/s. The truncation affects both the acceleration and the cap. In the plots there is only the acceleration, because the plotted value is the simulation velocity. The acceleration is still the part you notice in a duel, when you peek a corner or strafe out of cover, because in those moments you are almost never at steady state.
The cleanest way to think about the whole artefact is time dilation. If a framerate throws away a fraction of every second, everything the player does takes proportionally longer in the real world:
$$ t_{real} = \frac{t_{sim}}{1 - error} $$
At 600 fps two fifths of every second is discarded, so that four-tenths-of-a-second sprint becomes:
$$ t_{real} = \frac{0.41}{1 - 0.4} \approx 0.68 $$
A 600 fps client without the fix sends exactly what a correct 1000 fps client would send -- the same single millisecond per command -- it just takes over one and a half times as long in real time to get there.
Munging and the Move CRC¶
The CL_Move path implements its own integrity layer on top of everything the NetChannel already does. Because of a legacy.
Each movement packet (clc_move) is munged with the outgoing_sequence (sequence accumulator of current datagram the client is about to send). The server then picks the clc_move message up, demunges it. Along the movement data, the clc_move also contains a CRC checksum of the data itself.
After unmunging, the server CRCs the data with the same algorithm the client used and compares it against the received byte. On a mismatch the message is flagged as bad and the rest of it is thrown away.
It's worth mentioning why is that important, because it might seem like an anti-cheat measure but the reality is different. The munge key is a sequence number and the CRC is computed by ordinary client code, so between them they cover integrity on the wire: a corrupted datagram, a replayed one, or a packet hand-crafted by an attacker. What they don't cover at all is authenticity of the client. A cheat running inside the client produces perfectly valid CRCs, because it's the legitimate client code that computes them, over whatever values the cheat put in the struct first. Everything in the speedhacking section below is not stopped by this layer.
The munge is also redundant here. The whole datagram gets munged on the NetChannel layer anyway, so the movement block is munged twice. The redundancy came about by accident. Comparing engine builds shows the clc_move munge came first (already present in build 1357, alongside the older move CRC), and the whole-packet NetChannel munge was only added later (it's absent at 1357 and present by 1600), so the outer layer munges bytes the inner layer had already munged.
Over to the Server Side¶
The serverside per-client function for processing movement clc_move packets is SV_ParseMove. It reads the message, de-munges it, calculates the CRC checksum, reads the numbackup and numcmds values, and parses the delta-stored usercmd_t messages. There are bounds checks all around in this function so the client-owned data should not be easily exploitable. I'm sure this function has been seen by many people trying to either hack the game and prevent hackers from exploiting it, so this is a very battle-tested code in my opinion.
Replaying Dropped Commands¶
The backup commands are only one part of the loss tolerance. The other part is what the server does once it notices a gap.
The NetChannel hands SV_ParseMove a net_drop count: how many packets went missing immediately before this one. The server uses it to fill the gap so that movement never stalls:
net_drop -= (numcmds - 1); // commands in THIS packet already cover part of the gap
// If we haven't dropped too many packets, then run some commands
if (net_drop < CMDDROP_LIMIT) // CMDDROP_LIMIT = 24
{
// Rerun the last valid command a bunch of times.
while (net_drop > numbackup) // gap wider than the backup buffer
{
SV_RunCmd(&host_client->lastcmd, NULL);
net_drop--;
}
// Now run the "history" commands if we still have dropped packets
while (net_drop > 0) // gap the backup buffer does cover
{
cmdnum = net_drop + numcmds - 1;
SV_RunCmd(&cmds[cmdnum], incoming_sequence - cmdnum);
net_drop--;
}
}
Two different repairs, applied in that order. For the commands that are gone for good there is no real input left, so the server repeats lastcmd, the last command it successfully received. You keep walking in whatever direction you were last known to be walking. It's a guess, but better than standing still. For the part the backup buffer does cover, the actual commands are replayed, oldest first.
Past CMDDROP_LIMIT (24 packets, a few hundred milliseconds of unbroken loss at typical cmdrates) the server stops trying to reconstruct the gap and just runs the fresh commands. Seen from the outside, that is the classic "player freezes, then teleports forward" after a lag spike.
Rebuilding the Clock¶
Because the number of commands in a batch varies (dropped + backup + new), the server can't advance its per-client clock by one frame per packet. SV_EstablishTimeBase sums the msec of every command that is about to run and anchors backwards from the present:
cl->svtimebase = host_frametime + sv.time - runcmd_time;
Every SV_RunCmd then pushes svtimebase forward by its own msec. So after the whole batch has executed, the player lands on exactly the current server time, whether this packet carried one command or twenty. The time base is reconstructed from the inputs the client sent. This is the same design decision that makes speedhacking possible, covered at the end of this article.
Furthermore, the rehlds project aims to recreate and further battletest the serverside of GoldSrc, and has many bugs, buffer overflows and other exploits fixed. It is a community-run reversal of the serverside of the engine, and has been around for quite some time. I'd say around 80-90% servers use it nowadays4.
You can see whether a server uses reHLDS by checking the console if it sends a relatively small build number:

The reHLDS build numbers often are small, because the day counter started in around 2014, unlike in GoldSrc, which started in October 1996.
Lag Compensation¶
Lag compensation is, as the name suggests, a mechanism to compensate for your high ping. You can imagine it like this: when a player has a higher ping (say 150 ms), everything they see is 150 ms behind reality. So if they shoot at a "ghost" that isn't there any more, because the target has already moved during those 150 ms, the hit won't register. This is the direct side effect of higher latency.
In Quake, there is no lag compensation. With a higher ping you have to literally preaim to hit an enemy. Valve stepped in and introduced a mechanism where the server accounts for your ping and for when you started shooting. It then looks up a world state snapshot from exactly that point in the past, checks whether the enemy was where your bullet landed, and either registers or dismisses the hit.
Without lag compensation you need to aim N ms (your latency) ahead in order to land the shot.
This side effect of ping also creates what's known as peekers advantage. It is a situation where one player is holding a position and the other is peeking him. Because of latency, the peeker sees the holder first, shoots at him first, and gets the hit first.
How does the server determine what slot from the past to pick? It does so by using several variables which we'll talk about in next section.
Calculation of the Right Moment¶
Lag compensation occurs in SV_SetupMove called per client. The target time for the history snapshot is computed out of several variables:
targettime = realtime - clientLatency - cl_interptime + sv_unlagpush
Where:
realtime: This is the time of the server clock. The "real time" as server sees it.clientLatency: This is the server-measured latency of the client capped tosv_maxunlagcvar value (hard limit of 1500 ms). It comes fromSV_CalcClientTime, which reads theping_timesamples out of this client's own snapshot ring and averages at mostsv_unlagsamplesof them. That cvar defaults to 1 and is clamped to 16, so out of the box there is no averaging at all, just the newest sample. The same function also has a stability check: if the spread across the newest samples exceeds 200 ms, it returns 0, so a jittery connection gets no rewind.cl_interptime: This is the clientside interpolation amount5.sv_unlagpush: A constant offset added to the target time, defaulting to0.0. Raising it pushes the rewind target towards the present (less rewind), lowering it pushes it further into the past. It's a server operator's cvar for tuning hit registration. The result is clamped so thattargettimenever exceedsrealtime.
Using this formula, the server can estimate at which time did this movement event really take place from the position of the client. Based on this timestamp, the server then goes and checks which snapshot to choose.
Walking the Ring Back¶
There is no dedicated position history for lag compensation. GoldSrc re-reads the same per-client snapshot ring that delta compression already needed. That makes lag comp the third consumer of that buffer. Source later split this out into a CLagCompensationManager in the game DLL with its own ~1 second position store.
It walks the shooter's own ring, so what gets reproduced is what that one client received, including their update rate and any choke gaps.
The walk goes backwards from the newest slot until it finds a snapshot older than targettime:
for (i = 0; i < SV_UPDATE_BACKUP; i++)
{
nextFrame = &host_client->frames[(outgoing_sequence - i - 1) & SV_UPDATE_MASK];
for (each player entity_state_t in nextFrame->entities)
// screen the player (see below) and remember its origin
frame = nextFrame;
if (targettime > nextFrame->senttime)
break; // we've hit our target time
}
// paranoid check: 1 second old diff is too much.
if (i >= SV_UPDATE_BACKUP || targettime - nextFrame->senttime > 1.0)
{
nofind = TRUE;
return; // nothing gets rewound at all
}
That leaves targettime bracketed between two stored snapshots, and each player's origin is then linearly interpolated between them:
$$ frac = \frac{targettime - t_{older}}{t_{newer} - t_{older}}, \qquad origin = org_{older} + frac \cdot (org_{newer} - org_{older}) $$
with frac clamped to $[0, 1]$. If a player has no entry in the newer of the two snapshots, because they were outside the shooter's PVS at that moment, there is nothing to interpolate towards and the older sample is used as-is.
Not everyone is eligible. During the walk, a player is marked deadflag and left exactly where they are if any of these hold:
health <= 0, so they were dead in that frame,EF_NOINTERPis set, an explicit "don't interpolate me" flag,- or their origin jumped by more than
ENTITY_TELEPORT_DELTA(128 units) between two consecutive snapshots.
Interpolating across a teleport or a respawn would place the target somewhere they physically never were. That is wrong and, as the engine's own comment notes, abusable. This screening runs on every consecutive pair the walk touches, not just on the bracketing pair. A player who teleported anywhere inside the walked window stays disqualified even if the two snapshots used for the interpolation look clean.
It Edits the Real World¶
This is the part that surprised me most while reversing it. There is no shadow copy and no lag-comp-aware trace. The rewind writes the interpolated origin directly into the target's live edict and re-links it. For the duration of that one usercmd, the other player is standing in the past, as far as any ordinary trace is concerned.
Which means the two collision paths treat the rewind in opposite ways:
- Hit-scan goes through
UTIL_TraceLineintoSV_Move, which reads the edict directly. It sees the rewound position for free, without knowing lag compensation exists. This is what CS'sFireBulletsuses. - The shooter's own movement collision explicitly undoes it. When
SV_CopyEdictToPhysentbuilds the physent list that gets handed topm_shared, it overwrites the origin of every player edict with the un-rewound one:
if (e < 1 || e > svs.maxclients)
pe->player = 0;
else
SV_GetTrueOrigin(e - 1, pe->origin); // hand pmove the REAL position
So the rule is: your bullet can hit someone who isn't really there, but you can never body-block a phantom while walking.
Afterwards SV_RestoreMove puts everyone back, but only conditionally:
if (VectorCompare(pos->initial_correction_org, cl->edict->v.origin))
{
VectorCopy(pos->oldorg, cl->edict->v.origin);
SV_LinkEdict(cl->edict, FALSE);
}
It restores the true position only if the edict still sits exactly where the rewind put it. If game code moved that player during the command, via a trigger, a push, or an explosion, that move is kept and the restore is skipped. It's a rare edge case, and it's left unhandled.
What It Bounds, and What It Costs¶
There is a hard limit on how far back a client can be rewound. "The server trusts the client" gets repeated a lot about this system and only half of it is true here. The ceiling is:
$$ rewind_{max} = \min(1.5\ s,\ sv_maxunlag) + 100\ ms $$
With stock cvars that is 600 ms, well below the 1.5 second hard cap. And of those two terms, only the 100 ms half is client-declared. The latency half is measured by the server from its own ping_time samples, and a jittery connection gets zero. So the surface for a backtrack-style cheat is much narrower than "the client controls the rewind window" would imply.
The cost is elsewhere. One rewind cycle is one usercmd, not one packet, and SV_SetupMove / SV_RestoreMove bracket every single SV_RunCmd. A packet that bundles fresh, backup and drop-replayed commands therefore pays for setup and restore dozens of times over, and the recursive split of an oversized command means one input sample can pay it twice against the same targettime. On a 32-slot server every one of those cycles walks the ring and touches up to 31 other players.
Speedhacking¶
Everything that is based on time such as movement or weapon firing is based out on usecmd_t's msec, the command duration we covered earlier. The problem with GoldSrc is that the server doesn't measure how long did client's frame actually take.
The client-controlled msec field becomes an attack vector the client can spoof and play with. That's the entire attack surface for speedhacking. There's no exploit here, no memory corruption, only spoofed data.
The Two Ways to Speedhack¶
First way is to lie about the frame time. By modifying usercmd_t with a bigger msec field value, the server will essentially think that more time has passed, and therefore it will move you further when applying movement physics6.
frametime = (float)(ucmd->msec * 0.001);
host_client->svtimebase = frametime + host_client->svtimebase;
host_client->cmdtime = ucmd->msec / 1000.0 + host_client->cmdtime;
On the serverside, there's a check that is applied once per second, in SV_CheckCmdTimes. This function is the speedhack check. It checks for how long the physical time has actually passed vs what the client is reporting. So, let's say that the client is sending bigger msec than should be. The server can then reckon -- hey, there is something wrong, because the client is simulating ahead of time -- probably speedhacking -- and punishes the client.
The client punishment is that the server won't execute movement commands for this client for clockwindow seconds (a cvar, 0.5s default). This will cause rubberbanding on the client and basically will restrict its movement.
The cvar's full purpose was uncovered by Valve itself by an email to hlds users, see this link. This is the definition of the cvar:
// It's designed to combat the speedhacks being used in-game.
cvar_t clockwindow = { "clockwindow", "0.5" };
It only contains the problem, it doesn't block it. The value is a tradeoff: the same tolerance that lets a speedhacker burn half a second of budget is the tolerance a real modem client needs, so tightening it trades cheaters for false positives.
However this also buys space for the client to essentially speedhack because it has a 0.5s window where it can fit the extra time before being rate-limited by SV_CheckCmdTimes. The check is also ran per second, so if the client sends packets with crazy msec values, the server will still execute these movement packets, making the client travel enormous distance, regardless of this rubberbanding "fix".
Historical fact: This was almost certainly a response from Valve to people cheating. This anti-speedhacking measure was added somewhere after build 1460 (somewhere late 2000), and before it didn't exist. This is also the time when Valve seemed to be fighting cheaters the most. In build 1460 the function SV_CheckCmdTimes doesn't exist at all.
The second way, the more adopted amongst cheats, is to flood the server with more movement packets. The server has a specific check for preventing multiple movement packets per datagram. Therefore client's only bet is to send more packets.
This works because the client is essentially flooding the server artificially. The key point there is that the msec field is not changing with the higher rate of packets, which is the main point why this is working as a speedhack. Again, similar situation as with modifying msec, just an inverse problem. More packets with "higher" msec = more ground covered.
This also gets covered by the server-sided SV_CheckCmdTimes remedy.
Conclusion¶
And that's the server side. One thing you've probably noticed is that a lot of this keeps coming back to the same 64-slot buffer. The snapshot ring is there because delta compression needs to own the state it delta'd against. But then the scoreboard ping is calculated out of it as well, and lag compensation walks it backwards to rewind the world. So three things that look completely unrelated from outside are all reading the same array. Source later gave lag comp its own position history inside the game DLL, GoldSrc just reused what it already had.
The thing I keep coming back to is how much of the timing is owned by the client. How long a command took is whatever the client says it took, and this one single byte is basically the whole speedhacking surface. The rewind distance is not like this at all. The server measures it from its own ping samples, caps it by sv_maxunlag, and if your connection is jittery you get nothing. "The server trusts the client" gets said a lot about this system, and it's only half true, but the half that is true happens to be exactly the half that matters for cheating.
The rest is mostly bandwidth. msec is a byte and not a float, which saves a few bits per command and cost the game years of weird movement on high fps. The entity header saves 7 to 12 bits per entity and buys a format where one bit off corrupts everything after it. The packet entity list is capped at 256 because reserving the worst case would be 178 MB. For a 2001 server these were all reasonable calls, and none of it is really defensive either: the rewind writes straight into the live edict, the entity cap just breaks out of the loop and prints into a console that nobody has open. And it all still works somehow, most of this is running on public servers right now.
Next¶
Thanks for reading the 3rd part! Again a lot of information covered, I hope it was helpful. Next up is Part 4: The Client -- Prediction & Interpolation, where we cross to the other side and see what the client does with all of this to make a 90s-latency game feel instant.
-
I'm referring to a delta update here however, this is true for a full update as well, PVS culling happens for both types of updates. What is delta update and full update; more on that later. ↩
-
A few years prior, this was also a flooding technique where the cheat clients were requesting full updates each frame instead of delta updates, effectively flooding the server with a lot of outbound traffic, consuming their compute. Almost all servers have a protection against this. ↩
-
This function is well known among hackers and modders; this is a core of the client movement sending code where each
clc_movepacket is issued to the server. This function name IIRC survived till CS:GO and served same purpose. ↩ -
This is a very rough guess, but the project really overtook the community in this regard. ↩
-
We will talk about client-side interpolation in the next part but just to summarize, the client interpolates entities in order to make the gameplay experience smoother. Because of this, it needs to maintain a list of snapshots from the past similar to server. In order to interpolate from point N to N-1 where N has not yet been delivered by the server, the client renders entities from the past, and therefore this adds even more delay to the latency. More on this in the next part, for now, just remember that the client artificially adds up latency. ↩
-
See rehlds on GitHub. ↩