harvest/game/scripts/coop_link.gd
Forrest 39f9d15cfe Co-op voice/session work, config retune, net budget tool, overhaul plan
Snapshot of in-progress work before the alien overhaul so worker
worktrees branch from current code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:35:53 -04:00

199 lines
5.8 KiB
GDScript

class_name CoopLink
extends RefCounted
## The wire between the two machines of a co-op game (CoopSession talks only to this). send()
## delivers one message (a kind and a Variant) to the other side, reliably (in order, never
## lost) or not (may be dropped; for the snapshots and the partner's input, which the next one
## replaces). received is emitted on the other side.
## Messages over COMPRESS_OVER bytes go out compressed (kind "z": [size, zstd bytes]) and are
## unpacked by receive(). GD-Sync compresses its packets only after encrypting them, which saves
## nothing, so this is the only compression co-op traffic gets.
## GDSyncLink is the real one (GD-Sync, LAN or online). CoopLink.pair() makes two loopback links
## for tests: messages go through var_to_bytes / bytes_to_var like on the wire, and are delivered
## when the receiving side polls. Every link counts what it sends; unreliable messages over
## UNRELIABLE_LIMIT bytes are counted as too big (GD-Sync splits datagrams at 1200 bytes).
signal received(kind: String, data: Variant)
const UNRELIABLE_LIMIT := 1100
const COMPRESS_OVER := 256
## The largest message receive() unpacks (bytes, uncompressed).
const UNPACK_LIMIT := 1 << 20
var sent_messages: int = 0
var sent_bytes: int = 0
## The largest unreliable message so far (bytes) and how many were over the limit.
var largest_unreliable: int = 0
var oversized: int = 0
## kind -> [messages, bytes] sent (bytes as sent, after compression).
var sent_kinds := {}
## Set when the other side went away.
var closed := false
func send(kind: String, data: Variant, reliable: bool) -> void:
var label := kind
var bytes := var_to_bytes([kind, data])
var size := bytes.size()
if size > COMPRESS_OVER:
var packed := bytes.compress(FileAccess.COMPRESSION_ZSTD)
if packed.size() + 16 < size:
kind = "z"
data = [size, packed]
size = var_to_bytes([kind, data]).size()
var tally: Array = sent_kinds.get(label, [0, 0])
tally[0] += 1
tally[1] += size
sent_kinds[label] = tally
sent_messages += 1
sent_bytes += size
if not reliable:
largest_unreliable = maxi(largest_unreliable, size)
if size > UNRELIABLE_LIMIT:
oversized += 1
_deliver(kind, data, reliable)
## Messages of a kind sent so far.
func sent_count(kind: String) -> int:
return int(sent_kinds.get(kind, [0, 0])[0])
## A message from the other side (unpacked if it came compressed): emits received.
func receive(kind: String, data: Variant) -> void:
if kind == "z":
var m: Variant = _unpack(data)
if m == null:
return
kind = String(m[0])
data = m[1]
received.emit(kind, data)
## Delivers what has arrived (loopback links; GD-Sync delivers on its own).
func poll() -> void:
pass
func close() -> void:
closed = true
func _deliver(_kind: String, _data: Variant, _reliable: bool) -> void:
pass
static func _unpack(data: Variant) -> Variant:
if not (data is Array) or (data as Array).size() != 2 or not (data[1] is PackedByteArray):
return null
var size := int(data[0])
if size <= 0 or size > UNPACK_LIMIT:
return null
var bytes := (data[1] as PackedByteArray).decompress(size, FileAccess.COMPRESSION_ZSTD)
if bytes.size() != size:
return null
var m: Variant = bytes_to_var(bytes)
if not (m is Array) or (m as Array).size() != 2 or not (m[0] is String):
return null
return m
# --- Packing: the binary messages (CoopSession's snapshots, RemoteControls' input) -----------
static func reader(bytes: PackedByteArray) -> StreamPeerBuffer:
var b := StreamPeerBuffer.new()
b.data_array = bytes
return b
## A length in centimeters (s16: up to 327 m either way).
static func put_cm(b: StreamPeerBuffer, v: float) -> void:
b.put_16(clampi(roundi(v * 100.0), -32768, 32767))
static func get_cm(b: StreamPeerBuffer) -> float:
return b.get_16() / 100.0
static func put_v3(b: StreamPeerBuffer, v: Vector3) -> void:
put_cm(b, v.x)
put_cm(b, v.y)
put_cm(b, v.z)
static func get_v3(b: StreamPeerBuffer) -> Vector3:
var x := get_cm(b)
var y := get_cm(b)
return Vector3(x, y, get_cm(b))
## An angle in radians (s16).
static func put_angle(b: StreamPeerBuffer, a: float) -> void:
b.put_16(roundi(wrapf(a, -PI, PI) * 10000.0))
static func get_angle(b: StreamPeerBuffer) -> float:
return b.get_16() / 10000.0
## A timer in centiseconds (u16: 0 to 655 s).
static func put_time(b: StreamPeerBuffer, t: float) -> void:
b.put_u16(clampi(roundi(t * 100.0), 0, 65535))
static func get_time(b: StreamPeerBuffer) -> float:
return b.get_u16() / 100.0
## A short text: a length byte, then up to 255 bytes of UTF-8.
static func put_text(b: StreamPeerBuffer, s: String) -> void:
var u := s.to_utf8_buffer()
if u.size() > 255:
u = u.slice(0, 255)
b.put_u8(u.size())
b.put_data(u)
static func get_text(b: StreamPeerBuffer) -> String:
var n := b.get_u8()
if n == 0:
return ""
return (b.get_data(n)[1] as PackedByteArray).get_string_from_utf8()
## Two loopback links, each the other's far end.
static func pair() -> Array[CoopLink]:
var a := Loopback.new()
var b := Loopback.new()
a.other = b
b.other = a
return [a, b]
class Loopback extends CoopLink:
var other: Loopback
## Drops every n-th unreliable message (0 = none), to test that nothing depends on them.
var drop_every: int = 0
var _inbox: Array = []
var _count: int = 0
func _deliver(kind: String, data: Variant, reliable: bool) -> void:
if other == null or other.closed:
return
_count += 1
if not reliable and drop_every > 0 and _count % drop_every == 0:
return
other._inbox.append(var_to_bytes([kind, data])) # as on the wire
func poll() -> void:
var batch := _inbox
_inbox = []
for bytes: PackedByteArray in batch:
var m: Array = bytes_to_var(bytes)
receive(String(m[0]), m[1])
func close() -> void:
closed = true
if other != null:
other.closed = true
other.other = null # the pair refers to each other: break the cycle
other = null