GoldSrc Networking, Part 2: Transmission -- Getting Bytes Across the Wire
The lower four layers of the GoldSrc netcode: UDP sockets and SPLITPACKET, the NetChannel's one-bit reliability scheme, bit-level serialization, and the self-describing delta encoder. Part 2 of a four-part reverse-engineering series.
Ever wondered how does GoldSrc networking work under the hood? How does it transfer bytes over the wire? How does it ensure reliability when the socket is UDP? How is data encoded and compressed before sent, to ensure low latency? Uhmm.. What's that? ... No you didn't ? 😀 Shame! Well... I did, and this article is a comprehensive writup of just that. ðŸ¤
This part walks the four layers underneath the game code -- the UDP socket, the NetChannel, the bit writer, and the delta encoder -- and follows a game message all the way down into bytes on the wire. On the way through we run into:
- why does the engine splits the packet under 1400 bytes, and why did this matter in 90s,
- what does the engine do to delta-compress the data to ensure maximal data-efficiency during transmission,
- how does it implement reliability through sequence numbers on the application layer to implement a lightweight TCP mechanism,
- and how does CS2 build on top of this after 30 years of development.
Here's a little TL;DR of the part 1, which introduces this series and establishes a historic background:
Recap: In Part 1 we laid out the five-layer stack the engine uses and the technical and historical background of the engine from the Quake view.
GoldSrc Networking series -- Part 2 of 4:
- Part 1 -- The High-Level Overview: history, the client-server model, and the five-layer stack.
- 👉 (this article) Part 2 -- Transmission: how bytes actually cross the wire -- UDP and
SPLITPACKET, the NetChannel's one-bit reliability, bit serialization, and the delta encoder. - 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.
Layer 1 -- The UDP Socket (net_ws.c)¶
On the lowest layer of the stack there are raw UDP sockets. GoldSrc builds on top of QW/Quake2 net_wins.c implementation and as previously discussed in Part 1, it's using the classic POSIX
Berkeley sockets API.
First of all, the socket GoldSrc creates is a non-blocking socket. If it were a blocking socket, a call to recvfrom would hang the thread. Since it's all running on one main thread1, this would freeze the entire execution.
Other flags specified in the setsockopt function are SO_BROADCAST and SO_REUSEADDR. The first one allows sending to broadcast addresses like 255.255.255.255. This is what makes LAN server discovery work. The latter one is only set when a launch option -reuse (not used by default) is specified. For multicast it's practically required (multiple listeners on the same group port); the -reuse option was for running several server instances on one machine. It's deliberately not default, because on a plain UDP unicast socket, two processes binding the same port can make the other one multiplex its traffic, resulting in garbage data.
The code also supports IPX, which is an obsolete network layer protocol.
The Hidden MultiThreading in this Code¶
The implementation also allows for asynchronous packet ingestion using a secondary thread that listens on the socket. However, this option is not the default and for some reason, the singlethreaded approach is used unless -netthread launch option is specified.
The two threads communicate through a small message queue. The NET thread spends its whole execution waiting on the socket. Whenever a packet arrives, it copies it into a buffer taken from a preallocated pool and appends it to a simple linked-list queue. On the other side, the main thread pops packets off that queue at the exact place where it would otherwise read the socket directly. The rest of the whole engine pretty much runs on a single thread and the interface of getting the messages from the socket remains the same, only a locking mechanism is in place if this is ever used. Access to the queue is protected by a critical section lock.
flowchart LR
subgraph NT["NET thread"]
direction TB
S1["wait on the socket<br/>(select)"] --> S2["receive packet"] --> S3["copy into a<br/>pooled buffer"]
end
Q["packet queue<br/>(shared, lock-guarded)"]
subgraph MT["main thread"]
direction TB
G1["NET_GetPacket()<br/>pops the oldest packet"] --> G2["engine processes<br/>the packet"]
end
NT -->|append| Q
Q -->|pop| MT
classDef srv fill:#2d3b52,stroke:#5a7db0,color:#eef2f7;
classDef cli fill:#22303f,stroke:#3d5a80,color:#e0e6ed;
class S1,S2,S3 srv
class G1,G2 cli
How the NET thread hands packets to the main thread when -netthread is enabled. The packet buffers come from a preallocated pool and return to it once the main thread is done with them.
The thread is Windows-only, and it is never shut down gracefully: the engine just kills it with TerminateThread().
The PDU In net_ws.c¶
At this layer, a UDP datagram can take one of two special forms, both identified by the first 4 bytes of the payload. Any other value in those 4 bytes means the datagram is a regular NetChannel packet, and this layer passes it through unchanged.
The first form is the connectionless PDU, marked with -1. This one is used surprisingly often. It carries everything that happens outside an established connection: the getchallenge / connect handshake when joining a server, the queries a server browser sends (info, players, rules, ping), and rcon commands. Its layout is minimal, the marker is usually followed by plain ASCII text:
packet title The connectionless PDU 0-31: "netID = -1" +32: "ASCII command text (getchallenge, connect, ...) and its data"
Connectionless data that is purely unreliable. If one query gets lost, the sender simply must ask again.
The second form is the splitpacket PDU, marked with -2. Only the server sends these, and only when a packet exceeds 1400 bytes (also known as MAX_ROUTEABLE_PACKET) and has to be broken into chunks2. Each chunk gets a 9-byte header:
#pragma pack(1)
struct SPLITPACKET
{
int netID; // -2
int sequenceNumber;
byte packetID; // index / count
};
#pragma pack()
The SPLITPACKET header layout
packet title The SPLITPACKET PDU (one chunk of a large packet) 0-31: "netID = -2" +32: "sequence number" +4: "count" +4: "index" +24: "chunk of the original packet (up to 1391 bytes)"
The single packetID byte splits into two values that are helpful during packet reassembly.
The remaining chunk of data, the 1391 bytes, also known as SPLIT_SIZE, is the remaining payload in the packet buffer after the SPLITPACKET header.
Data Reassembly upon Receive¶
UDP datagrams (kept under the ~1500-byte Ethernet path MTU to avoid IP fragmentation) go through the network independently, and because each packet may travel a different route, they arrive at the destination at different times. This causes what's known as Out-of-order delivery. Because of this, GoldSrc implements a simple mechanism to preserve the data order they were originally sent in.
The SPLITPACKET's sequence number identifies which split packet a chunk belongs to. The sender increments it once per split packet, and the receiver uses it to group chunks together. Reassembly is deliberately simple: there is a single global buffer holding one packet in progress, so when a chunk with a new sequence number arrives, any incomplete packet is discarded. The sequence number is also remembered per chunk index, which lets the receiver ignore duplicated chunks. There is no retransmission at this layer: if one chunk is lost, the whole packet is lost.
Then, the packetID 8-bit value is split into two nibbles: index / count. This pair is used for the reassembly of the data itself. count says how many chunks the packet was split into and this value is kept unchanged during splitting. index determines where the chunk's data is copied. Each chunk has the size of 1391 (SPLIT_SIZE) bytes. The total size becomes known when the last chunk (index == count - 1) arrives, and the packet is handed to the next layer once all count chunks with a matching sequence number have been received.
The 4-bit nibble could describe up to 15 chunks, but the engine caps it at 5. In theory that allows about 7 KB (5 * SPLIT_SIZE), but as shown below, the reassembly code rejects anything above 4010 bytes, so in practice a split packet never exceeds 3 chunks.
sequenceDiagram
participant S as Server<br/>(sends chunks 0, 1, 2)
participant C as Client<br/>(reassembly buffer)
S->>C: chunk index 2 (seq 42)
Note over C: copied to offset 2782<br/>have 1 of 3
S->>C: chunk index 0 (seq 42)
Note over C: copied to offset 0<br/>have 2 of 3
S->>C: chunk index 1 (seq 42)
Note over C: copied to offset 1391<br/>have 3 of 3 -- complete,<br/>packet handed to the next layer
The server sends the chunks in order 0, 1, 2, but the network delivers them as 2, 0, 1. Each chunk is copied to the position given by its index, so the arrival order does not matter. If a chunk with a different sequence number than 42 arrived, it'd either restart the buffer (a new packet) or get ignored as a duplicate of an old one.
Why Not Use All 15 Chunks¶
Why not? It's not intuitive at first, but statistically, the lower cap is more effective.
A fully reassembled split packet is only accepted if all parts of the packet are present. If only one part is missing, the whole split will be thrown away. With higher number of splits the probability of one missing gets higher. The probability that all $n$ chunks arrive is:
$$ (1-p)^n $$
Now, I'll assume a 1990s-typical 3% loss (though I need to emphasize: no source on this!). At that rate, 5 chunks still gets through ~86% of the time; 15 chunks drops to ~63%, and every failure wastes the bandwidth of all the chunks that did arrive.
Another kinda GoldSrc-specific constraint is that any split packet sized above MAX_UDP_PACKET (4010 bytes) is thrown away as a too-big packet anyway:
qboolean NET_GetLong(unsigned char* pData, int size, int* outSize)
{
...
int packetNumber = (packetID >> 4);
if ((SPLIT_SIZE * packetNumber + size) > MAX_UDP_PACKET)
{
Con_Printf("Malformed packet size (%i, %i)\n", SPLIT_SIZE * packetNumber, size);
return FALSE;
}
...
}
FakeLag And FakeLoss¶
The socket layer also contains the engine's built-in network condition simulator: two developer cvars, both requiring sv_cheats.
fakelagdelays all incoming data by the given number of milliseconds. Received packets are not handed to the engine immediately; they are appended to a per-socket queue with a timestamp and released only once they are old enough. The current lag value also converges toward the cvar gradually instead of jumping, so changing it mid-game does not produce one absurd packet gap.fakelossdrops incoming packets. A positive value is a percentage, so each packet is discarded with that probability. A negative value is deterministic and drops every|n|-th packet. The packets are received from the socket normally and then simply not processed, so to the layers above, it looks just like real loss.
This was probably used for testing the netcode, and fun fact, this doesn't come from Quake and is purely Valve thing.
Layer 2 -- The NetChannel (net_chan.c)¶
One layer up is the NetChannel, the connection abstraction built on top of the raw socket. Personally I find this the most complex layer and also the hardest to understand, because of all the state variables, buffers, and timing nuances. I will try my best explaining it as clearly as possible.
This layer gives each client-server pair a sequenced stream of packets, TCP-like reliability for important data (like chat messages), and an unreliable tail for the data that isn't fatal when lost. On top of the inherited QuakeWorld design, GoldSrc added fragmentation for large reliable payloads such as files; more on that later.
The Sequence Numbers¶
Why do sequence numbers need to exist? UDP is quite random. Packets deliver out of order, are lost, are delayed, or duplicated, and the receiver doesn't know about any one of these things. For every packet that arrives, a game protocol has to be able to tell:
- Is this data older than what I already have?
- Did anything get lost before it?
- Did my reliable data make it across? Do I need to resend to make sure?
Sequence numbers deal with all of these. The idea is the same one TCP uses to sequence its segments; what differs is how the code reacts to problems, and we'll get to that. Each side (client & server) keeps its own counter, incremented once per packet it transmits. Both numbers in a packet's header are written from the standpoint of the machine sending that packet:
- outgoing sequence - the number the sender assigned to this very packet.
- acknowledged sequence - the highest packet number the sender has received from the other side so far.
So each packet simultaneously numbers itself and acknowledges the other direction; there are no separate ack packets. The way this works with the sequence numbers is done in similar way in regular TCP implementation.
The first two questions are solved by simply discarding packets. A packet whose number is not newer than the newest one already received gets dropped entirely, and the gap between consecutive numbers tells the receiver exactly how many packets were lost in between. Nothing is buffered or reordered but rather the newest packet simply preempts the older one. This is where this implementation differs from TCP. TCP usually buffers out-of-order segments and reorders them into a stream, while here they are discarded, because an update from 50 ms ago has no value once a newer one has been applied.
One-Bit Reliability¶
The third question is answered by two single-bit flags, one of which is on top of each sequence number.
Say the server wants to send the client a reliable message (e.g., a chat message). The server keeps exactly one reliable message in transmission per client, in a dedicated buffer. When a new reliable message is loaded into that buffer, the server flips a one-bit toggle (reliable_sequence ^= 1) and transmits the packet with the R flag set.
The client, upon receiving a packet with the R flag, flips its own record of the server's toggle, and echoes it in the top bit of the acknowledged-sequence integer of every packet it sends from then on. Once the echoed bit matches the server's toggle, the message is confirmed as delivered.
The channel is symmetric, so the client-to-server direction works exactly the same way.
sequenceDiagram
participant S as Server<br/>(toggle = 0)
participant C as Client<br/>(record of server's toggle = 0)
Note over S: reliable message is loaded into the buffer,<br/>toggle flips: 0 to 1
S->>C: outgoing sequence 100, R flag = 1, reliable payload
Note over C: payload processed,<br/>record flips: 0 to 1
C->>S: outgoing sequence 205, R bit of the<br/>acknowledged sequence = 1
Note over S: received R bit 1 == my toggle 1,<br/>message confirmed, buffer freed
C->>S: outgoing sequence 206, R bit of the<br/>acknowledged sequence still 1
Note over S,C: the confirmation repeats in every later packet,<br/>so one lost packet cannot lose the acknowledgement
One reliable message exchange. The toggle travels as the R flag of the sender's outgoing sequence; the confirmation travels back as the R bit of the receiver's acknowledged sequence. Both are single header bits (shown in the PDU below), so no extra bytes are spent. Each side numbers its own packets, which is why the two counters (100 and 205) are unrelated.
The server usually sends data at a lower pace (hence the lower sequence number: 100) while the client, running at 100 fps and more, often sends more packets. This is also constrained by cl_cmdrate value, of course.
Packet Loss on Reliable Payload¶
Since UDP never guarantees delivery, a dropped chat message or spawn event would simply be gone without retransmission. Luckily, retransmitting reliable data needs no complicated logic or timers. The server resends when this condition becomes true:
// Netchan_Transmit()
if (chan->incoming_acknowledged > chan->last_reliable_sequence &&
chan->incoming_reliable_acknowledged != chan->reliable_sequence)
In other words: the client has acknowledged a packet newer than the one that carried the reliable data, yet the reliable-acknowledge bit it echoes back (the top bit of the acknowledged-sequence word, incoming_reliable_acknowledged on the server) still holds the old value, not the toggled value the server sent with the reliable payload. That combination can be considered as proof that the packet has been lost, because the client demonstrably received later traffic without ever seeing the reliable payload, otherwise it would have flipped that bit to match the state. There's no timeout timer either, the constant packet stream takes care of that, and since nothing is resent unless its loss is proven, no duplicates can occur.
This bit-toggling scheme is known as the alternating bit protocol. The cost of this implementation is the throughput. There exists at most one reliable payload, roughly 1200 bytes, per round trip. That is why the reliable stream only carries data that must arrive, and why file transfers running through it are slow (see Fragmentation).
Producing a Reliable Message¶
Where does the reliable message come from in the first place? Any engine or game code that wants guaranteed delivery simply writes into that client's accumulation buffer, netchan.message:
// SV_ClientPrintf(), host.cpp
MSG_WriteByte(&host_client->netchan.message, svc_print);
MSG_WriteString(&host_client->netchan.message, string);
Nothing is sent at that moment. At transmit time, if the reliable buffer is free, the channel copies everything accumulated so far into it, flips the toggle, and the mechanism above does the rest.
The NetChan Internals¶
Read this section if you're interested in how the netchan code works internally, with all of its state and logic.
If you'd ever stumble studying the netchan code yourself, the hardest part is IMO understanding the several similarly named state variables in netchan_t.
Two nice rules help understand the naming:
- Each side keeps its own copy of the struct, written from its own point of view.
- The
incoming_prefix means the latest thing I learned from the remote's packets I've gotten.
With that, here's a short table describing each in detail:
| Variable | Type | Written in | Meaning |
|---|---|---|---|
outgoing_sequence |
int |
Netchan_Transmit() |
my own packet counter, bundled with every packet I send |
incoming_sequence |
int |
Netchan_Process() |
the newest packet number I have received from the remote |
incoming_acknowledged |
int |
Netchan_Process() |
the newest of my packet numbers the remote confirmed receiving |
reliable_sequence |
qboolean |
Netchan_Transmit() |
my one-bit toggle; flips every time a new reliable message is loaded |
incoming_reliable_acknowledged |
qboolean |
Netchan_Process() |
the toggle bit the remote last echoed back to me; once it matches reliable_sequence, my reliable message is confirmed |
incoming_reliable_sequence |
qboolean |
Netchan_Process() |
my record of the remote's toggle; this is the bit I echo back to them |
last_reliable_sequence |
int |
Netchan_Transmit() |
which of my packets last carried my reliable message; used by the resend check |
Everything in this layer is manipulation of these seven values. If you're confused on all of the variables, that's fine. It's a really complicated state machine after all, and requires careful inspection for good understanding. Here's a sequence diagram showing a full reliable message transmission, and how the client and server manipulate their state:
sequenceDiagram
autonumber
participant S as Server
participant C as Client
activate S
Note right of S: Netchan_Transmit()
S->>S: reliable_sequence flips (reliable message loaded)
S->>S: outgoing_sequence++
S->>S: last_reliable_sequence = 100 (for example)
S->>C: packet 100, R flag set
deactivate S
activate C
Note left of C: Netchan_Process()
C->>C: incoming_sequence = 100
C->>C: incoming_acknowledged = ack from the header
C->>C: incoming_reliable_acknowledged = received R bit
C->>C: incoming_reliable_sequence flips (R flag was set)
deactivate C
activate C
Note left of C: Netchan_Transmit()<br/>(next frame, from CL_Move)
C->>C: outgoing_sequence++
C->>S: packet 205 (for example), header carries<br/>incoming_reliable_sequence as the echo
deactivate C
activate S
Note right of S: Netchan_Process()
S->>S: the three incoming_ values updated the same way
S->>S: reliable message confirmed
deactivate S
Here you can see the entire flow, what exactly is set by who, and how the state propagates between the two parties. The vertical bars mark which function is executing, and each arrow-to-self is one state write from the table above.
The PDU In net_chan.c¶
When it comes to the netchan PDU, all of the shared state fits into 8 bytes in front of the payload. Two 32-bit sequence numbers with the flags packed into their top bits, as stated previously in The Sequence Numbers section.
The first integer contains the outgoing sequence, the R bit saying whether this packet carries reliable data, and an F bit saying whether it carries fragments (explained in Fragmentation below). The second integer contains the acknowledged sequence with the echoed reliable bit on top. After the header come the fragment sub-headers (when F is set), the reliable block (when R is set), and whatever unreliable data still fits after that:
packet title The NetChannel header (two 32-bit words) 0-29: "outgoing sequence" +1: "F" +1: "R" +31: "acknowledged sequence" +1: "R"
The fixed 8-byte header, one 32-bit word per row. R = reliable flag, F = fragment flag. The variable-length body listed above (fragment sub-headers, reliable block, and then the unreliable tail) follows these 64 bits; those parts have no fixed bit layout, so they aren't shown here.
The Anti-Cheat Bit in Early Builds¶
In the early WON-era builds of the engine, the first sequence integer carried one more flag, an anti-cheat tag in bit 28:
packet title The first sequence integer in early WON builds 0-27: "outgoing sequence" +1: "C" +1: "-" +1: "F" +1: "R"
C = the "cheat-detected" tag. In today's builds these bits are not set.
From what I know, the bit 29 was never used for anything, which I find quite strange.
The client game itself was running a bunch of anti-cheat checks, and they all set the flag seen here. When one of the checks hit, nothing visible happened. On the next transmitted packet, Netchan_Transmit checked the flag, set the bit 28, and cleared it again. After that, congratulations, the client has just quietly reported itself to the server.
The server does nothing right away either. Netchan_Process clears the bit back out of the sequence number and calls Netchan_ScheduleDelayedDrop function6, which selects a client disconnect time of 15 to 22 seconds, randomized. After the time runs out, the client who got flagged then gets disconnected. This all happens well after whatever triggered the detection, with nothing obvious to correlate it to.
The detection methods used for various cheats are a topic of its own, so I will not discuss them here. Why this mechanism was removed though is anyone's guess. I suggest it was removed with all of the "anti-cheat" code present in the game at the time, and outsourced to a VAC module instead, although I don't have this confirmed.
Fragmentation¶
The reliable stream can oftentimes have a size problem. One reliable payload is at most ~1200 bytes (hardcoded), and the one-bit scheme only allows a single reliable message in transmission per round trip. Anything bigger, a resource file the client needs to download for example, has to be cut into pieces and moved piece by piece. That is what fragmentation is for, a GoldSrc addition on top of the QuakeWorld channel.
In Quake there was no such mechanism at the channel level. A reliable message had to fit in a single packet, and there was no way to hand the netchannel a payload larger than that. Bulk transfers were done one layer up, in the game protocol: to send a file, the Quake 2 server wrote it into the reliable buffer as a stream of svc_download blocks of at most 1024 bytes each, one block per client request, and the client asked for the next block (nextdl) after processing each one. GoldSrc moved this splitting down into the netchannel itself, so the reliable stream can carry an arbitrarily large payload and the game code doesn't have to chunk anything by hand.
This is the second splitting mechanism in the stack, so to keep the two apart:
| SPLITPACKET (Layer 1) | Fragmentation (Layer 2) | |
|---|---|---|
| Purpose | one oversized datagram | bulk data (files, big messages) |
| Reliability | none, one lost chunk kills the packet | guaranteed by the one-bit scheme |
| Direction | server to client only | both directions |
| Capacity | 4010 bytes (MAX_UDP_PACKET, ~3 chunks) |
up to 65535 fragments |
Each channel has two independent fragment streams, FRAG_NORMAL_STREAM for oversized reliable messages and FRAG_FILE_STREAM for file transfers, each with its own queue of pending fragments. The separation exists so that a several-minutes-long file download does not block other reliable payload.
While a reliable message is in transmission, newly written reliable data keeps accumulating, and if the backlog grows past the 1200-byte payload limit by the time the buffer frees up, the channel does not fail. The oversized data is compressed and split, and gets queued as fragments automatically. Only when the accumulator outgrows its own capacity does the connection actually give up, printing the "reliable channel overflow", followed by a disconnect.
This is also what the fragment sub-headers from the PDU diagram display. When a packet contains fragments, the F flag is set, and after the 8-byte header comes one small record per stream: a presence byte, a 4-byte fragment id holding a 16-bit group id and a 16-bit total count, and two shorts locating the fragment inside the reliable block (offset and length). Fragments are reliable data, so their delivery is guaranteed by the same one-bit scheme described above; a lost packet is retransmitted.
I'm not going to go into much more detail about the implementation. On the transmitting side the data is compressed (more on that below) and cut into numbered fragments, and the receiver collects them until the group is complete, then reassembles them into one continuous in-order blob, for example a file.
Payload Obfuscation & Compression¶
In order to protect the data, GoldSrc uses "Munging" (no idea what is the etymology of that), which is basically a combination of xorring, byte-swapping, xorring from a table of values, etc. This isn't encryption, it's just obfuscation of the data. Quake doesn't use this so data on Quake servers were transmitted in plaintext.
The munge covers everything after the first 8 bytes of the packet. The header has to stay readable, because the sequence number inside it is the key the receiver uses to reverse the munge.
Beginning with CS, the game essentially created the cheating industry. Before that, game cheats weren't as popular, so Valve needed to act on this. Beginning around build 1460, Valve added payload obfuscation, to prevent possible MITM cheats. At the time, I suspect Valve was at war with cheaters, because there were so many cheats being developed at the time.

Counter-Strike ~1.3 Cheat called HeliX.
The data is also compressed, though only on the fragment path. The payload is run through Bzip2 before being cut into fragments, and prefixed with a small BZ2 magic so the receiver knows to decompress after reassembly. Compressing first also shortens the transfer itself: fewer bytes means fewer fragments, and each fragment costs a round trip. Per-frame game data is not compressed at all. This data is already "manually compressed enough", and is latency-critical, so compressing it would not be efficient. The 8684 Steam engine uses Bzip2 version 1.0.2 from 30-Dec-2001, statically linked into the engine.
Rate Limiting¶
Each channel has a bytes-per-second budget, and there are two knobs controlling it:
rateis a client cvar (default 30k, clamped between 1k and 100k). It's sent to the server in a userinfo string, and the server applies it to that client's channel. In other words, the player declares how fast the server may send to them. In 1999, the player behind a modem may setrate 3000and the server rate-limited the connection.cl_ratewas a console command used in builds around 2511 that set the client's own channel rate, i.e. the client-to-server direction. This cvar is either not used, or is under a_DEBUGmacro not defined in retail builds, since the client's output is small enough that limiting it didn't matter anymore, apparently.
The implementation is a virtual clock. Every transmitted packet pushes a cleartime timestamp into the future, proportionally to its size:
// Netchan_Transmit()
chan->cleartime += (sb_send.cursize + L3_L4_HEADER_SIZE) * (1.0 / chan->rate);
Where L3_L4_HEADER_SIZE is 28 bytes added on top3, so the budget models what the wire actually carries, not just the payload. A channel may send only when cleartime has gotten behind the present. That check is in Netchan_CanPacket(), and both sides use it: the client in CL_Move() before sending its movement packet, and the server before building a client's update.
The interesting part is what happens when the server-side check fails: the update for that frame is simply not built. Nothing is queued, since that would only add latency, and the next update supersedes the skipped one anyway. The server only counts how many updates were withheld (chokecount), and prepends an svc_choke message to the next packet that does go out, so the client's interpolation code knows there is a gap and why.
On modern connections this whole mechanism is basically useless. rate should just be at the maximum, unless you're in an extremely connection-limited environment.
Layer 3 -- Bit Serialization (common.c)¶
Packing numbers into a stream of data is straightforward. But in the 90s the network budget was kind of brutal. A modem player's rate 3000 gives the server about 3 KB per second to send the entire world to them. At that budget, a naively serialized 12-byte vector is a luxury, kind of. Therefore bit serialization exists.
Bit serialization packs numbers as tightly as possible. There exist many clever techniques such as variable-length integers, 8-bit or 16-bit floats, quantized floats, huffman coding, etc. Almost all of these I've named are actively used in CS2 (Source2 engine) as of today. However, GoldSrc uses far simpler, manual, and tedious approach.
The programmer chooses which values are bit-aligned and which aren't. For instance the delta fields, the resource list, coordinates, etc. are bit-aligned, because this data is relatively dense. The serialization is LSB-first. The amount of bits for each value is specified:
void MSG_WriteBits(uint32 data, int numbits);
MSG_StartBitWriting(&buf);
MSG_WriteBits(res->nIndex, MAX_RESOURCE_INDEX_BITS);
MSG_WriteBits(res->nDownloadSize, MAX_RESOURCE_DL_FILESIZE_BITS);
MSG_WriteBits(res->ucFlags & (RES_WASMISSING | RES_FATALIFMISSING), 3);
MSG_EndBitWriting(&buf);
// or e.g.:
MSG_WriteByte(&buf, clc_move);
The bitstream is byte-aligned and also bit-aligned when certain conditions are met. There's functionality for all sorts of data types: MSG_WriteByte, MSG_WriteLong, MSG_WriteFloat, and even custom serializers such as MSG_WriteUsercmd, MSG_WriteCoord, and the reading counterparts.
As it's common in C, there's a struct holding the buffer that is filled along with the flags. This is the sizebuf_t buffer struct. The flags check for the buffer overflowing: FSB_ALLOWOVERFLOW and FSB_OVERFLOWED. At initialization, the caller usually does the following:
// CL_Move()
sizebuf_t buf;
// Prepare the movement buffer we'll send
Q_memset(&buf, NULL, sizeof(sizebuf_t));
buf.buffername = "Client Move";
buf.data = data;
buf.maxsize = sizeof(data);
buf.cursize = 0;
buf.flags = FSB_NONE;
The buffer is then continuously written into using the MSG_Write* functions. Normally, the buffer is byte-aligned; however, bit-level serialization can be enabled using functions MSG_StartBitWriting, MSG_EndBitWriting, and MSG_StartBitReading. Once enabled, the data is packed as tightly as possible.
On the clientside, the sizebuf_t buffer is then passed to Netchan_Transmit and transmitted to the server, in CL_Move() if the client isn't rate-limited.
Writing Resource List¶
This is the simplified engine code that builds the svc_resourcelist message:
// SV_SendResources()
MSG_WriteByte(msg, svc_resourcelist); // byte mode
MSG_StartBitWriting(msg); // enter bit mode
MSG_WriteBits(sv.num_resources, MAX_RESOURCE_INDEX_BITS);
for (i = 0; i < sv.num_resources; i++)
{
res = &sv.resourcelist[i];
MSG_WriteBits(res->type, 4);
MSG_WriteBitString(res->szFileName);
MSG_WriteBits(res->nIndex, MAX_RESOURCE_INDEX_BITS);
MSG_WriteBits(res->nDownloadSize, MAX_RESOURCE_DL_FILESIZE_BITS);
MSG_WriteBits(res->ucFlags & (RES_WASMISSING | RES_FATALIFMISSING), 3);
// ...
}
MSG_EndBitWriting(msg); // pad to the byte boundary
// byte-aligned writes continue from here
And this is how same data visualizes into a packet diagram:
---
config:
packet:
bitsPerRow: 36
---
packet
title Byte mode, then a bit-packed span, then byte mode again
0-7: "svc_resourcelist"
+12: "count"
+4: "type"
+12: "index"
+24: "download size"
+3: "flg"
+1: "p"
+8: "next message"
A single resource entry, with the file name omitted for simplicity. flg = resource flags, p = pad bit; MSG_EndBitWriting fills the started byte with zeros, so at most 7 bits per bit-span are wasted.
Layer 4 -- Delta Encoding: The Mechanism (delta.c)¶
The layers so far dealt with how to move bytes. The fourth layer exists to avoid sending them in the first place. Delta encoding transmits only the fields of an object that changed compared to a reference state both client and server have saved, instead of the whole object. Which object gets compared against which reference (baselines, snapshots, and so on) is the topic of Part 3. This layer provides just the mechanism.
The interesting part of the GoldSrc implementation is that it's fully data-driven. The engine does not hardcode what an entity update contains. Instead, every networked struct, entity_state_t, clientdata_t, usercmd_t, etc., has a field table describing how each member is encoded. Note that usercmd_t in that list means the client-to-server direction is delta-encoded too: each movement command inside clc_move is encoded against the previous one. The tables are loaded at startup from a plain text file, delta.lst, that ships with the game:
clientdata_t none
{
DEFINE_DELTA( origin[0], DT_SIGNED | DT_FLOAT, 21, 128.0 ),
DEFINE_DELTA( velocity[0], DT_SIGNED | DT_FLOAT, 16, 8.0 ),
DEFINE_DELTA( m_flNextAttack, DT_FLOAT | DT_SIGNED, 22, 1000.0 ),
DEFINE_DELTA( ammo_shells, DT_SIGNED | DT_INTEGER, 10, 1.0 ),
DEFINE_DELTA( health, DT_SIGNED | DT_FLOAT, 10, 1.0 ),
// ...
}
A showcase from the delta.lst listing; field name, type, number of bits, and a multiplier.
Each line declares the following: field type (the DT_* flags: byte, short, integer, float, angle, string, or a server-time-relative timestamp), how many bits it takes, and a multiplier. Internally, every line becomes a delta_description_t holding the field's name, its byte offset inside the struct, the bit count, and a premultiply/postmultiply pair.
The multiplier is used for primitive floating-point quantization. A value is multiplied by premultiply before writing and by postmultiply after reading4. Reading the fragment above: origin[0] is sent as a 21-bit signed integer of 1/128-unit steps, m_flNextAttack (a weapon cooldown timestamp) with 1/1000-unit (millisecond) precision, and health as a whole number, because usually, nobody needs fractional health. Each field's precision is an explicit, tunable parameter in the definition file.
The PDU In delta.c¶
Encoding an object is then a three-step process. Compare the old and new struct field by field, set a bit in a bitmask for every field that differs, and write: 3 bits saying how many mask bytes follow, the mask itself, and only the marked fields, each packed by the Layer 3 bit writers with its configured bit count. This also puts a limit on the table size: at most ~64 fields per struct5, since the mask is kept in two 32-bit integers.
packet title One delta-encoded object 0-2: "size" +13: "bitmask" +16: "changed fields"
size = how many mask bytes follow (3 bits); bitmask = one bit per field (1-7 bytes); changed fields = only the marked fields, each bit-packed with its configured width. A field that didn't change since the reference frame costs only one bit, a zero in the mask.
The Table That Describes Itself¶
To decode a delta-encoded object, the receiver needs the exact table it was encoded with. The bitmask is only meaningful if both sides agree which bit belongs to which field, and a field's value only reads back correctly with the right bit count and multiplier. If the client's table differs from the server's in a single entry (order, width, anything), everything after that field is misread.
So how do both sides end up with identical tables? Relying on both machines having the same delta.lst file would be fragile, since a mod can edit the file, or the two installations are simply not the same version. GoldSrc instead ignores the client's local file entirely. At connect time, the server transmits the tables it uses, one svc_deltadescription message per table, and the client decodes all later traffic with these received tables.
But how is the table itself put on the wire? A table is an array of field descriptions, and each description is a small struct of its own (delta_description_t: field name, type, bit count, multipliers). The engine uses the same delta encoder to serialize the delta descriptions. That in turn requires a table describing the description struct itself. This table, the meta table (g_MetaDelta), is hardcoded into both binaries, and it is the only one that has to match at compile time, all the other tables just arrive as data.
When a description is transmitted, it's "delta"-encoded using an all-zero reference, the mask therefore marks every non-zero field. Zero fields are not transmitted because they'd have no effect.
sequenceDiagram
participant S as Server
participant C as Client
Note over S,C: only the meta table is compiled into both binaries
S->>C: svc_deltadescription -- entity_state_t, clientdata_t tables
Note over C: client stores the received tables
S->>C: entity updates, delta-encoded per those tables
Note over C: decoded with the received tables,<br/>not with the client's own delta.lst
The connect-time exchange. The transmitted tables are themselves encoded with the meta table, which both sides carry in the binary.
The same delta mechanism that compresses entity data also transmits its own schema, which makes this design recursive, and a mod can restructure its network encoding by editing the listing file, without engine modifications.
The Differences from Quake¶
Quake and Quake 2 delta-encode too and GoldSrc built on top of it. The difference is in how the per-struct schema gets defined. Quake 2 describes an entity update with hardcoded flag bits (U_ORIGIN1, U_FRAME8, and so on, plus U_MOREBITS to chain more mask bytes). The meaning of each bit is compiled into both the client and the server, so if you wanted to add a field or change its precision, you had to edit the engine on both ends and bump the protocol version.
GoldSrc iterated on this by moving the schema out of the code into the definition file that can be extended by mods.
The Same Mechanism in CS2¶
The delta system is the one part of this stack that remained in place through every engine rewrite since.
In Source (2004), the delta.lst tables became SendTables and RecvTables. The per-field descriptions stayed pretty much the same (type, bit count, value range), except now they are defined in C++ macros inside the game DLLs instead of a text file. The server still transmits its table layout to the client during signon, so the schema remained self-describing.
Source 2, and therefore CS2, calls the tables flattened serializers. These are per-class field lists with types, bit counts and encoders, generated from the engine's schema system and sent to the client as a protobuf message called CSVCMsg_FlattenedSerializer. This is also the message a demo parser has to read first, before it can decode any entity at all. Everything around it changed over the years (protobuf framing, different compression, different reliability), but the model itself hasn't really: the object is compared against a reference state, a mask of the changed fields is sent, and each field is packed with the bit count from a table the server shipped.
Conclusion¶
As you can see, if dealt into details, the description of each layer can be quite complex to comprehend. Hopefully the wording chosen there was good enough to explain everything. The netchan part is quite easily the most complex out of all the layers however, once understood, at least from a high-level perspective, starts to make sense.
To quickly recap: at the very bottom, there's the SPLITPACKET code + raw Berkeley sockets. One layer above is the netchan code with reliability, fragments, and acknowledgements. Above that is the application layer, where bit writers are used, and delta compression as well. The engine code chooses what data is reliable (what needs to land on the receiver) and what isn't.
Regarding the delta system, it's nice that Valve made the delta definitions modifiable by making the delta.lst file "open-source" and available for edit. However, it's kind of sad that this system doesn't allow for addition of new fields / structs7. It only allows for change of the flags, precision, or pre/post-multiplication. Mods usually use this to tweak the map size, omit the fields that don't need to be delta-encoded at all, etc. Because of this limitation, mods need to operate on the few fields in entity_state_t: iuserX, fuserX, vuserX fields.
What the netcode stack fights with the most are the tradeoffs. Each layer trades off something for something else. That might be payload size, efficiency, or performance. The engineers (mainly from idSoftware, because this is what the stack built on top of) chose whatever was the best at the time, and it still happens to work today. Valve built on top of them and adapted the code for their use cases. For example Quake was never what CS was, and CS was far more demanding game in terms of network efficiency than Quake was.
Next¶
Next up, Part 3: The Server -- Lag Compensation, Client Movement, Speedhacking, where all of this machinery gets put to work building a separate view of the world for every client, running their movement, and rewinding the world for hit registration.
-
Yes, GoldSrc is (as well as Quake 1 & 2, and other engines) singlethreaded by design. The move towards multithreaded approach started to appear around Id Tech 4 (Doom 3 engine, and also used in Quake 4), which was developed around 2004-2005. Also, the Source engine is multithreaded as well. ↩
-
This is because only the server has anything that large to send. The client's per-frame output (movement commands and an occasional string command) fits well under 1400 bytes anyway. The server, on the other hand, produces large payloads at connect time and when many entities are visible at once. When the client needs to transfer something big (a file, for example), that goes through the fragmentation mechanism one layer up, in the NetChannel. ↩
-
This size is: size of the IP header - 20 bytes + size of the UDP header - 8 bytes. IP: RFC 791, UDP: RFC 768. However, for completeness, the 28-byte constant is still an approximation. The true cost of the data sent through the wire also includes layer 2 framing (Ethernet adds another 38 bytes with preamble and inter-frame gap, PPP over a modem added its own). ↩
-
In scenarios where the client and server might store the final value in different format, postmultiply != premultiply per se. For instance, in the
delta.lstfile we can see thatcustom_entity_state_t'sanimtimedelta description has premultiply value of1.0and postmultiply value of0.1. The client simply expects the value in different scale. ↩ -
Approximately. The real number is actually about 56 fields based on how the operations with the mask are implemented. ↩
-
Some of the function names used in this article are entirely my own; there's no DWARF information for some of these AFAIK. The other functions are available in either DWARF, PDBs, leaks, or other sources. ↩
-
Source engine actually fixes this by allowing mods to directly create new structs/fields in SendTables, because apparently this started to be quite limiting during mod development. ↩