Documentation
¶
Overview ¶
Package worldsync is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package worldsync bridges pkg/entities.World and pkg/online/netplay replication: WorldReplicator spawns registered prefabs on the authoritative server and replicates chosen components through ServerWorld, while WorldMirror spawns matching prefabs on clients, applies synced components with optional interpolation, enforces per-component owner authority rules, verifies prefab table fingerprints, and maintains bidirectional netplay.EntityID <-> entities.Entity mappings.
Index ¶
- Variables
- func Sync[T any](target SyncTarget, mode SyncMode, opts ...SyncOption[T]) error
- func SyncFromDocument(target SyncTarget) error
- type FieldOwner
- type InterpolationMode
- type LayoutCodec
- type ReplicatorConfig
- type SpawnOption
- type SyncMode
- type SyncOption
- func Interpolate[T any]() SyncOption[T]
- func WithCodec[T any](codec LayoutCodec[T]) SyncOption[T]
- func WithEvery[T any](ticks uint32) SyncOption[T]
- func WithInterpolation[T any](mode InterpolationMode) SyncOption[T]
- func WithLerp[T any](fn func(a, b T, alpha float32) T) SyncOption[T]
- func WithName[T any](name string) SyncOption[T]
- func WithOwner[T any](owner FieldOwner) SyncOption[T]
- type SyncTarget
- type WorldMirror
- func (m *WorldMirror) Applied() int
- func (m *WorldMirror) Close()
- func (m *WorldMirror) Count() int
- func (m *WorldMirror) Entity(netID netplay.EntityID) (entities.Entity, bool)
- func (m *WorldMirror) Err() error
- func (m *WorldMirror) Interpolate(renderTick float64)
- func (m *WorldMirror) Kind(netID netplay.EntityID) (uint16, bool)
- func (m *WorldMirror) NetID(e entities.Entity) (netplay.EntityID, bool)
- func (m *WorldMirror) Poll() error
- func (m *WorldMirror) Publish() (int, error)
- func (m *WorldMirror) PublishEntity(netID netplay.EntityID) error
- func (m *WorldMirror) TableHash() uint64
- type WorldReplicator
- func (r *WorldReplicator) Close()
- func (r *WorldReplicator) Count() int
- func (r *WorldReplicator) Despawn(e entities.Entity) bool
- func (r *WorldReplicator) DespawnID(netID netplay.EntityID) bool
- func (r *WorldReplicator) Entity(netID netplay.EntityID) (entities.Entity, bool)
- func (r *WorldReplicator) Kind(netID netplay.EntityID) (uint16, bool)
- func (r *WorldReplicator) NetID(e entities.Entity) (netplay.EntityID, bool)
- func (r *WorldReplicator) SetEntityOwner(e entities.Entity, owner netplay.PeerID) bool
- func (r *WorldReplicator) SetOwner(netID netplay.EntityID, owner netplay.PeerID) bool
- func (r *WorldReplicator) Spawn(kind uint16, spawnData []byte, opts ...SpawnOption) (entities.Entity, netplay.EntityID, error)
- func (r *WorldReplicator) Step(tick uint32) error
- func (r *WorldReplicator) Sync(tick uint32) error
- func (r *WorldReplicator) TableHash() uint64
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig reports an invalid ReplicatorConfig, WorldReplicator, or WorldMirror setup. ErrInvalidConfig = errors.New("worldsync: invalid replicator config") // ErrUnknownKind reports spawning or receiving an entity kind that is not registered in Prefabs. ErrUnknownKind = errors.New("worldsync: unknown prefab kind") // ErrSpawnLimitReached reports a server Spawn that would exceed ReplicatorConfig.SpawnLimit. ErrSpawnLimitReached = errors.New("worldsync: spawn limit reached") // ErrPrefabTableMismatch reports a client snapshot whose prefab table fingerprint differs from the client's registered Prefabs. ErrPrefabTableMismatch = errors.New("worldsync: prefab table mismatch") // ErrCodecNotFound reports syncing a component that has neither a LayoutCodec nor an entities.RegisterCodec registration on the world. ErrCodecNotFound = errors.New("worldsync: component codec not found") // ErrDuplicateComponent reports registering the same component name or Go type twice on one replicator or mirror. ErrDuplicateComponent = errors.New("worldsync: duplicate synced component") // ErrNotOwner reports publishing a client-owned component for an entity this client does not own. ErrNotOwner = errors.New("worldsync: client does not own entity") )
var ErrMalformedPayload = errors.New("worldsync: malformed replication payload")
ErrMalformedPayload reports a corrupt or incompatible worldsync payload inside EntityState.Props.
Functions ¶
func Sync ¶
func Sync[T any](target SyncTarget, mode SyncMode, opts ...SyncOption[T]) error
Sync registers component type T for replication on target (a *WorldReplicator or *WorldMirror).
Codec selection order:
- Explicit binary LayoutCodec[T] supplied with WithCodec.
- Deterministic binary layout codec derived from ReplicatorConfig.Layouts when a matching LayoutField exists.
- Registered entities component codec from entities.RegisterCodec[T] on target's world.
If none exists, Sync returns ErrCodecNotFound. Components not registered with Sync stay local.
func SyncFromDocument ¶
func SyncFromDocument(target SyncTarget) error
SyncFromDocument registers every component declared in target's ReplicatorConfig.Document that is not already registered on target, using its registered entities.RegisterCodec codec on target's world. Call Sync[T] first for any component that needs a binary LayoutCodec or typed interpolation function, then call SyncFromDocument for the rest.
Types ¶
type FieldOwner ¶
type FieldOwner = netplay.LayoutFieldOwner
FieldOwner controls which side may author a synced component.
const ( // OwnerServer means only the authoritative server may author this component (the default). OwnerServer FieldOwner = netplay.OwnerServer // OwnerClient means the entity's owning client may publish updates for this component, // subject to server validation via ReplicatorConfig.OnOwnerComponent. OwnerClient FieldOwner = netplay.OwnerClient )
type InterpolationMode ¶
type InterpolationMode = netplay.LayoutInterpolation
InterpolationMode controls how WorldMirror blends a synced component between snapshots.
const ( InterpolateNone InterpolationMode = netplay.InterpolateNone InterpolateLinear InterpolationMode = netplay.InterpolateLinear InterpolateSlerp InterpolationMode = netplay.InterpolateSlerp InterpolateAngle InterpolationMode = netplay.InterpolateAngle InterpolateStep InterpolationMode = netplay.InterpolateStep )
type LayoutCodec ¶
type LayoutCodec[T any] struct { Encode func(v T) ([]byte, error) Decode func(data []byte) (T, error) }
LayoutCodec encodes and decodes component values of type T into compact wire bytes, such as quantized #1442 layout codecs or custom binary codecs. When provided via WithCodec or derived from ReplicatorConfig.Layouts, it takes precedence over entities.RegisterCodec.
type ReplicatorConfig ¶
type ReplicatorConfig struct {
// Prefabs maps each non-zero wire kind to the prefab spawned on server and clients.
Prefabs map[uint16]*entities.Prefab
// SpawnLimit caps the maximum number of live replicated entities the server may spawn;
// 0 means unlimited, and negative values are refused.
SpawnLimit int
// Layouts optionally provides #1442 netplay.LayoutDocument metadata for quantized binary
// layout codecs and default per-component sync, interpolation, cadence, and owner rules.
Layouts *netplay.LayoutDocument
// Document optionally provides a parsed net/replication.yaml document. When set, its
// kind-to-prefab table is cross-checked against Prefabs, its SpawnLimit applies when
// SpawnLimit is 0, and its component rules act as defaults for Sync and SyncFromDocument.
Document *netplay.ReplicationDocument
// OnSpawnData, when set on a WorldMirror, is invoked with the server's custom spawnData
// immediately after spawning the prefab and applying initial synced components. Returning
// an error destroys the newly spawned entity and reports the error from Poll.
OnSpawnData func(kind uint16, entity entities.Entity, id netplay.EntityID, data []byte) error
// OnOwnerComponent, when set on a WorldReplicator, validates a client-authored update to
// an OwnerClient component after it is decoded onto entity in the server world. Returning
// false restores the previous value and sends an authoritative correction to the owner;
// mutating the component on entity and returning true clamps it and sends the clamped value.
OnOwnerComponent func(peer netplay.PeerID, id netplay.EntityID, entity entities.Entity, component string) bool
}
ReplicatorConfig configures both WorldReplicator (server) and WorldMirror (client). Both ends must register identical kind -> prefab-name tables; mismatches are reported via ErrPrefabTableMismatch rather than spawning the wrong prefab.
func PrefabsFromDocument ¶
func PrefabsFromDocument(doc *netplay.ReplicationDocument, byName map[string]*entities.Prefab) (ReplicatorConfig, error)
PrefabsFromDocument builds a ReplicatorConfig from a parsed net/replication.yaml document and a map of prefab names to *entities.Prefab templates. It returns ErrInvalidConfig if doc is invalid or if any prefab named in doc is missing from byName.
type SpawnOption ¶
type SpawnOption func(*spawnParams)
SpawnOption configures a server-side WorldReplicator.Spawn call.
func WithOwnerPeer ¶
func WithOwnerPeer(peer netplay.PeerID) SpawnOption
WithOwnerPeer assigns initial client ownership to peer when spawning an entity. PeerID(0) (the default) leaves authority with the server.
type SyncMode ¶
type SyncMode = netplay.LayoutSyncMode
SyncMode controls when a synced component is transmitted by WorldReplicator.
const ( // Always replicates the component on every Sync tick (or every N ticks when WithEvery is set). Always SyncMode = netplay.SyncAlways // OnChange replicates the component only when its encoded bytes differ from the last replicated state. OnChange SyncMode = netplay.SyncOnChange // OnSpawn replicates the component once at spawn time (and in full snapshots for late joiners). OnSpawn SyncMode = netplay.SyncSpawn // Never excludes the component from replication so it remains purely local. Never SyncMode = netplay.SyncNever )
type SyncOption ¶
type SyncOption[T any] func(*syncOptions[T])
SyncOption configures a single synced component registered with Sync[T].
func Interpolate ¶
func Interpolate[T any]() SyncOption[T]
Interpolate enables client-side interpolation for this component using InterpolateLinear (or an explicit InterpolationMode via WithInterpolation).
func WithCodec ¶
func WithCodec[T any](codec LayoutCodec[T]) SyncOption[T]
WithCodec registers an explicit binary LayoutCodec[T] (such as a #1442 layout or wire codec) that takes precedence over entities.RegisterCodec[T].
func WithEvery ¶
func WithEvery[T any](ticks uint32) SyncOption[T]
WithEvery limits replication of this component to at most once every ticks Sync ticks.
func WithInterpolation ¶
func WithInterpolation[T any](mode InterpolationMode) SyncOption[T]
WithInterpolation sets the client-side interpolation mode (InterpolateLinear, InterpolateAngle, InterpolateSlerp, InterpolateStep, or InterpolateNone).
func WithLerp ¶
func WithLerp[T any](fn func(a, b T, alpha float32) T) SyncOption[T]
WithLerp enables client-side interpolation with a custom blend function (for example quaternion slerp or custom shortest-arc blending).
func WithName ¶
func WithName[T any](name string) SyncOption[T]
WithName overrides the wire component name (defaults to entities.CodecName[T] or the Go type name).
func WithOwner ¶
func WithOwner[T any](owner FieldOwner) SyncOption[T]
WithOwner sets the per-component authority owner (OwnerServer by default, or OwnerClient).
type SyncTarget ¶
type SyncTarget interface {
// contains filtered or unexported methods
}
SyncTarget is implemented by both *WorldReplicator and *WorldMirror so a game can share one component registration helper between server and client.
type WorldMirror ¶
type WorldMirror struct {
// contains filtered or unexported fields
}
WorldMirror mirrors a netplay.ClientWorld into a client entities.World, spawning registered prefabs by kind, applying synced components with optional interpolation, publishing client-owned components, and reporting unknown kinds or prefab table mismatches rather than silently dropping entities.
func NewWorldMirror ¶
func NewWorldMirror(client *netplay.ClientWorld, world *entities.World, cfg ReplicatorConfig) (*WorldMirror, error)
NewWorldMirror creates a client WorldMirror mirroring client into world.
func (*WorldMirror) Applied ¶
func (m *WorldMirror) Applied() int
Applied returns the number of snapshots applied during the most recent Poll call.
func (*WorldMirror) Close ¶
func (m *WorldMirror) Close()
Close detaches callbacks installed on client and world.
func (*WorldMirror) Count ¶
func (m *WorldMirror) Count() int
Count returns the number of currently mirrored live entities.
func (*WorldMirror) Err ¶
func (m *WorldMirror) Err() error
Err returns the most recent error encountered by Poll, or nil when healthy.
func (*WorldMirror) Interpolate ¶
func (m *WorldMirror) Interpolate(renderTick float64)
Interpolate blends all interpolated synced components of mirrored entities at renderTick across buffered authoritative snapshots and writes the blended values into the client's entities.World. Client-owned components currently owned by this client are not overwritten.
func (*WorldMirror) Kind ¶
func (m *WorldMirror) Kind(netID netplay.EntityID) (uint16, bool)
Kind returns the registered prefab kind of netID.
func (*WorldMirror) Poll ¶
func (m *WorldMirror) Poll() error
Poll drains snapshots from ClientWorld, spawns registered prefabs for new entities, applies synced components, despawns removed entities, and maintains the EntityID <-> entities.Entity mapping. Unknown kinds, prefab table mismatches, decode failures, and OnSpawnData errors are returned explicitly (and stored in Err) rather than silently dropped.
func (*WorldMirror) Publish ¶
func (m *WorldMirror) Publish() (int, error)
Publish encodes and sends all OwnerClient components for every mirrored entity currently owned by this client through ClientWorld.Publish. Returns how many entities were published.
func (*WorldMirror) PublishEntity ¶
func (m *WorldMirror) PublishEntity(netID netplay.EntityID) error
PublishEntity encodes and sends all OwnerClient components of netID from the client's entities.World to the server via ClientWorld.Publish. Returns ErrNotOwner if this client does not currently own netID.
func (*WorldMirror) TableHash ¶
func (m *WorldMirror) TableHash() uint64
TableHash returns the deterministic 64-bit fingerprint of the client's registered prefab table.
type WorldReplicator ¶
type WorldReplicator struct {
// contains filtered or unexported fields
}
WorldReplicator bridges an authoritative entities.World onto a netplay.ServerWorld. It spawns registered prefabs locally and replicates chosen components to connected peers, enforcing ReplicatorConfig.SpawnLimit and per-component owner rules.
Example ¶
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/entities"
"github.com/nsgo-dev/game/pkg/online/netplay"
"github.com/nsgo-dev/game/pkg/online/netplay/worldsync"
)
func main() {
type HP struct {
Value int `json:"value"`
}
hub := netplay.NewLoopbackHub(netplay.LoopbackConfig{})
srvTx := hub.AddPeer(1)
cliTx := hub.AddPeer(2)
srvWorld := entities.NewWorld()
cliWorld := entities.NewWorld()
_ = entities.RegisterCodec[HP](srvWorld, "hp")
_ = entities.RegisterCodec[HP](cliWorld, "hp")
makePrefabs := func() map[uint16]*entities.Prefab {
soldier := entities.NewPrefab("soldier")
entities.With(soldier, HP{Value: 100})
return map[uint16]*entities.Prefab{1: soldier}
}
rep, _ := worldsync.NewWorldReplicator(netplay.NewServerWorld(srvTx), srvWorld, worldsync.ReplicatorConfig{
Prefabs: makePrefabs(),
})
defer rep.Close()
_ = worldsync.Sync[HP](rep, worldsync.OnChange)
mirror, _ := worldsync.NewWorldMirror(netplay.NewClientWorld(cliTx, 1), cliWorld, worldsync.ReplicatorConfig{
Prefabs: makePrefabs(),
})
defer mirror.Close()
_ = worldsync.Sync[HP](mirror, worldsync.OnChange)
srvEntity, netID, _ := rep.Spawn(1, nil)
entities.Set(srvWorld, srvEntity, HP{Value: 85})
_ = rep.Step(1)
hub.Advance(time.Millisecond)
_ = mirror.Poll()
cliEntity, _ := mirror.Entity(netID)
hp, _ := entities.Get[HP](cliWorld, cliEntity)
fmt.Printf("mirrored=%d hp=%d\n", mirror.Count(), hp.Value)
}
Output: mirrored=1 hp=85
func NewWorldReplicator ¶
func NewWorldReplicator(server *netplay.ServerWorld, world *entities.World, cfg ReplicatorConfig) (*WorldReplicator, error)
NewWorldReplicator creates an authoritative WorldReplicator bridging world onto server.
func (*WorldReplicator) Close ¶
func (r *WorldReplicator) Close()
Close detaches lifecycle hooks installed on world and server.
func (*WorldReplicator) Count ¶
func (r *WorldReplicator) Count() int
Count returns the number of currently tracked live replicated entities.
func (*WorldReplicator) Despawn ¶
func (r *WorldReplicator) Despawn(e entities.Entity) bool
Despawn removes e from both ServerWorld and the server's entities.World.
func (*WorldReplicator) DespawnID ¶
func (r *WorldReplicator) DespawnID(netID netplay.EntityID) bool
DespawnID removes netID from ServerWorld and destroys its mapped entity in entities.World.
func (*WorldReplicator) Kind ¶
func (r *WorldReplicator) Kind(netID netplay.EntityID) (uint16, bool)
Kind returns the registered prefab kind of netID.
func (*WorldReplicator) SetEntityOwner ¶
SetEntityOwner transfers client ownership of entity e to owner (PeerID(0) returns authority to server).
func (*WorldReplicator) SetOwner ¶
SetOwner transfers client ownership of netID to owner (PeerID(0) returns authority to server).
func (*WorldReplicator) Spawn ¶
func (r *WorldReplicator) Spawn(kind uint16, spawnData []byte, opts ...SpawnOption) (entities.Entity, netplay.EntityID, error)
Spawn instantiates the registered prefab for kind in the server's entities.World, attaches optional custom spawnData and SpawnOptions (such as WithOwnerPeer or WithSetup), encodes initial synced components, and registers the entity in ServerWorld.
Returns ErrUnknownKind if kind is not registered, or ErrSpawnLimitReached if spawning would exceed ReplicatorConfig.SpawnLimit.
func (*WorldReplicator) Step ¶
func (r *WorldReplicator) Step(tick uint32) error
Step synchronizes entities.World into ServerWorld and then executes ServerWorld.Step(tick), processing incoming client acknowledgments and validated owner component updates and broadcasting full/delta snapshots to connected peers.
func (*WorldReplicator) Sync ¶
func (r *WorldReplicator) Sync(tick uint32) error
Sync reads dirty or due synced components from the server's entities.World and updates ServerWorld. Dead entities are automatically despawned. Call Step to run Sync followed by ServerWorld.Step.
func (*WorldReplicator) TableHash ¶
func (r *WorldReplicator) TableHash() uint64
TableHash returns the deterministic 64-bit fingerprint of the registered prefab table.