wire

package
v0.4.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package wire is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package wire defines the YAML wire message schema format for pkg/online/netplay and game protocols, integer-only quantization helpers, bit-packing primitives, and deterministic zero-allocation Go and TypeScript codec generators.

Schema files declare fixed-width integers (with explicit big- or little-endian byte order), varints, zigzag signed varints, booleans, raw float32 values, integer-quantized qfloat and fixed-point numbers, length-prefixed or trailing bytes and strings, fixed and variable arrays, enums, MSB-first bit-packed fields, presence-bitmask groups with optional delta diff/apply generation, and tag- or nibble-discriminated unions.

Run game wire (directly or through go generate) to produce deterministic Go codecs (AppendX / DecodeX) and dependency-free TypeScript codecs (encodeX / decodeX, plus diffX / applyX for delta masks) that fill caller-owned storage without per-packet heap allocations.

Index

Examples

Constants

View Source
const (
	// Client hello (0xA1).
	HandshakeMessageTagHello uint8 = 161
	// Server welcome (0xA2).
	HandshakeMessageTagWelcome uint8 = 162
	// Server rejection (0xA3).
	HandshakeMessageTagReject uint8 = 163
)
View Source
const (
	// Join or leave announcement (tag 13).
	MembershipMessageTagChange uint8 = 13
	// Join state fragment (tag 14).
	MembershipMessageTagJoinStatePart uint8 = 14
)
View Source
const (
	// Unreliable peer datagram (0x01).
	RelayBodyTagUnreliable uint8 = 1
	// Reliable ordered peer segment (0x02).
	RelayBodyTagReliable uint8 = 2
	// Cumulative + 64-bit SACK acknowledgment (0x03).
	RelayBodyTagAck uint8 = 3
	// Piggybacked acknowledgements and coalesced messages (0x04).
	RelayBodyTagPacked uint8 = 4
	// Raw deflate-compressed unreliable peer datagram (0x81).
	RelayBodyTagUnreliableCompressed uint8 = 129
	// Raw deflate-compressed reliable ordered peer segment (0x82).
	RelayBodyTagReliableCompressed uint8 = 130
)
View Source
const (
	EntityRecordFieldKind     uint16 = 1 << 0
	EntityRecordFieldX        uint16 = 1 << 1
	EntityRecordFieldY        uint16 = 1 << 2
	EntityRecordFieldVX       uint16 = 1 << 3
	EntityRecordFieldVY       uint16 = 1 << 4
	EntityRecordFieldRotation uint16 = 1 << 5
	EntityRecordFieldFlags    uint16 = 1 << 6
	EntityRecordFieldProps    uint16 = 1 << 7
	EntityRecordFieldOwner    uint16 = 1 << 8
	EntityRecordMaskValid     uint16 = 0x1ff
)
View Source
const (
	ReplicationMessageVersion uint8 = 3
	// Full snapshot (type 1).
	ReplicationMessageTagFull uint8 = 1
	// Delta snapshot (type 2).
	ReplicationMessageTagDelta uint8 = 2
	// Snapshot acknowledgment (type 3).
	ReplicationMessageTagAck uint8 = 3
	// Full snapshot resync request (type 4).
	ReplicationMessageTagResync uint8 = 4
	// Split full snapshot part (type 5).
	ReplicationMessageTagFullPart uint8 = 5
	// Client-owned entity update (type 6).
	ReplicationMessageTagOwnerUpdate uint8 = 6
)
View Source
const (
	// Single input sample (tag 10).
	RollbackMessageTagSingleInput uint8 = 10
	// Redundant input bundle (tag 11).
	RollbackMessageTagInputBundle uint8 = 11
	// Periodic desync checksum (tag 12).
	RollbackMessageTagChecksum uint8 = 12
	// Redundant input bundle with per-peer frame advantage (tag 15).
	RollbackMessageTagInputSync uint8 = 15
)
View Source
const CurrentVersion = 1

CurrentVersion is the wire schema YAML format version this package reads and writes.

View Source
const DefaultModuleRange uint64 = 1000

DefaultModuleRange is the number of explicit message IDs allocated to a module when ModuleSpec.Range is zero. A module with base B owns [B, B+DefaultModuleRange) (for example, base 3000 owns 3000..3999).

View Source
const DefaultRuntimeImport = "github.com/nsgo-dev/game/pkg/online/netplay/wire"

DefaultRuntimeImport is the Go import path used by generated codecs outside pkg/online/netplay/wire.

View Source
const DefaultTSRuntimeImport = "./runtime.ts"

DefaultTSRuntimeImport is the ES module specifier imported by generated TypeScript codecs when EmbedRuntime is false.

View Source
const (
	HandshakeHelloVersion uint8 = 2
)
View Source
const (
	HandshakeRejectVersion uint8 = 2
)
View Source
const (
	HandshakeWelcomeVersion uint8 = 2
)
View Source
const (
	RelayFrameVersion uint8 = 1
)
View Source
const (
	RelayMembersKind uint8 = 1
)
View Source
const ReservedMessageIDMax uint64 = 15

ReservedMessageIDMax is the highest message ID reserved for pkg/online/netplay's own consumers (IDs 1..15). Application modules must declare their base and explicit message IDs strictly above ReservedMessageIDMax.

View Source
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL

SchemaComment is the yaml-language-server header line Encode writes at the top of a wire schema file.

View Source
const SchemaURL = "https://nsgo.games/schemas/wire.v1.json"

SchemaURL is where the JSON Schema of version 1 wire schema files (*.wire.yaml) is published.

Variables

View Source
var (
	// ErrShortBuffer is returned when the input slice ends before a message or field is complete.
	ErrShortBuffer = errors.New("wire: short buffer")
	// ErrOverflow is returned when a varint overflows 64 bits or exceeds the field's declared bit width.
	ErrOverflow = errors.New("wire: integer overflow")
	// ErrInvalidBool is returned when a boolean byte on the wire is neither 0 nor 1.
	ErrInvalidBool = errors.New("wire: invalid boolean value")
	// ErrInvalidEnum is returned when a decoded enum integer does not match any declared enum value.
	ErrInvalidEnum = errors.New("wire: unknown enum value")
	// ErrInvalidTag is returned when a union discriminator does not match any declared case tag.
	ErrInvalidTag = errors.New("wire: unknown message tag")
	// ErrInvalidVersion is returned when a nibble-split discriminator carries an unexpected high-bit version value.
	ErrInvalidVersion = errors.New("wire: unexpected protocol version")
	// ErrInvalidConst is returned when a constant wire field does not match its declared value.
	ErrInvalidConst = errors.New("wire: unexpected constant field value")
	// ErrInvalidMask is returned when a presence bitmask sets bits beyond the mask group's declared fields.
	ErrInvalidMask = errors.New("wire: unknown presence mask bit")
	// ErrNonZeroPadding is returned when trailing padding bits in a bit-packed byte are non-zero.
	ErrNonZeroPadding = errors.New("wire: non-zero bit padding")
	// ErrLimitExceeded is returned when a variable-length bytes, string, or array field exceeds its schema maxLength.
	ErrLimitExceeded = errors.New("wire: length limit exceeded")
)
View Source
var BuiltinFS embed.FS

BuiltinFS embeds the canonical YAML wire schemas describing every pkg/net wire format (transport, UDP sealed datagrams, handshake, relay, replication v2, lockstep/rollback, and membership).

Functions

func AppendChannel

func AppendChannel(dst []byte, v Channel) []byte

AppendChannel appends v to dst in wire format.

func AppendChecksumMsg

func AppendChecksumMsg(dst []byte, m *ChecksumMsg) []byte

AppendChecksumMsg encodes m onto dst in wire format without allocating when dst has capacity.

func AppendEntityRecord

func AppendEntityRecord(dst []byte, m *EntityRecord) []byte

AppendEntityRecord encodes m onto dst in wire format without allocating when dst has capacity.

func AppendHandshakeHello

func AppendHandshakeHello(dst []byte, m *HandshakeHello) []byte

AppendHandshakeHello encodes m onto dst in wire format without allocating when dst has capacity.

func AppendHandshakeMessage

func AppendHandshakeMessage(dst []byte, m *HandshakeMessage) []byte

AppendHandshakeMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.

func AppendHandshakeReject

func AppendHandshakeReject(dst []byte, m *HandshakeReject) []byte

AppendHandshakeReject encodes m onto dst in wire format without allocating when dst has capacity.

func AppendHandshakeWelcome

func AppendHandshakeWelcome(dst []byte, m *HandshakeWelcome) []byte

AppendHandshakeWelcome encodes m onto dst in wire format without allocating when dst has capacity.

func AppendInputBundle

func AppendInputBundle(dst []byte, m *InputBundle) []byte

AppendInputBundle encodes m onto dst in wire format without allocating when dst has capacity.

func AppendInputFrame

func AppendInputFrame(dst []byte, m *InputFrame) []byte

AppendInputFrame encodes m onto dst in wire format without allocating when dst has capacity.

func AppendInputSync

func AppendInputSync(dst []byte, m *InputSync) []byte

AppendInputSync encodes m onto dst in wire format without allocating when dst has capacity.

func AppendJoinState

func AppendJoinState(dst []byte, m *JoinState) []byte

AppendJoinState encodes m onto dst in wire format without allocating when dst has capacity.

func AppendJoinStatePart

func AppendJoinStatePart(dst []byte, m *JoinStatePart) []byte

AppendJoinStatePart encodes m onto dst in wire format without allocating when dst has capacity.

func AppendMatchMember

func AppendMatchMember(dst []byte, m *MatchMember) []byte

AppendMatchMember encodes m onto dst in wire format without allocating when dst has capacity.

func AppendMemberChange

func AppendMemberChange(dst []byte, m *MemberChange) []byte

AppendMemberChange encodes m onto dst in wire format without allocating when dst has capacity.

func AppendMemberChangeKind

func AppendMemberChangeKind(dst []byte, v MemberChangeKind) []byte

AppendMemberChangeKind appends v to dst in wire format.

func AppendMembershipMessage

func AppendMembershipMessage(dst []byte, m *MembershipMessage) []byte

AppendMembershipMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.

func AppendOwnerUpdate

func AppendOwnerUpdate(dst []byte, m *OwnerUpdate) []byte

AppendOwnerUpdate encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayAck

func AppendRelayAck(dst []byte, m *RelayAck) []byte

AppendRelayAck encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayBody

func AppendRelayBody(dst []byte, m *RelayBody) []byte

AppendRelayBody encodes the active case of m onto dst in wire format without allocating when dst has capacity.

func AppendRelayFrame

func AppendRelayFrame(dst []byte, m *RelayFrame) []byte

AppendRelayFrame encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayMembers

func AppendRelayMembers(dst []byte, m *RelayMembers) []byte

AppendRelayMembers encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayPacked

func AppendRelayPacked(dst []byte, m *RelayPacked) []byte

AppendRelayPacked encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayPackedItem

func AppendRelayPackedItem(dst []byte, m *RelayPackedItem) []byte

AppendRelayPackedItem encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayReliable

func AppendRelayReliable(dst []byte, m *RelayReliable) []byte

AppendRelayReliable encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRelayUnreliable

func AppendRelayUnreliable(dst []byte, m *RelayUnreliable) []byte

AppendRelayUnreliable encodes m onto dst in wire format without allocating when dst has capacity.

func AppendReplicationMessage

func AppendReplicationMessage(dst []byte, m *ReplicationMessage) []byte

AppendReplicationMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.

func AppendResyncRequest

func AppendResyncRequest(dst []byte, m *ResyncRequest) []byte

AppendResyncRequest encodes m onto dst in wire format without allocating when dst has capacity.

func AppendRollbackMessage

func AppendRollbackMessage(dst []byte, m *RollbackMessage) []byte

AppendRollbackMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.

func AppendSingleInput

func AppendSingleInput(dst []byte, m *SingleInput) []byte

AppendSingleInput encodes m onto dst in wire format without allocating when dst has capacity.

func AppendSnapshotAck

func AppendSnapshotAck(dst []byte, m *SnapshotAck) []byte

AppendSnapshotAck encodes m onto dst in wire format without allocating when dst has capacity.

func AppendSnapshotDelta

func AppendSnapshotDelta(dst []byte, m *SnapshotDelta) []byte

AppendSnapshotDelta encodes m onto dst in wire format without allocating when dst has capacity.

func AppendSnapshotFull

func AppendSnapshotFull(dst []byte, m *SnapshotFull) []byte

AppendSnapshotFull encodes m onto dst in wire format without allocating when dst has capacity.

func AppendSnapshotFullPart

func AppendSnapshotFullPart(dst []byte, m *SnapshotFullPart) []byte

AppendSnapshotFullPart encodes m onto dst in wire format without allocating when dst has capacity.

func AppendTransportFrame

func AppendTransportFrame(dst []byte, m *TransportFrame) []byte

AppendTransportFrame encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPAckPayload

func AppendUDPAckPayload(dst []byte, m *UDPAckPayload) []byte

AppendUDPAckPayload encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPDatagramType

func AppendUDPDatagramType(dst []byte, v UDPDatagramType) []byte

AppendUDPDatagramType appends v to dst in wire format.

func AppendUDPFragmentPayload

func AppendUDPFragmentPayload(dst []byte, m *UDPFragmentPayload) []byte

AppendUDPFragmentPayload encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPPackedAck

func AppendUDPPackedAck(dst []byte, m *UDPPackedAck) []byte

AppendUDPPackedAck encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPPackedItem

func AppendUDPPackedItem(dst []byte, m *UDPPackedItem) []byte

AppendUDPPackedItem encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPPackedPayload

func AppendUDPPackedPayload(dst []byte, m *UDPPackedPayload) []byte

AppendUDPPackedPayload encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPPeerFrame

func AppendUDPPeerFrame(dst []byte, m *UDPPeerFrame) []byte

AppendUDPPeerFrame encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPPingPayload

func AppendUDPPingPayload(dst []byte, m *UDPPingPayload) []byte

AppendUDPPingPayload encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPReliablePayload

func AppendUDPReliablePayload(dst []byte, m *UDPReliablePayload) []byte

AppendUDPReliablePayload encodes m onto dst in wire format without allocating when dst has capacity.

func AppendUDPSealedDatagram

func AppendUDPSealedDatagram(dst []byte, m *UDPSealedDatagram) []byte

AppendUDPSealedDatagram encodes m onto dst in wire format without allocating when dst has capacity.

func ApplyEntityRecord

func ApplyEntityRecord(dst, delta *EntityRecord)

ApplyEntityRecord copies every masked field present in delta into dst, reusing dst slice capacities.

func BuiltinFiles

func BuiltinFiles() ([]string, error)

BuiltinFiles returns the sorted file names of the embedded pkg/net wire schemas.

func DecodeChannel

func DecodeChannel(src []byte, v *Channel) (int, error)

DecodeChannel decodes one Channel from src into v, validating that it is a declared enum value.

func DecodeChecksumMsg

func DecodeChecksumMsg(src []byte, m *ChecksumMsg) (int, error)

DecodeChecksumMsg decodes one ChecksumMsg from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeEntityRecord

func DecodeEntityRecord(src []byte, m *EntityRecord) (int, error)

DecodeEntityRecord decodes one EntityRecord from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeHandshakeHello

func DecodeHandshakeHello(src []byte, m *HandshakeHello) (int, error)

DecodeHandshakeHello decodes one HandshakeHello from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeHandshakeMessage

func DecodeHandshakeMessage(src []byte, m *HandshakeMessage) (int, error)

DecodeHandshakeMessage decodes one HandshakeMessage from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeHandshakeReject

func DecodeHandshakeReject(src []byte, m *HandshakeReject) (int, error)

DecodeHandshakeReject decodes one HandshakeReject from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeHandshakeWelcome

func DecodeHandshakeWelcome(src []byte, m *HandshakeWelcome) (int, error)

DecodeHandshakeWelcome decodes one HandshakeWelcome from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeInputBundle

func DecodeInputBundle(src []byte, m *InputBundle) (int, error)

DecodeInputBundle decodes one InputBundle from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeInputFrame

func DecodeInputFrame(src []byte, m *InputFrame) (int, error)

DecodeInputFrame decodes one InputFrame from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeInputSync

func DecodeInputSync(src []byte, m *InputSync) (int, error)

DecodeInputSync decodes one InputSync from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeJoinState

func DecodeJoinState(src []byte, m *JoinState) (int, error)

DecodeJoinState decodes one JoinState from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeJoinStatePart

func DecodeJoinStatePart(src []byte, m *JoinStatePart) (int, error)

DecodeJoinStatePart decodes one JoinStatePart from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeMatchMember

func DecodeMatchMember(src []byte, m *MatchMember) (int, error)

DecodeMatchMember decodes one MatchMember from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeMemberChange

func DecodeMemberChange(src []byte, m *MemberChange) (int, error)

DecodeMemberChange decodes one MemberChange from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeMemberChangeKind

func DecodeMemberChangeKind(src []byte, v *MemberChangeKind) (int, error)

DecodeMemberChangeKind decodes one MemberChangeKind from src into v, validating that it is a declared enum value.

func DecodeMembershipMessage

func DecodeMembershipMessage(src []byte, m *MembershipMessage) (int, error)

DecodeMembershipMessage decodes one MembershipMessage from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeOwnerUpdate

func DecodeOwnerUpdate(src []byte, m *OwnerUpdate) (int, error)

DecodeOwnerUpdate decodes one OwnerUpdate from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayAck

func DecodeRelayAck(src []byte, m *RelayAck) (int, error)

DecodeRelayAck decodes one RelayAck from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayBody

func DecodeRelayBody(src []byte, m *RelayBody) (int, error)

DecodeRelayBody decodes one RelayBody from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayFrame

func DecodeRelayFrame(src []byte, m *RelayFrame) (int, error)

DecodeRelayFrame decodes one RelayFrame from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayMembers

func DecodeRelayMembers(src []byte, m *RelayMembers) (int, error)

DecodeRelayMembers decodes one RelayMembers from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayPacked

func DecodeRelayPacked(src []byte, m *RelayPacked) (int, error)

DecodeRelayPacked decodes one RelayPacked from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayPackedItem

func DecodeRelayPackedItem(src []byte, m *RelayPackedItem) (int, error)

DecodeRelayPackedItem decodes one RelayPackedItem from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayReliable

func DecodeRelayReliable(src []byte, m *RelayReliable) (int, error)

DecodeRelayReliable decodes one RelayReliable from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRelayUnreliable

func DecodeRelayUnreliable(src []byte, m *RelayUnreliable) (int, error)

DecodeRelayUnreliable decodes one RelayUnreliable from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeReplicationMessage

func DecodeReplicationMessage(src []byte, m *ReplicationMessage) (int, error)

DecodeReplicationMessage decodes one ReplicationMessage from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeResyncRequest

func DecodeResyncRequest(src []byte, m *ResyncRequest) (int, error)

DecodeResyncRequest decodes one ResyncRequest from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeRollbackMessage

func DecodeRollbackMessage(src []byte, m *RollbackMessage) (int, error)

DecodeRollbackMessage decodes one RollbackMessage from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeSingleInput

func DecodeSingleInput(src []byte, m *SingleInput) (int, error)

DecodeSingleInput decodes one SingleInput from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeSnapshotAck

func DecodeSnapshotAck(src []byte, m *SnapshotAck) (int, error)

DecodeSnapshotAck decodes one SnapshotAck from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeSnapshotDelta

func DecodeSnapshotDelta(src []byte, m *SnapshotDelta) (int, error)

DecodeSnapshotDelta decodes one SnapshotDelta from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeSnapshotFull

func DecodeSnapshotFull(src []byte, m *SnapshotFull) (int, error)

DecodeSnapshotFull decodes one SnapshotFull from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeSnapshotFullPart

func DecodeSnapshotFullPart(src []byte, m *SnapshotFullPart) (int, error)

DecodeSnapshotFullPart decodes one SnapshotFullPart from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeTransportFrame

func DecodeTransportFrame(src []byte, m *TransportFrame) (int, error)

DecodeTransportFrame decodes one TransportFrame from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPAckPayload

func DecodeUDPAckPayload(src []byte, m *UDPAckPayload) (int, error)

DecodeUDPAckPayload decodes one UDPAckPayload from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPDatagramType

func DecodeUDPDatagramType(src []byte, v *UDPDatagramType) (int, error)

DecodeUDPDatagramType decodes one UDPDatagramType from src into v, validating that it is a declared enum value.

func DecodeUDPFragmentPayload

func DecodeUDPFragmentPayload(src []byte, m *UDPFragmentPayload) (int, error)

DecodeUDPFragmentPayload decodes one UDPFragmentPayload from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPPackedAck

func DecodeUDPPackedAck(src []byte, m *UDPPackedAck) (int, error)

DecodeUDPPackedAck decodes one UDPPackedAck from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPPackedItem

func DecodeUDPPackedItem(src []byte, m *UDPPackedItem) (int, error)

DecodeUDPPackedItem decodes one UDPPackedItem from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPPackedPayload

func DecodeUDPPackedPayload(src []byte, m *UDPPackedPayload) (int, error)

DecodeUDPPackedPayload decodes one UDPPackedPayload from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPPeerFrame

func DecodeUDPPeerFrame(src []byte, m *UDPPeerFrame) (int, error)

DecodeUDPPeerFrame decodes one UDPPeerFrame from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPPingPayload

func DecodeUDPPingPayload(src []byte, m *UDPPingPayload) (int, error)

DecodeUDPPingPayload decodes one UDPPingPayload from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPReliablePayload

func DecodeUDPReliablePayload(src []byte, m *UDPReliablePayload) (int, error)

DecodeUDPReliablePayload decodes one UDPReliablePayload from src into caller-owned storage m without heap allocations once slices have capacity.

func DecodeUDPSealedDatagram

func DecodeUDPSealedDatagram(src []byte, m *UDPSealedDatagram) (int, error)

DecodeUDPSealedDatagram decodes one UDPSealedDatagram from src into caller-owned storage m without heap allocations once slices have capacity.

func DequantizeFixed

func DequantizeFixed(q, scale int64) float64

DequantizeFixed converts a signed fixed-point integer q back to float64 (q / scale) using integer arithmetic only.

func DequantizeFixedUint

func DequantizeFixedUint(q uint64, scale int64) float64

DequantizeFixedUint converts an unsigned fixed-point integer q back to float64 (q / scale) using integer arithmetic only.

func DequantizeFloat

func DequantizeFloat(q uint32, minVal, maxVal float32, bits int) float32

DequantizeFloat reconstructs a float32 from an unsigned quantized integer q in [0, (1<<bits)-1] over [minVal, maxVal] using integer arithmetic only, guaranteeing bit-identical results across architectures.

q == 0 returns minVal exactly and q >= (1<<bits)-1 returns maxVal exactly.

func DiffEntityRecord

func DiffEntityRecord(base, cur *EntityRecord) uint16

DiffEntityRecord returns the presence mask of fields in cur that differ from base, comparing float bit patterns and byte slices directly.

Example

Generated codecs encode into caller-owned slices with AppendX and decode into caller-owned structs with DecodeX, while DiffX and ApplyX compute and apply presence-bitmask deltas.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)

func main() {
	base := wire.EntityRecord{ID: 7, Kind: 1, X: 10, Y: 20}
	cur := base
	cur.X = 14.5
	cur.Props = []byte{0x01, 0x02}

	cur.FieldsMask = wire.DiffEntityRecord(&base, &cur)
	buf := wire.AppendEntityRecord(make([]byte, 0, 64), &cur)

	var decoded wire.EntityRecord
	n, err := wire.DecodeEntityRecord(buf, &decoded)
	if err != nil {
		panic(err)
	}
	wire.ApplyEntityRecord(&base, &decoded)
	fmt.Printf("bytes=%d mask=0x%02x x=%.1f y=%.1f props=%x\n", n, decoded.FieldsMask, base.X, base.Y, base.Props)
}
Output:
bytes=10 mask=0x82 x=14.5 y=20.0 props=0102

func Encode

func Encode(s *Schema) ([]byte, error)

Encode validates s and writes it as canonical, deterministic 2-space YAML prefixed with SchemaComment.

func FrameMessageType

func FrameMessageType(frame DecodedFrame) string

FrameMessageType returns a stable, human-readable message type name for frame (such as "replication.delta", "rollback.single_input", "relay.members", or "raw").

func GenerateGo

func GenerateGo(schema *Schema, opts GenerateOptions) ([]byte, error)

GenerateGo generates deterministic, formatted, zero-allocation Go codec source for schema.

Example

Parse reads a *.wire.yaml schema strictly and GenerateGo writes deterministic Go codecs for it.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)

func main() {
	const src = `version: 1
package: demo
messages:
  - name: Ping
    fields:
      - name: seq
        type: uvarint
        bits: 32
`
	s, err := wire.Parse([]byte(src))
	if err != nil {
		panic(err)
	}
	code, err := wire.GenerateGo(s, wire.GenerateOptions{SourceName: "ping.wire.yaml"})
	if err != nil {
		panic(err)
	}
	fmt.Println(len(code) > 0, s.Messages[0].Name)
}
Output:
true Ping

func GenerateTS

func GenerateTS(schema *Schema, opts TSGenerateOptions) ([]byte, error)

GenerateTS generates deterministic, dependency-free TypeScript codec source for schema.

Example

GenerateTS produces deterministic, dependency-free TypeScript codecs (encodeX, decodeX, plus diffX/applyX for delta masks) from a parsed wire schema.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)

func main() {
	const src = `version: 1
package: demo
messages:
  - name: Ping
    fields:
      - name: seq
        type: uvarint
        bits: 32
      - name: stamp
        type: u64
`
	s, err := wire.Parse([]byte(src))
	if err != nil {
		panic(err)
	}
	code, err := wire.GenerateTS(s, wire.TSGenerateOptions{SourceName: "ping.wire.yaml"})
	if err != nil {
		panic(err)
	}
	fmt.Println(len(code) > 0, s.Messages[0].Name)
}
Output:
true Ping

func GenerateTSIndex

func GenerateTSIndex(schemaFileNames []string) []byte

GenerateTSIndex generates a deterministic barrel index.ts re-exporting runtime.ts and each generated schema module.

func GenerateTSRuntime

func GenerateTSRuntime() []byte

GenerateTSRuntime returns the deterministic, zero-dependency TypeScript runtime module shared by codecs generated with GenerateTS.

func QuantizeFixed

func QuantizeFixed(v float64, scale, minInt, maxInt int64) int64

QuantizeFixed converts v into a signed fixed-point integer round(v * scale), clamped to [minInt, maxInt], using integer arithmetic only. Halfway ties round away from zero.

func QuantizeFixedUint

func QuantizeFixedUint(v float64, scale int64, maxUint uint64) uint64

QuantizeFixedUint converts v into an unsigned fixed-point integer round(v * scale), clamped to [0, maxUint], using integer arithmetic only. Halfway ties round up.

func QuantizeFloat

func QuantizeFloat(v, minVal, maxVal float32, bits int) uint32

QuantizeFloat quantizes v from [minVal, maxVal] into an unsigned integer in [0, (1<<bits)-1] using integer arithmetic only, so every CPU architecture (amd64, arm64, wasm) and cross-language implementation produces identical bytes.

Values at or below minVal (and NaN) quantize to 0; values at or above maxVal quantize to (1<<bits)-1. Halfway ties round up.

Example

QuantizeFloat and DequantizeFloat map float32 values into compact integer bit widths using integer arithmetic only, producing bit-identical bytes on amd64, arm64, and wasm.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)

func main() {
	q := wire.QuantizeFloat(0.25, 0, 1, 8)
	v := wire.DequantizeFloat(q, 0, 1, 8)
	fmt.Printf("q=%d v=%.4f\n", q, v)
}
Output:
q=64 v=0.2510

func TSOutputFileName

func TSOutputFileName(schemaBaseName string) string

TSOutputFileName returns the generated TypeScript file name for a *.wire.yaml schema file name (for example "replication.wire.yaml" -> "replication_wire.ts").

func Validate

func Validate(s *Schema) error

Validate checks a single Schema document. When s.Imports is empty, every enum and message reference must resolve within s; when s.Imports is non-empty, cross-file references are verified by ValidateAll or GenerateGo.

func ValidateAll

func ValidateAll(schemas []*Schema) error

ValidateAll checks a linked set of schemas (such as a directory of *.wire.yaml files in one package), ensuring unique top-level type names, valid and non-overlapping module ID ranges, unique non-retired message IDs across files, and that every cross-file type reference resolves.

Types

type ArraySpec

type ArraySpec struct {
	// Count fixes the array length to a compile-time constant [Count]T; omit or set 0 for a variable-length slice.
	Count int `yaml:"count,omitempty" schema:"minimum=0"`
	// Length sets the element-count prefix for variable-length arrays ("uvarint", "u8", "u16", or "u32"; defaults to "uvarint").
	Length string `yaml:"length,omitempty" schema:"enum=uvarint|u8|u16|u32"`
	// Order overrides the byte order for a multi-byte Length prefix (and as default for elements when OfOrder is omitted).
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Of is the element wire type: a primitive ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "uvarint", "svarint", "bool", "f32") or the name of a declared Enum or Message.
	Of string `yaml:"of" schema:"required,minLength=1"`
	// OfOrder overrides the byte order of multi-byte primitive elements ("be" or "le").
	OfOrder ByteOrder `yaml:"ofOrder,omitempty" schema:"enum=be|le"`
	// OfBits sets the Go integer bit width (8, 16, 32, or 64) when Of is "uvarint" or "svarint".
	OfBits int `yaml:"ofBits,omitempty" schema:"minimum=1,maximum=64"`
	// MaxLength bounds the decoded element count of variable-length arrays (0 means unbounded).
	MaxLength int `yaml:"maxLength,omitempty" schema:"minimum=0"`
}

ArraySpec configures a fixed-count ([N]T) or length-prefixed ([]T) array field.

type BitReader

type BitReader struct {
	Src []byte
	Off int
	// contains filtered or unexported fields
}

BitReader reads MSB-first bit-packed values from a byte slice without heap allocations.

func (*BitReader) Align

func (r *BitReader) Align() error

Align discards the remaining unread low bits of the current partial byte, returning ErrNonZeroPadding if any padding bit is non-zero.

func (*BitReader) ReadBits

func (r *BitReader) ReadBits(n uint8) (uint64, error)

ReadBits reads n bits (1..64) in MSB-first order.

type BitWriter

type BitWriter struct {
	Dst []byte
	// contains filtered or unexported fields
}

BitWriter appends MSB-first bit-packed values to a caller-owned byte slice without heap allocations.

func (*BitWriter) Flush

func (w *BitWriter) Flush() []byte

Flush pads any remaining partial byte with zero low bits and returns the updated destination slice.

func (*BitWriter) WriteBits

func (w *BitWriter) WriteBits(v uint64, n uint8)

WriteBits appends the lowest n bits (1..64) of v in MSB-first order.

type ByteOrder

type ByteOrder string

ByteOrder selects multi-byte wire endianness.

const (
	// OrderBig encodes multi-byte integers and floats most-significant byte first.
	OrderBig ByteOrder = "be"
	// OrderLittle encodes multi-byte integers and floats least-significant byte first.
	OrderLittle ByteOrder = "le"
)

type CaptureStats

type CaptureStats struct {
	TotalPackets   int         `yaml:"total_packets" json:"total_packets"`
	TotalBytes     int64       `yaml:"total_bytes" json:"total_bytes"`
	SendPackets    int         `yaml:"send_packets" json:"send_packets"`
	SendBytes      int64       `yaml:"send_bytes" json:"send_bytes"`
	RecvPackets    int         `yaml:"recv_packets" json:"recv_packets"`
	RecvBytes      int64       `yaml:"recv_bytes" json:"recv_bytes"`
	DurationNS     int64       `yaml:"duration_ns" json:"duration_ns"`
	DeltaCount     int         `yaml:"delta_count" json:"delta_count"`
	DeltaBytes     int64       `yaml:"delta_bytes" json:"delta_bytes"`
	MeanDeltaBytes float64     `yaml:"mean_delta_bytes" json:"mean_delta_bytes"`
	ByType         []TypeStats `yaml:"by_type" json:"by_type"`
	ByPeer         []PeerStats `yaml:"by_peer" json:"by_peer"`
}

CaptureStats summarizes traffic decoded from a capture stream.

type Channel

type Channel uint8

Channel selects delivery semantics on a pkg/net Transport.

const (
	// Reliable, ordered delivery.
	ChannelReliableOrdered Channel = 0
	// Best-effort, unordered delivery.
	ChannelUnreliable Channel = 1
	// Best-effort newest-only delivery that drops packets older than the newest delivered.
	ChannelUnreliableSequenced Channel = 2
)

func (Channel) Valid

func (v Channel) Valid() bool

Valid reports whether v is a declared Channel value.

type ChecksumMsg

type ChecksumMsg struct {
	Tick     uint32
	Peer     uint32
	Checksum uint64
}

ChecksumMsg carries a peer's 64-bit simulation state checksum for tick following tag 12.

func (*ChecksumMsg) AppendWire

func (m *ChecksumMsg) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*ChecksumMsg) DecodeWire

func (m *ChecksumMsg) DecodeWire(src []byte) (int, error)

DecodeWire decodes one ChecksumMsg from src into m without heap allocations once slices have capacity.

type DecodedEnum

type DecodedEnum struct {
	Name  string
	Value uint64
}

DecodedEnum holds a validated wire enum value together with its declared schema member name. It marshals as Name in both YAML and JSON while retaining Value for lossless re-encoding.

func (DecodedEnum) MarshalJSON

func (e DecodedEnum) MarshalJSON() ([]byte, error)

MarshalJSON encodes DecodedEnum as its member name.

func (DecodedEnum) MarshalYAML

func (e DecodedEnum) MarshalYAML() (any, error)

MarshalYAML encodes DecodedEnum as its member name.

type DecodedField

type DecodedField struct {
	Name  string
	Value any
}

DecodedField is one decoded wire field in exact schema declaration order.

type DecodedFrame

type DecodedFrame struct {
	// Index is the 0-based frame index in the input stream.
	Index int `yaml:"index" json:"index"`
	// T is the capture timestamp in nanoseconds (nil for raw stdin frames).
	T *int64 `yaml:"t,omitempty" json:"t,omitempty"`
	// Dir is "send" or "recv" (empty for raw stdin frames).
	Dir string `yaml:"dir,omitempty" json:"dir,omitempty"`
	// Peer is the remote peer ID (nil for raw stdin frames).
	Peer *uint32 `yaml:"peer,omitempty" json:"peer,omitempty"`
	// Size is the payload size in bytes.
	Size int `yaml:"size" json:"size"`
	// Layers lists the decoded protocol layers from outermost to innermost.
	Layers []DecodedLayer `yaml:"layers" json:"layers"`
}

DecodedFrame is one fully decoded packet from a capture stream or raw frame input.

type DecodedLayer

type DecodedLayer struct {
	// Layer names the protocol layer ("transport", "udp_sealed", "relay", "replication", "rollback", "membership", "handshake", a custom schema package, or "raw").
	Layer string `yaml:"layer" json:"layer"`
	// Union names the discriminated wire union when this layer was selected by a union discriminator.
	Union string `yaml:"union,omitempty" json:"union,omitempty"`
	// Version is the nibble discriminator high value when a nibble union matched (for example 2 for ReplicationMessage).
	Version *uint8 `yaml:"version,omitempty" json:"version,omitempty"`
	// Case is the matched union case name (for example "full", "delta", "single_input", "reliable").
	Case string `yaml:"case,omitempty" json:"case,omitempty"`
	// Tag is the union discriminator tag value when Union is set.
	Tag *uint64 `yaml:"tag,omitempty" json:"tag,omitempty"`
	// Message is the wire message name decoded at this layer.
	Message string `yaml:"message,omitempty" json:"message,omitempty"`
	// Fields holds the decoded fields of Message in exact wire order. Trailing payload bytes peeled into the next layer are omitted here; ReencodeLayers restores them from the inner layer.
	Fields DecodedObject `yaml:"fields,omitempty" json:"fields,omitempty"`
	// Raw holds raw undecoded bytes when Layer is "raw".
	Raw WireBytes `yaml:"raw,omitempty" json:"raw,omitempty"`
	// Resolved holds the full resulting entity states after applying a SnapshotDelta to its tracked peer baseline when ResolveDeltas is enabled.
	Resolved []DecodedObject `yaml:"resolved,omitempty" json:"resolved,omitempty"`
	// BaselineMissing is true when ResolveDeltas was enabled on a SnapshotDelta whose baseline_tick had not been captured yet.
	BaselineMissing bool `yaml:"baseline_missing,omitempty" json:"baseline_missing,omitempty"`

	// PayloadField records which trailing bytes field of Message was peeled off into the next layer so ReencodeLayers can reconstruct exact wire bytes.
	PayloadField string `yaml:"-" json:"-"`
}

DecodedLayer is one protocol layer decoded from a packet using the wire schemas.

type DecodedMask

type DecodedMask struct {
	Mask   uint64
	Fields DecodedObject
}

DecodedMask holds a presence-bitmask group's raw bitmask and present fields in bit order.

func (DecodedMask) MarshalJSON

func (m DecodedMask) MarshalJSON() ([]byte, error)

MarshalJSON encodes DecodedMask as a JSON object with "mask" followed by its present fields.

func (DecodedMask) MarshalYAML

func (m DecodedMask) MarshalYAML() (any, error)

MarshalYAML encodes DecodedMask as a YAML mapping with "mask" followed by its present fields.

type DecodedObject

type DecodedObject []DecodedField

DecodedObject is an ordered list of decoded wire fields that marshals as a YAML mapping or JSON object in wire field order.

func (DecodedObject) Get

func (o DecodedObject) Get(name string) (any, bool)

Get returns the value of the named field and whether it was present.

func (DecodedObject) MarshalJSON

func (o DecodedObject) MarshalJSON() ([]byte, error)

MarshalJSON encodes DecodedObject as an ordered JSON object.

func (DecodedObject) MarshalYAML

func (o DecodedObject) MarshalYAML() (any, error)

MarshalYAML encodes DecodedObject as an ordered YAML mapping.

func (*DecodedObject) Set

func (o *DecodedObject) Set(name string, value any)

Set updates an existing field's value in place or appends a new field.

func (DecodedObject) Without

func (o DecodedObject) Without(name string) DecodedObject

Without returns a shallow copy of o omitting the named field.

type DecodedPayload

type DecodedPayload struct {
	Schema  string        `yaml:"schema" json:"schema"`
	Union   string        `yaml:"union,omitempty" json:"union,omitempty"`
	Case    string        `yaml:"case,omitempty" json:"case,omitempty"`
	Tag     *uint64       `yaml:"tag,omitempty" json:"tag,omitempty"`
	Version *uint8        `yaml:"version,omitempty" json:"version,omitempty"`
	Message string        `yaml:"message" json:"message"`
	Fields  DecodedObject `yaml:"fields,omitempty" json:"fields,omitempty"`
}

DecodedPayload holds a nested bytes field (such as EntityRecord.props) that was further decoded using a custom wire schema.

type DecodedUnion

type DecodedUnion struct {
	Schema    string
	Union     string
	HasHigh   bool
	HighName  string
	HighValue uint8
	Case      string
	Tag       uint64
	Message   string
	Fields    DecodedObject
}

DecodedUnion holds a dynamically decoded union envelope and its selected member message.

type Discriminator

type Discriminator struct {
	// Type selects the discriminator wire encoding: "u8", "u16", "uvarint", or "nibble" (a 1-byte high/low bit split).
	Type string `yaml:"type" schema:"required,enum=u8|u16|uvarint|nibble"`
	// Order overrides the byte order when Type is "u16" ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// HighBits is the width in bits (1..7) of the high field when Type is "nibble" (defaults to 4).
	HighBits int `yaml:"highBits,omitempty" schema:"minimum=1,maximum=7"`
	// HighName is the Go field name for the high bits when Type is "nibble" (defaults to "version").
	HighName string `yaml:"highName,omitempty"`
	// HighValue is the expected constant value of the high bits when Type is "nibble" (for example, 2 for replication v2).
	HighValue uint8 `yaml:"highValue,omitempty"`
	// LowName is the logical name of the low tag bits when Type is "nibble" (defaults to "type").
	LowName string `yaml:"lowName,omitempty"`
}

Discriminator configures the leading tag encoding of a Union.

type EntityRecord

type EntityRecord struct {
	ID         uint32
	FieldsMask uint16
	Kind       uint16
	X          float32
	Y          float32
	VX         float32
	VY         float32
	Rotation   float32
	Flags      uint32
	Props      []byte
	Owner      uint32
}

EntityRecord encodes one entity ID and its presence-masked ComponentState and Owner fields in replication v3.

func (*EntityRecord) AppendWire

func (m *EntityRecord) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*EntityRecord) DecodeWire

func (m *EntityRecord) DecodeWire(src []byte) (int, error)

DecodeWire decodes one EntityRecord from src into m without heap allocations once slices have capacity.

type Enum

type Enum struct {
	// Name is the Go type name of the enum, in PascalCase.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Doc is an optional comment emitted on the generated Go type.
	Doc string `yaml:"doc,omitempty"`
	// Type is the underlying integer wire type ("u8", "u16", "u32", "u64", or "uvarint").
	Type string `yaml:"type" schema:"required,enum=u8|u16|u32|u64|uvarint"`
	// Order overrides the schema byte order for multi-byte enum types ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Values lists the enum's named members and their wire integers.
	Values []EnumValue `yaml:"values" schema:"required,minItems=1"`
}

Enum defines a named integer enumeration on the wire.

type EnumValue

type EnumValue struct {
	// Name is the member name, appended to the enum type name to form the Go constant.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Value is the unsigned wire integer value of the member.
	Value uint64 `yaml:"value"`
	// Doc is an optional comment emitted on the generated Go constant.
	Doc string `yaml:"doc,omitempty"`
}

EnumValue is one named member of an Enum.

type Field

type Field struct {
	// Name is the field name (snake_case or lowerCamelCase); codegen converts it to an exported Go field name.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Doc is an optional comment emitted on the generated Go struct field.
	Doc string `yaml:"doc,omitempty"`
	// Type is a built-in wire type ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "uvarint", "svarint", "bool", "f32", "qfloat", "fixed", "bytes", "string", "array", "bits", "mask") or the name of a declared Enum or Message.
	Type string `yaml:"type" schema:"required,minLength=1"`
	// Order overrides the message/schema byte order for multi-byte primitives, length prefixes, or mask integers ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Bits specifies the bit width for "bits" fields (1..64) or the Go integer width (8, 16, 32, or 64) for "uvarint"/"svarint" fields.
	Bits int `yaml:"bits,omitempty" schema:"minimum=1,maximum=64"`
	// Const fixes an unsigned integer, bits, or enum wire field to a single constant value written on encode and verified on decode.
	Const *uint64 `yaml:"const,omitempty"`
	// QFloat configures an integer-quantized float32 field when Type is "qfloat".
	QFloat *QFloatSpec `yaml:"qfloat,omitempty"`
	// Fixed configures an integer-scaled fixed-point float64 field when Type is "fixed".
	Fixed *FixedSpec `yaml:"fixed,omitempty"`
	// Length configures the length encoding for "bytes" and "string" fields ("uvarint", "u8", "u16", "u32", or "rest"; defaults to "uvarint").
	Length string `yaml:"length,omitempty" schema:"enum=uvarint|u8|u16|u32|rest"`
	// MaxLength bounds the decoded byte length of variable-length "bytes" and "string" fields (0 means unbounded).
	MaxLength int `yaml:"maxLength,omitempty" schema:"minimum=0"`
	// Array configures a fixed-size or length-prefixed array field when Type is "array".
	Array *ArraySpec `yaml:"array,omitempty"`
	// Mask configures a presence-bitmask group of optional fields when Type is "mask".
	Mask *MaskSpec `yaml:"mask,omitempty"`
}

Field defines one field of a Message or MaskSpec.

type FixedSpec

type FixedSpec struct {
	// Scale is the positive integer scale factor (wire integer equals round(value * Scale)).
	Scale int64 `yaml:"scale" schema:"required,minimum=1"`
	// Type is the underlying integer wire type ("i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "uvarint", or "svarint").
	Type string `yaml:"type" schema:"required,enum=i8|i16|i32|i64|u8|u16|u32|u64|uvarint|svarint"`
	// Order overrides the byte order for multi-byte integer wire types ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
}

FixedSpec configures a fixed-point number stored as an integer scaled by Scale.

type GenerateOptions

type GenerateOptions struct {
	// Package overrides schema.Package when non-empty.
	Package string
	// SourceName is the schema file name shown in the generated header comment.
	SourceName string
	// Self omits the runtime package import and references runtime helpers unqualified, for files generated inside pkg/net/wire itself.
	Self bool
	// RuntimeImport overrides DefaultRuntimeImport when Self is false.
	RuntimeImport string
	// ExtraSchemas supplies sibling schemas in the same package whose enums and messages schema references via imports.
	ExtraSchemas []*Schema
}

GenerateOptions configures Go codec generation in GenerateGo.

type HandshakeHello

type HandshakeHello struct {
	Nonce         [16]uint8
	ResumePeer    uint32
	ResumeSecret  [16]uint8
	Token         []byte
	ClientVersion string
}

HandshakeHello is the client-to-server version 2 connection handshake body following tag 0xA1.

func (*HandshakeHello) AppendWire

func (m *HandshakeHello) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*HandshakeHello) DecodeWire

func (m *HandshakeHello) DecodeWire(src []byte) (int, error)

DecodeWire decodes one HandshakeHello from src into m without heap allocations once slices have capacity.

type HandshakeMessage

type HandshakeMessage struct {
	Tag     uint8
	Hello   HandshakeHello
	Welcome HandshakeWelcome
	Reject  HandshakeReject
}

HandshakeMessage is a tag-discriminated version 2 connection handshake message.

func (*HandshakeMessage) AppendWire

func (m *HandshakeMessage) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*HandshakeMessage) DecodeWire

func (m *HandshakeMessage) DecodeWire(src []byte) (int, error)

DecodeWire decodes one HandshakeMessage from src into m without heap allocations once slices have capacity.

type HandshakeReject

type HandshakeReject struct {
	Nonce             [16]uint8
	Code              uint8
	RetryAfterSeconds uint32
	Reason            string
}

HandshakeReject is the server-to-client version 2 rejection body following tag 0xA3.

func (*HandshakeReject) AppendWire

func (m *HandshakeReject) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*HandshakeReject) DecodeWire

func (m *HandshakeReject) DecodeWire(src []byte) (int, error)

DecodeWire decodes one HandshakeReject from src into m without heap allocations once slices have capacity.

type HandshakeWelcome

type HandshakeWelcome struct {
	Nonce   [16]uint8
	Peer    uint32
	Server  uint32
	Resumed bool
	Secret  [16]uint8
	Key     [32]uint8
}

HandshakeWelcome is the server-to-client version 2 acceptance body following tag 0xA2.

func (*HandshakeWelcome) AppendWire

func (m *HandshakeWelcome) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*HandshakeWelcome) DecodeWire

func (m *HandshakeWelcome) DecodeWire(src []byte) (int, error)

DecodeWire decodes one HandshakeWelcome from src into m without heap allocations once slices have capacity.

type InputBundle

type InputBundle struct {
	Inputs []InputFrame
}

InputBundle carries a 1-byte counted list of redundant InputFrames following tag 11.

func (*InputBundle) AppendWire

func (m *InputBundle) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*InputBundle) DecodeWire

func (m *InputBundle) DecodeWire(src []byte) (int, error)

DecodeWire decodes one InputBundle from src into m without heap allocations once slices have capacity.

type InputFrame

type InputFrame struct {
	Tick uint32
	Peer uint32
	Bits uint64
	Axes [2]int16
}

InputFrame is a 20-byte deterministic per-tick player input sample exchanged by lockstep and rollback sessions.

func (*InputFrame) AppendWire

func (m *InputFrame) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*InputFrame) DecodeWire

func (m *InputFrame) DecodeWire(src []byte) (int, error)

DecodeWire decodes one InputFrame from src into m without heap allocations once slices have capacity.

type InputSync

type InputSync struct {
	FrameAdvantage int16
	Inputs         []InputFrame
}

InputSync carries the sender's per-peer frame advantage alongside a 1-byte counted list of redundant InputFrames following tag 15.

func (*InputSync) AppendWire

func (m *InputSync) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*InputSync) DecodeWire

func (m *InputSync) DecodeWire(src []byte) (int, error)

DecodeWire decodes one InputSync from src into m without heap allocations once slices have capacity.

type InspectOptions

type InspectOptions struct {
	// ResolveDeltas tracks per-peer replication baselines across a capture so SnapshotDelta layers include full resolved entity states.
	ResolveDeltas bool
}

InspectOptions configures schema-driven packet inspection.

type Inspector

type Inspector struct {
	// contains filtered or unexported fields
}

Inspector decodes captured packets and raw wire frames layer by layer using a Registry of built-in and optional custom wire schemas, and re-encodes decoded frames back to exact wire bytes.

func NewInspector

func NewInspector(reg *Registry, opts InspectOptions) (*Inspector, error)

NewInspector returns a schema-driven Inspector. When reg is nil, NewRegistry() is called to load the built-in pkg/online/netplay schemas.

Example

NewInspector decodes a captured packet layer by layer using the built-in wire schemas and re-encodes it back to the exact original bytes.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)

func main() {
	ins, err := wire.NewInspector(nil, wire.InspectOptions{})
	if err != nil {
		panic(err)
	}
	payload := wire.AppendReplicationMessage(nil, &wire.ReplicationMessage{
		Tag: wire.ReplicationMessageTagAck,
		Ack: wire.SnapshotAck{Epoch: 1, Tick: 42},
	})
	frame := ins.InspectCaptureRecord(0, 0, "send", 1, uint8(wire.ChannelUnreliable), 1, payload)
	reencoded, err := ins.ReencodePayload(frame)
	if err != nil {
		panic(err)
	}
	fmt.Println(wire.FrameMessageType(frame), len(frame.Layers), len(reencoded) == len(payload))
}
Output:
replication.ack 2 true

func (*Inspector) ComputeStats

func (ins *Inspector) ComputeStats(frames []DecodedFrame) CaptureStats

ComputeStats aggregates message-type counts, per-peer counts, and mean delta size across frames.

func (*Inspector) DecodeRawFrameText

func (ins *Inspector) DecodeRawFrameText(text string) ([]byte, error)

DecodeRawFrameText parses a standalone hex (optional 0x prefix, optional spaces) or base64 (standard or URL, padded or unpadded) frame string into raw bytes.

func (*Inspector) InspectCaptureRecord

func (ins *Inspector) InspectCaptureRecord(index int, t int64, dir string, peer uint32, ch uint8, seq uint32, payload []byte) DecodedFrame

InspectCaptureRecord decodes one captured transport packet into a layered DecodedFrame. The transport layer is populated from ch and seq using transport.wire.yaml, and payload is decoded layer by layer using the wire discriminators.

func (*Inspector) InspectRawFrame

func (ins *Inspector) InspectRawFrame(index int, raw []byte) DecodedFrame

InspectRawFrame decodes a standalone raw wire frame (such as hex or base64 read from stdin) into a layered DecodedFrame.

func (*Inspector) ReencodeLayers

func (ins *Inspector) ReencodeLayers(layers []DecodedLayer) ([]byte, error)

ReencodeLayers re-encodes a stack of decoded layers from innermost to outermost back into wire bytes using the wire schemas.

func (*Inspector) ReencodePayload

func (ins *Inspector) ReencodePayload(frame DecodedFrame) ([]byte, error)

ReencodePayload re-encodes the transport payload of a capture-decoded DecodedFrame (skipping the synthetic outer transport layer when present). For frames decoded via InspectRawFrame, it re-encodes all layers from outermost to innermost.

func (*Inspector) Registry

func (ins *Inspector) Registry() *Registry

Registry returns the schema registry backing this inspector.

type JoinState

type JoinState struct {
	Tick    uint32
	Members []MatchMember
	Inputs  []InputFrame
	State   []byte
}

JoinState is the reassembled blob sent by the host to a joining peer at its join tick.

func (*JoinState) AppendWire

func (m *JoinState) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*JoinState) DecodeWire

func (m *JoinState) DecodeWire(src []byte) (int, error)

DecodeWire decodes one JoinState from src into m without heap allocations once slices have capacity.

type JoinStatePart

type JoinStatePart struct {
	Part  uint16
	Parts uint16
	Data  []byte
}

JoinStatePart is one fragment of a serialized JoinState following tag 14.

func (*JoinStatePart) AppendWire

func (m *JoinStatePart) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*JoinStatePart) DecodeWire

func (m *JoinStatePart) DecodeWire(src []byte) (int, error)

DecodeWire decodes one JoinStatePart from src into m without heap allocations once slices have capacity.

type MaskSpec

type MaskSpec struct {
	// Type is the mask integer wire type ("u8", "u16", "u32", or "u64"; defaults to "u8").
	Type string `yaml:"type,omitempty" schema:"enum=u8|u16|u32|u64"`
	// Order overrides the byte order for multi-byte mask types ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Delta, when true, generates Diff<Message>(base, cur) and Apply<Message>(dst, delta) helpers comparing float bit patterns and byte slices directly.
	Delta bool `yaml:"delta,omitempty"`
	// Fields lists the gated fields in bit order (index i corresponds to bit 1<<i).
	Fields []Field `yaml:"fields" schema:"required,minItems=1"`
}

MaskSpec configures a presence-bitmask group that gates its fields in bit order (bit 0, bit 1, ...).

type MatchMember

type MatchMember struct {
	ID       uint32
	From     uint32
	HasLeave bool
	Until    uint32
}

MatchMember is a 13-byte record describing one peer's active tick window inside an assembled JoinState.

func (*MatchMember) AppendWire

func (m *MatchMember) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*MatchMember) DecodeWire

func (m *MatchMember) DecodeWire(src []byte) (int, error)

DecodeWire decodes one MatchMember from src into m without heap allocations once slices have capacity.

type MemberChange

type MemberChange struct {
	Kind   MemberChangeKind
	Peer   uint32
	Tick   uint32
	Inputs []InputFrame
}

MemberChange is a host-issued membership announcement following tag 13.

func (*MemberChange) AppendWire

func (m *MemberChange) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*MemberChange) DecodeWire

func (m *MemberChange) DecodeWire(src []byte) (int, error)

DecodeWire decodes one MemberChange from src into m without heap allocations once slices have capacity.

type MemberChangeKind

type MemberChangeKind uint8

MemberChangeKind identifies whether a membership announcement adds or removes a peer.

const (
	// Peer joins at tick.
	MemberChangeKindJoin MemberChangeKind = 1
	// Peer leaves at tick with declared inputs.
	MemberChangeKindLeave MemberChangeKind = 2
)

func (MemberChangeKind) Valid

func (v MemberChangeKind) Valid() bool

Valid reports whether v is a declared MemberChangeKind value.

type MembershipMessage

type MembershipMessage struct {
	Tag           uint8
	Change        MemberChange
	JoinStatePart JoinStatePart
}

MembershipMessage is a tag-discriminated mid-match membership control packet.

func (*MembershipMessage) AppendWire

func (m *MembershipMessage) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*MembershipMessage) DecodeWire

func (m *MembershipMessage) DecodeWire(src []byte) (int, error)

DecodeWire decodes one MembershipMessage from src into m without heap allocations once slices have capacity.

type Message

type Message struct {
	// ID is the optional explicit router message ID within the schema's Module range. When set, codegen emits a <Name>ID constant.
	ID uint64 `yaml:"id,omitempty" schema:"minimum=16"`
	// Name is the Go struct name of the message, in PascalCase.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Doc is an optional comment emitted on the generated Go struct.
	Doc string `yaml:"doc,omitempty"`
	// Order overrides the schema default byte order for fields of this message ("be" or "le").
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Fields lists the wire fields in exact on-the-wire order.
	Fields []Field `yaml:"fields,omitempty"`
}

Message defines one binary wire message struct and its ordered sequence of fields.

type ModuleSpec

type ModuleSpec struct {
	// Name is the module identifier (and the default Go package name when Schema.Package is omitted).
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Base is the inclusive start of the module's message ID range; it must be at least 16 (above the reserved range 1..15).
	Base uint64 `yaml:"base" schema:"required,minimum=16"`
	// Range is the optional width of the module's ID range [Base, Base+Range); 0 uses DefaultModuleRange (1000).
	Range uint64 `yaml:"range,omitempty" schema:"minimum=1"`
}

ModuleSpec declares a routed message module and its explicit message ID range [Base, Base+Span()).

func (ModuleSpec) Contains

func (m ModuleSpec) Contains(id uint64) bool

Contains reports whether id falls inside [Base, Base+Span()) without uint64 overflow.

func (ModuleSpec) Overlaps

func (m ModuleSpec) Overlaps(other ModuleSpec) bool

Overlaps reports whether m and other share at least one message ID in their [Base, Base+Span()) ranges.

func (ModuleSpec) Span

func (m ModuleSpec) Span() uint64

Span returns m.Range when non-zero, or DefaultModuleRange otherwise.

type NamedSchema

type NamedSchema struct {
	Name   string
	Schema *Schema
}

NamedSchema pairs a parsed wire Schema with its schema file name (for example "transport.wire.yaml") so cross-file TypeScript imports resolve to sibling generated modules.

type OwnerUpdate

type OwnerUpdate struct {
	Epoch     uint32
	AckedTick uint32
	Seq       uint32
	Entity    EntityRecord
}

OwnerUpdate sends a client-owned entity's state from its owning peer to the server in replication v3.

func (*OwnerUpdate) AppendWire

func (m *OwnerUpdate) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*OwnerUpdate) DecodeWire

func (m *OwnerUpdate) DecodeWire(src []byte) (int, error)

DecodeWire decodes one OwnerUpdate from src into m without heap allocations once slices have capacity.

type PeerStats

type PeerStats struct {
	Peer        uint32 `yaml:"peer" json:"peer"`
	Packets     int    `yaml:"packets" json:"packets"`
	Bytes       int64  `yaml:"bytes" json:"bytes"`
	SendPackets int    `yaml:"send_packets" json:"send_packets"`
	SendBytes   int64  `yaml:"send_bytes" json:"send_bytes"`
	RecvPackets int    `yaml:"recv_packets" json:"recv_packets"`
	RecvBytes   int64  `yaml:"recv_bytes" json:"recv_bytes"`
}

PeerStats aggregates packet and byte totals for one peer ID.

type QFloatSpec

type QFloatSpec struct {
	// Min is the finite lower bound mapped to 0.
	Min float64 `yaml:"min"`
	// Max is the finite upper bound mapped to (1<<Bits)-1; it must be strictly greater than Min.
	Max float64 `yaml:"max"`
	// Bits is the quantized bit width, from 1 to 32.
	Bits int `yaml:"bits" schema:"required,minimum=1,maximum=32"`
}

QFloatSpec configures integer-only quantization of a float32 across [Min, Max] into Bits unsigned bits.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry indexes built-in and optional custom wire schemas for schema-driven dynamic decoding and re-encoding.

func NewRegistry

func NewRegistry(custom ...*Schema) (*Registry, error)

NewRegistry builds a Registry loaded with all built-in pkg/online/netplay wire schemas plus any caller-supplied custom schemas.

func (*Registry) CustomMessages

func (r *Registry) CustomMessages() []string

CustomMessages returns the sorted names of messages declared in custom schemas.

func (*Registry) CustomUnions

func (r *Registry) CustomUnions() []string

CustomUnions returns the sorted names of unions declared in custom schemas.

func (*Registry) DecodeMessage

func (r *Registry) DecodeMessage(name string, src []byte) (DecodedObject, int, error)

DecodeMessage dynamically decodes one named Message from src using its schema definition.

func (*Registry) DecodeUnion

func (r *Registry) DecodeUnion(name string, src []byte) (DecodedUnion, int, error)

DecodeUnion dynamically decodes one named Union from src using its discriminator and matched case message.

func (*Registry) EncodeMessage

func (r *Registry) EncodeMessage(name string, obj DecodedObject) ([]byte, error)

EncodeMessage dynamically encodes obj back into wire bytes according to the named Message's schema definition.

func (*Registry) EncodeUnion

func (r *Registry) EncodeUnion(du DecodedUnion) ([]byte, error)

EncodeUnion dynamically encodes du back into wire bytes according to its Union's discriminator and selected case message.

type RelayAck

type RelayAck struct {
	Next uint32
	Mask uint64
}

RelayAck is a cumulative plus selective acknowledgment body following tag 0x03.

func (*RelayAck) AppendWire

func (m *RelayAck) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayAck) DecodeWire

func (m *RelayAck) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayAck from src into m without heap allocations once slices have capacity.

type RelayBody

type RelayBody struct {
	Tag                  uint8
	Unreliable           RelayUnreliable
	Reliable             RelayReliable
	Ack                  RelayAck
	Packed               RelayPacked
	UnreliableCompressed RelayUnreliable
	ReliableCompressed   RelayReliable
}

RelayBody is the tag-discriminated end-to-end body carried inside a peer-addressed RelayFrame.

func (*RelayBody) AppendWire

func (m *RelayBody) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayBody) DecodeWire

func (m *RelayBody) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayBody from src into m without heap allocations once slices have capacity.

type RelayFrame

type RelayFrame struct {
	Peer uint32
	Body []byte
}

RelayFrame is the version 1 outer frame exchanged between a RelayTransport and a Relay server.

func (*RelayFrame) AppendWire

func (m *RelayFrame) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayFrame) DecodeWire

func (m *RelayFrame) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayFrame from src into m without heap allocations once slices have capacity.

type RelayMembers

type RelayMembers struct {
	Epoch uint32
	Peers []uint32
}

RelayMembers is the control body (when RelayFrame.Peer is 0) announcing the sorted members of a relay session.

func (*RelayMembers) AppendWire

func (m *RelayMembers) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayMembers) DecodeWire

func (m *RelayMembers) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayMembers from src into m without heap allocations once slices have capacity.

type RelayPacked

type RelayPacked struct {
	Acks  []RelayAck
	Items []RelayPackedItem
}

RelayPacked carries optional piggybacked acknowledgements and one or more coalesced peer messages following tag 0x04.

func (*RelayPacked) AppendWire

func (m *RelayPacked) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayPacked) DecodeWire

func (m *RelayPacked) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayPacked from src into m without heap allocations once slices have capacity.

type RelayPackedItem

type RelayPackedItem struct {
	Kind    uint8
	Seq     uint32
	Payload []byte
}

RelayPackedItem is one framed end-to-end message inside RelayPacked.

func (*RelayPackedItem) AppendWire

func (m *RelayPackedItem) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayPackedItem) DecodeWire

func (m *RelayPackedItem) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayPackedItem from src into m without heap allocations once slices have capacity.

type RelayReliable

type RelayReliable struct {
	Seq     uint32
	Payload []byte
}

RelayReliable is a peer-to-peer reliable body following tag 0x02.

func (*RelayReliable) AppendWire

func (m *RelayReliable) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayReliable) DecodeWire

func (m *RelayReliable) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayReliable from src into m without heap allocations once slices have capacity.

type RelayUnreliable

type RelayUnreliable struct {
	Seq     uint32
	Payload []byte
}

RelayUnreliable is a peer-to-peer unreliable body following tag 0x01.

func (*RelayUnreliable) AppendWire

func (m *RelayUnreliable) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RelayUnreliable) DecodeWire

func (m *RelayUnreliable) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RelayUnreliable from src into m without heap allocations once slices have capacity.

type ReplicationMessage

type ReplicationMessage struct {
	Tag         uint8
	Version     uint8
	Full        SnapshotFull
	Delta       SnapshotDelta
	Ack         SnapshotAck
	Resync      ResyncRequest
	FullPart    SnapshotFullPart
	OwnerUpdate OwnerUpdate
}

ReplicationMessage is a version 3 replication packet whose leading byte packs protocol version (high nibble = 3) and message type (low nibble = 1..6).

func (*ReplicationMessage) AppendWire

func (m *ReplicationMessage) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*ReplicationMessage) DecodeWire

func (m *ReplicationMessage) DecodeWire(src []byte) (int, error)

DecodeWire decodes one ReplicationMessage from src into m without heap allocations once slices have capacity.

type ResyncRequest

type ResyncRequest struct {
	Epoch uint32
}

ResyncRequest asks the server for a full replication v3 snapshot in epoch.

func (*ResyncRequest) AppendWire

func (m *ResyncRequest) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*ResyncRequest) DecodeWire

func (m *ResyncRequest) DecodeWire(src []byte) (int, error)

DecodeWire decodes one ResyncRequest from src into m without heap allocations once slices have capacity.

type RollbackMessage

type RollbackMessage struct {
	Tag         uint8
	SingleInput SingleInput
	InputBundle InputBundle
	Checksum    ChecksumMsg
	InputSync   InputSync
}

RollbackMessage is a tag-discriminated lockstep or rollback input/checksum packet.

func (*RollbackMessage) AppendWire

func (m *RollbackMessage) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*RollbackMessage) DecodeWire

func (m *RollbackMessage) DecodeWire(src []byte) (int, error)

DecodeWire decodes one RollbackMessage from src into m without heap allocations once slices have capacity.

type Schema

type Schema struct {
	// Version is the schema format version; it must equal CurrentVersion (1).
	Version int `yaml:"version" schema:"required"`
	// Package is the Go package name emitted by game wire when -pkg is not specified. When Module is set, Package may be omitted and defaults to Module.Name.
	Package string `yaml:"package,omitempty" schema:"minLength=1"`
	// Module optionally declares the module identity and explicit message ID range for routed application messages.
	Module *ModuleSpec `yaml:"module,omitempty"`
	// Order is the default byte order for multi-byte fields in this file ("be" or "le"; defaults to "be" when omitted).
	Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
	// Imports lists relative paths to sibling *.wire.yaml files in the same package whose enums and messages this schema references.
	Imports []string `yaml:"imports,omitempty"`
	// Enums declares named integer enumerations validated on decode.
	Enums []Enum `yaml:"enums,omitempty"`
	// Messages declares binary wire message layouts.
	Messages []Message `yaml:"messages,omitempty"`
	// Unions declares tag- or nibble-discriminated message envelopes.
	Unions []Union `yaml:"unions,omitempty"`
	// Retired lists message IDs that were once assigned in this module and must never be reused.
	Retired []uint64 `yaml:"retired,omitempty"`
}

Schema is the root of a versioned *.wire.yaml document describing binary wire enums, messages, and discriminated unions.

func LoadBuiltins

func LoadBuiltins() ([]*Schema, error)

LoadBuiltins parses and validates all embedded pkg/net wire schemas in sorted file order.

func LoadFS

func LoadFS(fsys fs.FS, name string) (*Schema, error)

LoadFS reads, parses, and validates a *.wire.yaml file from fsys.

func LoadFile

func LoadFile(filePath string) (*Schema, error)

LoadFile reads, parses, and validates a *.wire.yaml file from disk.

func LoadSchemaPath

func LoadSchemaPath(path string) ([]*Schema, error)

LoadSchemaPath loads one *.wire.yaml file or every *.wire.yaml file directly under a directory in sorted lexical order.

func Parse

func Parse(data []byte) (*Schema, error)

Parse decodes and validates a *.wire.yaml document, refusing unknown fields, missing or unsupported versions, duplicate keys, and trailing YAML documents.

type SingleInput

type SingleInput struct {
	Input InputFrame
}

SingleInput carries one InputFrame following tag 10.

func (*SingleInput) AppendWire

func (m *SingleInput) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*SingleInput) DecodeWire

func (m *SingleInput) DecodeWire(src []byte) (int, error)

DecodeWire decodes one SingleInput from src into m without heap allocations once slices have capacity.

type SnapshotAck

type SnapshotAck struct {
	Epoch uint32
	Tick  uint32
}

SnapshotAck acknowledges receipt of a replication v3 snapshot tick for epoch.

func (*SnapshotAck) AppendWire

func (m *SnapshotAck) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*SnapshotAck) DecodeWire

func (m *SnapshotAck) DecodeWire(src []byte) (int, error)

DecodeWire decodes one SnapshotAck from src into m without heap allocations once slices have capacity.

type SnapshotDelta

type SnapshotDelta struct {
	Epoch        uint32
	Tick         uint32
	BaselineTick uint32
	Despawns     []uint32
	Updates      []EntityRecord
}

SnapshotDelta is a delta replication v3 world snapshot relative to baseline_tick.

func (*SnapshotDelta) AppendWire

func (m *SnapshotDelta) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*SnapshotDelta) DecodeWire

func (m *SnapshotDelta) DecodeWire(src []byte) (int, error)

DecodeWire decodes one SnapshotDelta from src into m without heap allocations once slices have capacity.

type SnapshotFull

type SnapshotFull struct {
	Epoch    uint32
	Tick     uint32
	Entities []EntityRecord
}

SnapshotFull is a full replication v3 world snapshot following the nibble header byte.

func (*SnapshotFull) AppendWire

func (m *SnapshotFull) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*SnapshotFull) DecodeWire

func (m *SnapshotFull) DecodeWire(src []byte) (int, error)

DecodeWire decodes one SnapshotFull from src into m without heap allocations once slices have capacity.

type SnapshotFullPart

type SnapshotFullPart struct {
	Epoch    uint32
	Tick     uint32
	Index    uint32
	Total    uint32
	Entities []EntityRecord
}

SnapshotFullPart carries one fragment of a split full replication v3 snapshot.

func (*SnapshotFullPart) AppendWire

func (m *SnapshotFullPart) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*SnapshotFullPart) DecodeWire

func (m *SnapshotFullPart) DecodeWire(src []byte) (int, error)

DecodeWire decodes one SnapshotFullPart from src into m without heap allocations once slices have capacity.

type TSGenerateOptions

type TSGenerateOptions struct {
	// SourceName is the schema file name shown in the generated header comment.
	SourceName string
	// RuntimeImport overrides DefaultTSRuntimeImport when EmbedRuntime is false.
	RuntimeImport string
	// EmbedRuntime embeds the shared runtime directly into the generated module instead of importing RuntimeImport.
	EmbedRuntime bool
	// ExtraSchemas supplies sibling schemas referenced via imports, paired with their schema file names.
	ExtraSchemas []NamedSchema
}

TSGenerateOptions configures TypeScript codec generation in GenerateTS.

type TransportFrame

type TransportFrame struct {
	// Channel ID (0=reliable_ordered, 1=unreliable, 2=unreliable_sequenced, 3..66=independent reliable lanes).
	Channel uint8
	Seq     uint32
	Payload []byte
}

TransportFrame is the 5-byte channel and sequence header followed by raw payload bytes used by pkg/net transports.

func (*TransportFrame) AppendWire

func (m *TransportFrame) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*TransportFrame) DecodeWire

func (m *TransportFrame) DecodeWire(src []byte) (int, error)

DecodeWire decodes one TransportFrame from src into m without heap allocations once slices have capacity.

type TypeStats

type TypeStats struct {
	Type    string `yaml:"type" json:"type"`
	Packets int    `yaml:"packets" json:"packets"`
	Bytes   int64  `yaml:"bytes" json:"bytes"`
}

TypeStats aggregates packet and byte totals for one decoded message type.

type UDPAckPayload

type UDPAckPayload struct {
	Next uint32
	Mask uint64
}

UDPAckPayload is the decrypted 12-byte payload of a UDP ack or server_ack datagram (0xBA / 0xBB).

func (*UDPAckPayload) AppendWire

func (m *UDPAckPayload) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPAckPayload) DecodeWire

func (m *UDPAckPayload) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPAckPayload from src into m without heap allocations once slices have capacity.

type UDPDatagramType

type UDPDatagramType uint8

UDPDatagramType identifies the direction and purpose of a sealed UDP session datagram.

const (
	// Client-to-server application datagram (0xB1).
	UDPDatagramTypeData UDPDatagramType = 177
	// Server-to-client application datagram (0xB2).
	UDPDatagramTypeServerData UDPDatagramType = 178
	// Client-to-server keepalive ping (0xB3).
	UDPDatagramTypePing UDPDatagramType = 179
	// Server-to-client keepalive reply (0xB4).
	UDPDatagramTypePong UDPDatagramType = 180
	// Client-to-server session goodbye (0xB5).
	UDPDatagramTypeBye UDPDatagramType = 181
	// UDPTransport pre-shared key peer datagram (0xB6).
	UDPDatagramTypePeerData UDPDatagramType = 182
	// Server-to-client session removal whose payload is the reason (0xB7).
	UDPDatagramTypeKick UDPDatagramType = 183
	// Client-to-server reliable ordered segment or fragment (0xB8).
	UDPDatagramTypeReliable UDPDatagramType = 184
	// Server-to-client reliable ordered segment or fragment (0xB9).
	UDPDatagramTypeServerReliable UDPDatagramType = 185
	// Client-to-server reliable cumulative plus 64-bit SACK acknowledgement (0xBA).
	UDPDatagramTypeAck UDPDatagramType = 186
	// Server-to-client reliable cumulative plus 64-bit SACK acknowledgement (0xBB).
	UDPDatagramTypeServerAck UDPDatagramType = 187
	// Client-to-server fragmented unreliable or sequenced datagram (0xBC).
	UDPDatagramTypeFragment UDPDatagramType = 188
	// Server-to-client fragmented unreliable or sequenced datagram (0xBD).
	UDPDatagramTypeServerFragment UDPDatagramType = 189
	// Server-to-client RTT probe ping (0xBE).
	UDPDatagramTypeServerPing UDPDatagramType = 190
	// Client-to-server RTT probe reply echoing timestamp_ns (0xBF).
	UDPDatagramTypeClientPong UDPDatagramType = 191
	// Client-to-server packed datagram carrying piggybacked acknowledgements and one or more coalesced items (0xC0).
	UDPDatagramTypePacked UDPDatagramType = 192
	// Server-to-client packed datagram carrying piggybacked acknowledgements and one or more coalesced items (0xC1).
	UDPDatagramTypeServerPacked UDPDatagramType = 193
)

func (UDPDatagramType) Valid

func (v UDPDatagramType) Valid() bool

Valid reports whether v is a declared UDPDatagramType value.

type UDPFragmentPayload

type UDPFragmentPayload struct {
	MsgID     uint32
	FragIndex uint16
	FragCount uint16
	Data      []byte
}

UDPFragmentPayload is the decrypted payload of a UDP fragment or server_fragment datagram (0xBC / 0xBD).

func (*UDPFragmentPayload) AppendWire

func (m *UDPFragmentPayload) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPFragmentPayload) DecodeWire

func (m *UDPFragmentPayload) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPFragmentPayload from src into m without heap allocations once slices have capacity.

type UDPPackedAck

type UDPPackedAck struct {
	Channel uint8
	Next    uint32
	Mask    uint64
}

UDPPackedAck is one per-channel cumulative plus 64-bit SACK entry carried inside UDPPackedPayload.

func (*UDPPackedAck) AppendWire

func (m *UDPPackedAck) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPPackedAck) DecodeWire

func (m *UDPPackedAck) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPPackedAck from src into m without heap allocations once slices have capacity.

type UDPPackedItem

type UDPPackedItem struct {
	Type    UDPDatagramType
	Channel uint8
	Body    []byte
}

UDPPackedItem is one framed sub-datagram inside UDPPackedPayload.

func (*UDPPackedItem) AppendWire

func (m *UDPPackedItem) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPPackedItem) DecodeWire

func (m *UDPPackedItem) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPPackedItem from src into m without heap allocations once slices have capacity.

type UDPPackedPayload

type UDPPackedPayload struct {
	Acks  []UDPPackedAck
	Items []UDPPackedItem
}

UDPPackedPayload is the decrypted payload of a UDP packed or server_packed datagram (0xC0 / 0xC1) carrying piggybacked acknowledgements and coalesced items.

func (*UDPPackedPayload) AppendWire

func (m *UDPPackedPayload) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPPackedPayload) DecodeWire

func (m *UDPPackedPayload) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPPackedPayload from src into m without heap allocations once slices have capacity.

type UDPPeerFrame

type UDPPeerFrame struct {
	From    uint32
	Channel Channel
	Seq     uint32
	Payload []byte
}

UDPPeerFrame is the 9-byte peer-to-peer UDP datagram header (sender PeerID plus TransportFrame) used by UDPTransport.

func (*UDPPeerFrame) AppendWire

func (m *UDPPeerFrame) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPPeerFrame) DecodeWire

func (m *UDPPeerFrame) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPPeerFrame from src into m without heap allocations once slices have capacity.

type UDPPingPayload

type UDPPingPayload struct {
	TimestampNs uint64
}

UDPPingPayload is the decrypted 8-byte payload of a UDP ping, pong, server_ping, or client_pong datagram (0xB3 / 0xB4 / 0xBE / 0xBF).

func (*UDPPingPayload) AppendWire

func (m *UDPPingPayload) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPPingPayload) DecodeWire

func (m *UDPPingPayload) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPPingPayload from src into m without heap allocations once slices have capacity.

type UDPReliablePayload

type UDPReliablePayload struct {
	RelSeq    uint32
	FragIndex uint16
	FragCount uint16
	Data      []byte
}

UDPReliablePayload is the decrypted payload of a UDP reliable or server_reliable datagram (0xB8 / 0xB9).

func (*UDPReliablePayload) AppendWire

func (m *UDPReliablePayload) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPReliablePayload) DecodeWire

func (m *UDPReliablePayload) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPReliablePayload from src into m without heap allocations once slices have capacity.

type UDPSealedDatagram

type UDPSealedDatagram struct {
	Type UDPDatagramType
	Peer uint32
	Seq  uint32
	// Channel ID in bits 0..6 (0=reliable_ordered, 1=unreliable, 2=unreliable_sequenced, 3..66=independent reliable lanes); bit 7 (0x80) marks a raw deflate-compressed payload.
	Channel uint8
	// ChaCha20-Poly1305 ciphertext followed by the 16-byte Poly1305 authentication tag.
	Sealed []byte
}

UDPSealedDatagram is a ChaCha20-Poly1305 AEAD UDP datagram with a 10-byte cleartext header (type, peer, seq, channel) authenticated as associated data followed by ciphertext and a 16-byte Poly1305 tag.

func (*UDPSealedDatagram) AppendWire

func (m *UDPSealedDatagram) AppendWire(dst []byte) []byte

AppendWire encodes m onto dst in wire format without allocating when dst has capacity.

func (*UDPSealedDatagram) DecodeWire

func (m *UDPSealedDatagram) DecodeWire(src []byte) (int, error)

DecodeWire decodes one UDPSealedDatagram from src into m without heap allocations once slices have capacity.

type Union

type Union struct {
	// Name is the Go struct name of the union envelope, in PascalCase.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Doc is an optional comment emitted on the generated Go struct.
	Doc string `yaml:"doc,omitempty"`
	// Discriminator configures how the leading tag (and optional nibble-split version) is encoded on the wire.
	Discriminator Discriminator `yaml:"discriminator" schema:"required"`
	// Cases maps discriminator tags to member messages.
	Cases []UnionCase `yaml:"cases" schema:"required,minItems=1"`
}

Union defines a discriminated message envelope selecting one of Cases by a leading tag or nibble-split header byte.

type UnionCase

type UnionCase struct {
	// Name is the Go field name inside the union struct (defaults to Message when omitted).
	Name string `yaml:"name,omitempty"`
	// Tag is the discriminator tag value selecting this case.
	Tag uint64 `yaml:"tag"`
	// Message is the name of the Message encoded after the discriminator.
	Message string `yaml:"message" schema:"required,minLength=1"`
	// Doc is an optional comment emitted on the generated tag constant.
	Doc string `yaml:"doc,omitempty"`
}

UnionCase binds one discriminator tag value to a Message inside a Union.

type WireBytes

type WireBytes []byte

WireBytes holds raw wire bytes in a dynamically decoded message. It marshals as a standard base64 string in both YAML and JSON.

func (WireBytes) MarshalJSON

func (b WireBytes) MarshalJSON() ([]byte, error)

MarshalJSON encodes WireBytes as a standard base64 JSON string.

func (WireBytes) MarshalYAML

func (b WireBytes) MarshalYAML() (any, error)

MarshalYAML encodes WireBytes as a standard base64 string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL