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>
This commit is contained in:
Forrest 2026-10-05 13:35:53 -04:00
parent 2e6638b744
commit 39f9d15cfe
15 changed files with 1394 additions and 339 deletions

View file

@ -2,8 +2,11 @@ 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 20 Hz snapshots and the partner's input, which the next
## one replaces). received is emitted on the other side.
## 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
@ -12,18 +15,35 @@ extends RefCounted
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 size := var_to_bytes([kind, data]).size()
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:
@ -33,6 +53,22 @@ func send(kind: String, data: Variant, reliable: bool) -> void:
_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
@ -46,6 +82,84 @@ 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()
@ -75,7 +189,7 @@ class Loopback extends CoopLink:
_inbox = []
for bytes: PackedByteArray in batch:
var m: Array = bytes_to_var(bytes)
received.emit(String(m[0]), m[1])
receive(String(m[0]), m[1])
func close() -> void:
closed = true

View file

@ -8,22 +8,29 @@ extends Node
##
## Host -> partner
## welcome (reliable, once) the farm state, the phase, tonight's time, the loot, the names
## refused (reliable) the partner's game speaks another PROTOCOL
## batch (reliable, each tick with news) events in order: phase changes (with the state),
## the end of the campaign, sounds, toasts for the partner, loot and arrival news,
## breaches, fear bursts, gather popups, the workbench; enemies removed
## state (reliable, at most STATE_HZ, when it changed) the farm state
## state (reliable, at most STATE_HZ, when it changed) the farm state (the phase clock
## alone isn't a change: it is in every snapshot)
## loot (reliable, at most LOOT_HZ, when it changed) every item
## snap (unreliable, SNAP_HZ) the phase clock, both scarecrows, the animals
## foes (unreliable, SNAP_HZ, in chunks) every enemy, 16 bytes each
## shots (unreliable, SNAP_HZ) the shots in flight
## snap (unreliable, SNAP_HZ) packed bytes: the phase clock, both scarecrows, the
## animals, the shots in flight, and the enemies that are due (as many as fit)
## foes (unreliable, with a snapshot) the due enemies that didn't fit, 16 bytes each
## Partner -> host
## hello (reliable) its player's name
## input (unreliable, INPUT_HZ) its scarecrow's position and facing, held buttons and press
## counts, aim, build mode, the upgrade menu (RemoteControls)
## hello (reliable) its player's name and PROTOCOL
## input (unreliable, up to INPUT_HZ when it changed, else every INPUT_KEEPALIVE) its
## scarecrow's position and facing, held buttons and press counts, aim, build mode,
## the upgrade menu (RemoteControls, packed bytes)
## req (reliable) start the day, start the night early, retry the night, build,
## dismantle, buy an upgrade
## Unreliable messages stay under CoopLink.UNRELIABLE_LIMIT; nothing depends on any single one
## arriving (enemies missed by a snapshot appear in the next; removals are reliable).
## arriving. Enemies go by dead reckoning: the partner moves each one on at the velocity of its
## last record, and the host sends a new record only when that guess drifts (FOE_DRIFT, or the
## velocity, heading, altitude, state, or a hit), at least every FOE_REFRESH seconds, and a
## record sent for a change (or a new enemy) goes out again in the next snapshots in case one is
## lost. Removals are reliable. Large messages go out compressed (CoopLink).
## Voice chat (GD-Sync only, start_voice): a CoopVoice per player, owned by that player's client.
enum Role { SOLO, HOST, CLIENT }
@ -35,12 +42,29 @@ signal ended(reason: String)
## Partner: the first full state arrived; the game is on.
signal welcomed
const SNAP_EVERY := 3 # physics ticks: 20 Hz
const INPUT_EVERY := 2 # 30 Hz
## The wire format: both machines must speak the same one (hello and welcome carry it).
const PROTOCOL := 2
const SNAP_EVERY := 4 # physics ticks: 15 Hz
const INPUT_EVERY := 3 # 20 Hz, when it changed
## Seconds: the partner's input goes out at least this often, changed or not.
const INPUT_KEEPALIVE := 0.25
const STATE_EVERY := 15 # 4 Hz
const LOOT_EVERY := 6 # 10 Hz
const ENEMY_CHUNK := 56
const MAX_SHOTS := 60
## Bytes of packed data in one snapshot or foes message (the wrapping keeps it under
## CoopLink.UNRELIABLE_LIMIT).
const PACK_LIMIT := 1000
const FOE_RECORD := 16
## An enemy record's velocity, in 1/VEL_SCALE m/s (s8: up to 12.7 m/s).
const VEL_SCALE := 10.0
## Dead reckoning: a new record goes out when the partner's guess is this far off (m), its
## velocity this far (m/s), its heading turned past FOE_TURN (cosine: 20 degrees), its altitude
## FOE_ALT_DRIFT off (m), or FOE_REFRESH seconds after the last one.
const FOE_DRIFT := 0.25
const FOE_VEL_DRIFT := 0.75
const FOE_TURN := 0.94
const FOE_ALT_DRIFT := 0.25
const FOE_REFRESH := 1.0
## Partner: seconds without a word from the host before it counts as gone.
const TIMEOUT := 8.0
@ -56,8 +80,15 @@ var quiet: float = 0.0
var voices: Array[CoopVoice] = []
var microphone := true
## Seconds since the session started (physics time).
var clock: float = 0.0
# Host
var _events: Array = []
## Enemy records sent so far (each 16 bytes).
var foe_records: int = 0
## What the partner last got for each enemy: host handle -> [clock, record, times to send again].
var _foe_sent := {}
var _removed: Array = []
var _state_hash: int = 0
var _loot_hash: int = 0
@ -67,6 +98,8 @@ var _map := {} # host enemy handle -> local handle
var _gone := {} # host handles already removed (a late snapshot mustn't bring them back)
var _targets := {} # local handle -> PackedFloat32Array [x, z, hx, hz, vx, vz, alt]
var _sender := RemoteControls.Sender.new()
var _last_input := PackedByteArray()
var _input_age: float = 0.0
var _snap_tick: int = -1
var _structures_json := ""
var _shed_json := ""
@ -95,7 +128,9 @@ func start_host(p_sim: FarmSim, p_link: CoopLink, p_my_name: String, p_partner_n
my_name = p_my_name
partner_name = p_partner_name
ticks = 0
clock = 0.0
quiet = 0.0
_foe_sent.clear()
link.received.connect(_on_message)
sim.avatars[0].player_name = my_name
var a := sim.add_partner(false, partner_name)
@ -104,12 +139,15 @@ func start_host(p_sim: FarmSim, p_link: CoopLink, p_my_name: String, p_partner_n
_tag_all()
_hook(sim.campaign.phase_changed, func(phase: CampaignController.Phase, previous: CampaignController.Phase) -> void:
_events.append(["phase", int(phase), int(previous), sim.campaign.state.to_dict(), sim.campaign.state.phase_time_left])
if phase == CampaignController.Phase.MORNING and sim.partner != null:
_ensure_coop())
if phase == CampaignController.Phase.MORNING:
_foe_sent.clear() # the partner forgets the night's enemies too
if sim.partner != null:
_ensure_coop())
_hook(sim.campaign.campaign_ended, func(outcome: CampaignController.Outcome) -> void:
_events.append(["ended", int(outcome), sim.campaign.state.to_dict()]))
_hook(sim.enemies.enemy_removed, func(h: int, reason: EnemySystem.Removal, x: float, z: float, _c: int, _t: int) -> void:
_removed.append([h, int(reason), x, z]))
_removed.append([h, int(reason), x, z])
_foe_sent.erase(h))
_hook(sim.waves.arrived, func(h: int, at: Vector2) -> void:
var d := sim.enemies.resolve_handle(h)
_events.append(["arrived", sim.enemies.type[d] if d >= 0 else 0, at]))
@ -146,8 +184,11 @@ func start_client(p_sim: FarmSim, p_link: CoopLink, p_my_name: String) -> void:
role = Role.CLIENT
my_name = p_my_name
ticks = 0
clock = 0.0
quiet = 0.0
_is_welcomed = false
_snap_tick = -1
_last_input = PackedByteArray()
link.received.connect(_on_message)
var c := sim.campaign
c.save_path = "" # only the host saves
@ -236,13 +277,14 @@ func partner_speaking() -> bool:
## GD-Sync calls this on the other machine (GDSyncLink).
func net_receive(kind: String, data: Variant) -> void:
if link != null:
link.received.emit(kind, data)
link.receive(kind, data)
func _physics_process(dt: float) -> void:
if role == Role.SOLO or link == null:
return
ticks += 1
clock += dt
quiet += dt
if role == Role.HOST:
link.poll()
@ -256,9 +298,11 @@ func _physics_process(dt: float) -> void:
_hello_wait -= dt
if _hello_wait <= 0.0:
_hello_wait = 1.0
link.send("hello", {"name": my_name}, true)
elif ticks % INPUT_EVERY == 0:
_send_input()
link.send("hello", {"name": my_name, "v": PROTOCOL}, true)
else:
_input_age += dt
if ticks % INPUT_EVERY == 0:
_send_input()
if link.closed or (role == Role.CLIENT and quiet > TIMEOUT):
stop("The host left the game" if link.closed else "Lost the connection to the host")
@ -270,7 +314,10 @@ func _host_tick() -> void:
_send_snapshot()
if ticks % STATE_EVERY == 0:
var d := sim.campaign.state.to_dict()
var left: float = d["phase_time_left"]
d["phase_time_left"] = 0.0 # ticks down all day and night; every snapshot has it
var h := hash(d)
d["phase_time_left"] = left
if h != _state_hash:
_state_hash = h
link.send("state", d, true)
@ -289,32 +336,98 @@ func _host_tick() -> void:
func _welcome() -> Dictionary:
var c := sim.campaign
return {"state": c.state.to_dict(), "phase": int(c.state.phase), "time": c.state.phase_time_left, "outcome": int(c.outcome),
"night_time": sim.waves.night_time, "loot": sim.loot.replica_record(), "host": my_name}
"night_time": sim.waves.night_time, "loot": sim.loot.replica_record(), "host": my_name, "v": PROTOCOL}
## One snapshot: the clock, the scarecrows, the animals, the shots, and the enemies that are due,
## packed; the due enemies that don't fit follow in foes messages.
func _send_snapshot() -> void:
var avs: Array = []
var b := StreamPeerBuffer.new()
b.put_u32(ticks)
b.put_float(sim.campaign.state.phase_time_left)
b.put_float(sim.waves.night_time)
b.put_u8(sim.avatars.size())
for a in sim.avatars:
avs.append(_avatar_record(a))
link.send("snap", {"t": ticks, "time": sim.campaign.state.phase_time_left, "night": sim.waves.night_time, "av": avs,
"an": sim.animals.replica_record()}, false)
_put_avatar(b, a)
var an := sim.animals.replica_record() # x, z, yaw, speed per animal
b.put_u8(an.size() / 4)
for k in range(0, an.size(), 4):
CoopLink.put_cm(b, an[k])
CoopLink.put_cm(b, an[k + 1])
CoopLink.put_angle(b, an[k + 2])
b.put_u8(clampi(roundi(an[k + 3] * 20.0), 0, 255))
var shots := sim.projectiles.replica_record(MAX_SHOTS) # x, z, direction per shot
b.put_u8(shots.size() / 4)
for k in range(0, shots.size(), 4):
CoopLink.put_cm(b, shots[k])
CoopLink.put_cm(b, shots[k + 1])
b.put_8(clampi(roundi(shots[k + 2] * 127.0), -127, 127))
b.put_8(clampi(roundi(shots[k + 3] * 127.0), -127, 127))
var foes := _due_foes()
var n := foes.size() / FOE_RECORD
var fit := mini(n, (PACK_LIMIT - b.get_size() - 2) / FOE_RECORD)
b.put_u16(fit)
b.put_data(foes.slice(0, fit * FOE_RECORD))
link.send("snap", b.data_array, false)
var per := (PACK_LIMIT - 6) / FOE_RECORD
while fit < n:
var take := mini(n - fit, per)
var c := StreamPeerBuffer.new()
c.put_u32(ticks)
c.put_u16(take)
c.put_data(foes.slice(fit * FOE_RECORD, (fit + take) * FOE_RECORD))
link.send("foes", c.data_array, false)
fit += take
## The records of the enemies the partner needs news of (dead reckoning, see the top), noted as
## sent.
func _due_foes() -> PackedByteArray:
var es := sim.enemies
var chunk := PackedByteArray()
var out := PackedByteArray()
for d in es.active_count:
if es.alive[d] == 0:
continue
chunk.append_array(_enemy_bytes(es, d))
if chunk.size() >= ENEMY_CHUNK * 16:
link.send("foes", chunk, false)
chunk = PackedByteArray()
if not chunk.is_empty():
link.send("foes", chunk, false)
link.send("shots", sim.projectiles.replica_record(MAX_SHOTS), false)
var h := es.handle_of(d)
var last: Array = _foe_sent.get(h, [])
var again := 0
if last.is_empty():
again = 2 # a new enemy: in the next two snapshots too
elif int(last[2]) > 0:
again = int(last[2]) - 1
elif _foe_changed(es, d, last[1], clock - float(last[0])):
again = 1
elif clock - float(last[0]) < FOE_REFRESH:
continue
var rec := _enemy_bytes(es, d)
_foe_sent[h] = [clock, rec, again]
out.append_array(rec)
foe_records += 1
return out
## Whether enemy d is off from the partner's guess: its last record r, moved on for age seconds.
func _foe_changed(es: EnemySystem, d: int, r: PackedByteArray, age: float) -> bool:
if r[4] != es.type[d] or r[5] != es.state[d]:
return true
if es.hurt[d] > maxf(r[6] / 255.0 - age * EnemySystem.HURT_FADE, 0.0) + 0.15:
return true # hit again
if absf(es.alt[d] - r[7] / 40.0) > FOE_ALT_DRIFT:
return true
var vx := r.decode_s8(14) / VEL_SCALE
var vz := r.decode_s8(15) / VEL_SCALE
var off := Vector2(es.pos_x[d] - (r.decode_s16(8) / 100.0 + vx * age), es.pos_z[d] - (r.decode_s16(10) / 100.0 + vz * age))
if off.length_squared() > FOE_DRIFT * FOE_DRIFT:
return true
if Vector2(es.vel_x[d] - vx, es.vel_z[d] - vz).length_squared() > FOE_VEL_DRIFT * FOE_VEL_DRIFT:
return true
var head := Vector2(r.decode_s8(12), r.decode_s8(13))
return head.length_squared() > 0.0 and Vector2(es.head_x[d], es.head_z[d]).dot(head.normalized()) < FOE_TURN
static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray:
var b := PackedByteArray()
b.resize(16)
b.resize(FOE_RECORD)
b.encode_s32(0, es.handle_of(d))
b[4] = es.type[d]
b[5] = es.state[d]
@ -324,20 +437,31 @@ static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray:
b.encode_s16(10, clampi(roundi(es.pos_z[d] * 100.0), -32768, 32767))
b.encode_s8(12, clampi(roundi(es.head_x[d] * 127.0), -127, 127))
b.encode_s8(13, clampi(roundi(es.head_z[d] * 127.0), -127, 127))
b.encode_s8(14, clampi(roundi(es.vel_x[d] * 20.0), -127, 127))
b.encode_s8(15, clampi(roundi(es.vel_z[d] * 20.0), -127, 127))
b.encode_s8(14, clampi(roundi(es.vel_x[d] * VEL_SCALE), -127, 127))
b.encode_s8(15, clampi(roundi(es.vel_z[d] * VEL_SCALE), -127, 127))
return b
func _avatar_record(a: Avatar) -> Dictionary:
## A scarecrow in a snapshot: slot, position, facing, speed, alive and patching, health, its
## timers (invulnerable, fear, bomb recharge, patch, gather, repair), the weapon, the channel
## clip and what it is focused on and gathering (names), and the repair's target and progress.
func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
var it := a.interactions
var k := a.kit
return {"s": a.slot, "p": a.body.global_position, "y": a.body.model.rotation.y, "v": a.body.move_strength(),
"a": k.alive, "hp": k.hp(), "inv": k.invulnerable_left, "fl": k.fear_left,
"w": int(a.combat.weapon), "bl": a.combat.bomb_left,
"pt": k.patch_elapsed if k.patching else -1.0, "ch": String(a.body.channel_clip) if a.body.rooted else "",
"fo": String(it.focus.name) if it.focus != null else "", "ga": String(it.gathering.name) if it.gathering != null else "",
"ge": it.gather_elapsed, "rt": it.repair_target, "rp": it.repairing, "re": it.repair_elapsed}
b.put_u8(a.slot)
CoopLink.put_v3(b, a.body.global_position)
CoopLink.put_angle(b, a.body.model.rotation.y)
b.put_u8(clampi(roundi(a.body.move_strength() * 100.0), 0, 255))
b.put_u8((1 if k.alive else 0) | (2 if k.patching else 0))
b.put_u8(clampi(k.hp(), 0, 255))
for t: float in [k.invulnerable_left, k.fear_left, a.combat.bomb_left, k.patch_elapsed, it.gather_elapsed, it.repair_elapsed]:
CoopLink.put_time(b, t)
b.put_u8(int(a.combat.weapon))
CoopLink.put_text(b, String(a.body.channel_clip) if a.body.rooted else "")
CoopLink.put_text(b, String(it.focus.name) if it.focus != null else "")
CoopLink.put_text(b, String(it.gathering.name) if it.gathering != null else "")
b.put_32(it.repair_target)
b.put_32(it.repairing)
func _on_message(kind: String, data: Variant) -> void:
@ -354,20 +478,28 @@ func _host_message(kind: String, data: Variant) -> void:
return
match kind:
"hello":
partner_name = String((data as Dictionary).get("name", partner_name))
var hello := data as Dictionary
partner_name = String(hello.get("name", partner_name))
if int(hello.get("v", 1)) != PROTOCOL:
link.send("refused", {"v": PROTOCOL}, true)
var who := _display(partner_name, "Your friend")
stop()
if sim.toasts != null:
sim.toasts.push("%s has another version of the game: update both to play together" % who, Color(1.0, 0.6, 0.4))
return
a.player_name = partner_name
_tag_all()
if not _welcome_sent:
_welcome_sent = true
_events.clear()
_removed.clear()
_foe_sent.clear() # the partner starts with no enemies
link.send("welcome", _welcome(), true)
"input":
var rec := data as Dictionary
a.remote.apply(rec)
a.body.net_position = rec.get("p", a.body.net_position)
a.body.net_yaw = float(rec.get("y", a.body.net_yaw))
a.body.net_speed = float(rec.get("v", 0.0))
if data is PackedByteArray and a.remote.apply(data):
a.body.net_position = a.remote.position
a.body.net_yaw = a.remote.yaw
a.body.net_speed = a.remote.speed
"req":
_do_request(data as Array)
@ -429,11 +561,15 @@ func _client_message(kind: String, data: Variant) -> void:
"loot":
sim.loot.apply_replica(data as Dictionary, _local_handle)
"snap":
_apply_snap(data as Dictionary)
if data is PackedByteArray:
_apply_snap(data)
"foes":
_apply_foes(data as PackedByteArray)
"shots":
sim.projectiles.apply_replica(data as PackedFloat32Array)
if data is PackedByteArray and (data as PackedByteArray).size() >= 6:
var c := CoopLink.reader(data)
if c.get_u32() >= _snap_tick: # not from an older snapshot than the last
_apply_foes((data as PackedByteArray).slice(6, 6 + c.get_u16() * FOE_RECORD))
"refused":
stop("The host has another version of the game: update both to play together")
"batch":
var b := data as Dictionary
for r: Array in b.get("removed", []):
@ -443,6 +579,9 @@ func _client_message(kind: String, data: Variant) -> void:
func _welcome_received(w: Dictionary) -> void:
if int(w.get("v", 1)) != PROTOCOL:
stop("The host has another version of the game: update both to play together")
return
var c := sim.campaign
partner_name = String(w.get("host", ""))
sim.avatars[0].player_name = partner_name
@ -545,19 +684,55 @@ func _apply_event(e: Array) -> void:
sim.upgrade_panel.open()
func _apply_snap(snap: Dictionary) -> void:
var t := int(snap.get("t", 0))
func _apply_snap(data: PackedByteArray) -> void:
var b := CoopLink.reader(data)
var t := b.get_u32()
if t <= _snap_tick:
return # an older one, out of order
_snap_tick = t
sim.campaign.state.phase_time_left = float(snap["time"])
sim.waves.night_time = float(snap["night"])
for rec: Dictionary in snap["av"]:
var slot := int(rec["s"])
if slot >= sim.avatars.size():
continue
_apply_avatar(sim.avatars[slot], rec)
sim.animals.apply_replica(snap["an"])
sim.campaign.state.phase_time_left = b.get_float()
sim.waves.night_time = b.get_float()
for i in b.get_u8():
var slot := b.get_u8()
var rec := _read_avatar(b)
if slot < sim.avatars.size():
_apply_avatar(sim.avatars[slot], rec)
var an := PackedFloat32Array()
for i in b.get_u8():
var x := CoopLink.get_cm(b)
var z := CoopLink.get_cm(b)
var yaw := CoopLink.get_angle(b)
an.append_array([x, z, yaw, b.get_u8() / 20.0])
sim.animals.apply_replica(an)
var shots := PackedFloat32Array()
for i in b.get_u8():
var x := CoopLink.get_cm(b)
var z := CoopLink.get_cm(b)
var dx := b.get_8() / 127.0
shots.append_array([x, z, dx, b.get_8() / 127.0])
sim.projectiles.apply_replica(shots)
var n := b.get_u16()
var at := b.get_position()
_apply_foes(data.slice(at, at + n * FOE_RECORD))
## A scarecrow from a snapshot (after its slot; see _put_avatar), by the names _apply_avatar uses.
func _read_avatar(b: StreamPeerBuffer) -> Dictionary:
var rec := {"p": CoopLink.get_v3(b), "y": CoopLink.get_angle(b), "v": b.get_u8() / 100.0}
var flags := b.get_u8()
rec["a"] = (flags & 1) != 0
rec["hp"] = b.get_u8()
for key: String in ["inv", "fl", "bl", "pt", "ge", "re"]:
rec[key] = CoopLink.get_time(b)
if (flags & 2) == 0:
rec["pt"] = -1.0 # not patching
rec["w"] = b.get_u8()
rec["ch"] = CoopLink.get_text(b)
rec["fo"] = CoopLink.get_text(b)
rec["ga"] = CoopLink.get_text(b)
rec["rt"] = b.get_32()
rec["rp"] = b.get_32()
return rec
func _apply_avatar(a: Avatar, rec: Dictionary) -> void:
@ -581,9 +756,9 @@ func _apply_avatar(a: Avatar, rec: Dictionary) -> void:
body.die()
k.invulnerable_left = float(rec["inv"])
k.fear_left = float(rec["fl"])
a.combat.bomb_left = float(rec.get("bl", 0.0))
a.combat.bomb_left = float(rec["bl"])
if not a.is_local:
a.combat.show_weapon(int(rec.get("w", 0)))
a.combat.show_weapon(int(rec["w"]))
var pt := float(rec["pt"])
k.patching = pt >= 0.0
k.patch_elapsed = maxf(pt, 0.0)
@ -616,7 +791,7 @@ func _gather_node(node_name: String) -> Node3D:
func _apply_foes(chunk: PackedByteArray) -> void:
var es := sim.enemies
for o in range(0, chunk.size() - 15, 16):
for o in range(0, chunk.size() - FOE_RECORD + 1, FOE_RECORD):
var host := chunk.decode_s32(o)
if _gone.has(host):
continue
@ -634,7 +809,7 @@ func _apply_foes(chunk: PackedByteArray) -> void:
es.state[d] = chunk[o + 5]
es.hurt[d] = chunk[o + 6] / 255.0
var t := PackedFloat32Array([x, z, chunk.decode_s8(o + 12) / 127.0, chunk.decode_s8(o + 13) / 127.0,
chunk.decode_s8(o + 14) / 20.0, chunk.decode_s8(o + 15) / 20.0, chunk[o + 7] / 40.0])
chunk.decode_s8(o + 14) / VEL_SCALE, chunk.decode_s8(o + 15) / VEL_SCALE, chunk[o + 7] / 40.0])
_targets[h] = t
@ -689,6 +864,7 @@ func _replica_tick(dt: float) -> void:
es.vel_x[d] = t[4]
es.vel_z[d] = t[5]
es.alt[d] = lerpf(es.alt[d], t[6], 0.3)
es.hurt[d] = maxf(es.hurt[d] - dt * EnemySystem.HURT_FADE, 0.0) # as on the host, between records
sim.projectiles.advance_replica(dt)
@ -700,19 +876,16 @@ func _reset_world() -> void:
_targets.clear()
## The input record, when it changed or INPUT_KEEPALIVE after the last one (a lost one is
## replaced soon; standing still sends little).
func _send_input() -> void:
var a := sim.local_avatar
var build_on := sim.build.active
var ui := sim.upgrade_panel != null and sim.upgrade_panel.is_open
var rec := _sender.record(a.combat.aim, a.combat.aim_point, int(a.combat.device), build_on, ui)
if sim.local_frozen:
rec["held"] = 0 # a menu is up
rec["p"] = a.body.global_position
rec["y"] = a.body.model.rotation.y
rec["v"] = a.body.move_strength()
rec["weapon"] = int(a.combat.weapon)
rec["ground"] = a.combat.ground_point
link.send("input", rec, false)
var rec := _sender.record(a.combat, a.body, sim.build.active, ui, sim.local_frozen)
if rec != _last_input or _input_age >= INPUT_KEEPALIVE - 0.001: # (sums of 1/60 fall a hair short)
_last_input = rec
_input_age = 0.0
link.send("input", rec, false)
_close_menu_if_needed()

View file

@ -2,18 +2,53 @@ class_name CoopVoice
extends VoiceChat
## Voice chat in co-op: GD-Sync's VoiceChat, one per player at the same path on both machines
## (CoopSession/Voice1 for player 1, Voice2 for player 2). Each is owned by its player's GD-Sync
## client: the owner's microphone is recorded (above GD-Sync's volume threshold) and sent, and
## the other machine plays it on the Voice bus. This adds when the voice was last heard, for the
## "speaking" mark on the partner HUD and the name tag.
## client: the owner's microphone is recorded and sent, and the other machine plays it on the
## Voice bus. GD-Sync's capture and playback are kept; the sending is this class's own: GD-Sync's
## sends the raw samples (32-bit floats) every frame the microphone peaks over a threshold, about
## 60 KB/s. Here the microphone is resampled to RATE and cut into pieces of CHUNK samples (60 ms),
## and each piece of speech goes out as 4-bit IMA ADPCM (encode, decode: 3 + CHUNK / 2 bytes, about
## 6 KB/s while talking). A piece is loud when at least LOUD_PARTS of its four 15 ms parts are
## (RMS over gate_rms), so a click or a knock spread over two pieces doesn't count; the gate opens
## after GATE_OPEN loud pieces in a row, sends the piece before them too (the start of the first
## word), and stays open GATE_HOLD seconds after the last loud piece. Each piece starts with the
## codec's state, so a lost one costs only its own 60 ms.
## This also notes when the voice was last heard, for the "speaking" mark on the partner HUD.
const RATE := 12000
const CHUNK := 720
const GATE_OPEN := 2
const LOUD_PARTS := 2
const GATE_HOLD := 0.4
## Seconds of voice the playback buffer holds (room for a piece that arrives late).
const BUFFER := 0.3
const STEPS: Array[int] = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371,
408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,
10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767]
const INDEX_STEP: Array[int] = [-1, -1, -1, -1, 2, 4, 6, 8]
## Seconds of the game clock when audio last arrived (-1000 = never).
var last_heard: float = -1000.0
## A piece louder than this (RMS, full scale 1) counts as speech.
var gate_rms: float = 0.01
## Pieces sent so far (for tests and the traffic tool).
var pieces_sent: int = 0
# Sending: the resampler (a box filter), the piece being filled, the gate, the codec's state.
var _phase: float = 0.0
var _sum: float = 0.0
var _summed: int = 0
var _piece := PackedFloat32Array()
var _waiting: Array[PackedFloat32Array] = [] # pieces held while the gate is shut
var _loud: int = 0
var _open_left: float = 0.0
var _codec := [0, 0] # predictor, step index
static func make(slot: int) -> CoopVoice:
var v := CoopVoice.new()
v.name = "Voice%d" % (slot + 1)
v.input_volume_threshold = 0.025 # above room noise (GD-Sync's default is 0.01)
var out := AudioStreamPlayer.new()
out.name = "Out"
out.bus = &"Voice"
@ -22,10 +57,189 @@ static func make(slot: int) -> CoopVoice:
return v
func _ready() -> void:
super()
if not Engine.is_editor_hint() and GDSync != null:
GDSync.expose_func(_receive_voice)
func speaking() -> bool:
return Time.get_ticks_msec() / 1000.0 - last_heard < 0.35
func _process_audio(audio: PackedFloat32Array, mixrate: float) -> void:
func mute_microphone() -> void:
super()
_reset_gate()
## Replaces GD-Sync's sending (see the top).
func _process(_delta: float) -> void:
if GDSync == null or not _input_configured or not GDSync.is_gdsync_owner(self):
return
var n := _record_effect.get_frames_available()
if n <= 0:
return
if _muted:
_record_effect.clear_buffer()
return
for piece in feed(_record_effect.get_buffer(n), AudioServer.get_mix_rate()):
GDSync.call_func_relevant_unreliable(_receive_voice, piece)
## Microphone frames (stereo, at mix_rate) in; the encoded pieces to send out, if any.
func feed(frames: PackedVector2Array, mix_rate: float) -> Array[PackedByteArray]:
var out: Array[PackedByteArray] = []
var step := RATE / mix_rate
for f in frames:
_sum += (f.x + f.y) * 0.5
_summed += 1
_phase += step
if _phase < 1.0:
continue
_phase -= 1.0
_piece.append(_sum / _summed)
_sum = 0.0
_summed = 0
if _piece.size() == CHUNK:
_gate(_piece, out)
_piece = PackedFloat32Array()
return out
func _gate(piece: PackedFloat32Array, out: Array[PackedByteArray]) -> void:
var loud := loud_parts(piece, gate_rms) >= LOUD_PARTS
_loud = _loud + 1 if loud else 0
if _open_left <= 0.0:
if _loud < GATE_OPEN:
_waiting.append(piece)
if _waiting.size() > GATE_OPEN:
_waiting.pop_front()
return
for held in _waiting: # the quiet piece before the speech, and its start
out.append(_encode_next(held))
_waiting.clear()
if loud:
_open_left = GATE_HOLD
else:
_open_left -= float(CHUNK) / RATE
out.append(_encode_next(piece))
func _encode_next(piece: PackedFloat32Array) -> PackedByteArray:
pieces_sent += 1
var bytes := encode(piece, _codec)
return bytes
func _reset_gate() -> void:
_waiting.clear()
_loud = 0
_open_left = 0.0
_piece = PackedFloat32Array()
## A piece from the other machine: decoded into the playback buffer.
func _receive_voice(piece: PackedByteArray) -> void:
last_heard = Time.get_ticks_msec() / 1000.0
super(audio, mixrate)
if _output_stream_playback == null:
return
var samples := decode(piece)
var room := mini(_output_stream_playback.get_frames_available(), samples.size())
var frames := PackedVector2Array()
frames.resize(room)
for i in room:
frames[i] = Vector2(samples[i], samples[i])
_output_stream_playback.push_buffer(frames)
## GD-Sync's raw audio (another build's VoiceChat): not played; this one's comes as pieces.
func _process_audio(_audio: PackedFloat32Array, _mixrate: float) -> void:
pass
func _configure_output() -> void:
if _output_configured:
return
_output_configured = true
_output_stream = AudioStreamGenerator.new()
_output_stream.mix_rate = RATE
_output_stream.buffer_length = BUFFER
_output_player.stream = _output_stream
_output_player.play()
_output_stream_playback = _output_player.get_stream_playback()
## How many of the piece's four parts are louder than threshold (RMS).
static func loud_parts(piece: PackedFloat32Array, threshold: float) -> int:
var n := 0
var part := piece.size() / 4
for p in 4:
var sum := 0.0
for i in range(p * part, (p + 1) * part):
sum += piece[i] * piece[i]
if sum / maxi(part, 1) >= threshold * threshold:
n += 1
return n
## IMA ADPCM: the codec's state (predictor, step index) at the start, then two samples a byte
## (low nibble first). state carries over from piece to piece and is updated.
static func encode(samples: PackedFloat32Array, state: Array) -> PackedByteArray:
var predictor: int = state[0]
var index: int = state[1]
var out := PackedByteArray()
out.resize(3 + (samples.size() + 1) / 2)
out.encode_s16(0, predictor)
out[2] = index
for i in samples.size():
var target := clampi(roundi(samples[i] * 32767.0), -32768, 32767)
var step: int = STEPS[index]
var diff := target - predictor
var code := 0
if diff < 0:
code = 8
diff = -diff
var delta := step >> 3
if diff >= step:
code |= 4
diff -= step
delta += step
if diff >= step >> 1:
code |= 2
diff -= step >> 1
delta += step >> 1
if diff >= step >> 2:
code |= 1
delta += step >> 2
predictor = clampi(predictor - delta if code & 8 else predictor + delta, -32768, 32767)
index = clampi(index + INDEX_STEP[code & 7], 0, STEPS.size() - 1)
if i % 2 == 0:
out[3 + i / 2] = code
else:
out[3 + i / 2] |= code << 4
state[0] = predictor
state[1] = index
return out
static func decode(piece: PackedByteArray) -> PackedFloat32Array:
var out := PackedFloat32Array()
if piece.size() < 3:
return out
var predictor := piece.decode_s16(0)
var index := clampi(piece[2], 0, STEPS.size() - 1)
out.resize((piece.size() - 3) * 2)
for i in out.size():
var code := (piece[3 + i / 2] >> (4 * (i % 2))) & 15
var step: int = STEPS[index]
var delta := step >> 3
if code & 4:
delta += step
if code & 2:
delta += step >> 1
if code & 1:
delta += step >> 2
predictor = clampi(predictor - delta if code & 8 else predictor + delta, -32768, 32767)
index = clampi(index + INDEX_STEP[code & 7], 0, STEPS.size() - 1)
out[i] = predictor / 32768.0
return out

View file

@ -19,6 +19,8 @@ enum Aggression { NONE, CONTACT, FIGHT }
const ID_BITS := 16
const ID_MASK := (1 << ID_BITS) - 1
## How fast a hit's flash (hurt) fades, per second.
const HURT_FADE := 4.0
const TYPE_THIEF := 0
const TYPE_CROW := 1
const TYPE_BREAKER := 2
@ -339,7 +341,7 @@ func step(dt: float, scarecrow: Vector2, scarecrow_radius: float) -> void:
var max_corr := cfg.max_correction_per_tick
var g := grid
for i in active_count:
hurt[i] = maxf(hurt[i] - dt * 4.0, 0.0)
hurt[i] = maxf(hurt[i] - dt * HURT_FADE, 0.0)
attack_cd[i] = maxf(attack_cd[i] - dt, 0.0)
slow_left[i] = maxf(slow_left[i] - dt, 0.0)
var x := pos_x[i]

View file

@ -1,14 +1,18 @@
class_name RemoteControls
extends RefCounted
## What a scarecrow played on another machine wants this tick, as the host sees it (co-op,
## CoopSession). The partner's game sends its input every frame: which actions are held, a
## running press count per action (so a press is never lost with a dropped packet: the host
## counts the new ones), its aim (and the ground point a pumpkin bomb would land on), the weapon
## in hand, and whether it is building or has the upgrade menu open. The
## kit classes (Scarecrow, Interactions, ScarecrowCombat) read this instead of the local Input
## when their remote is set.
## CoopSession). The partner's game sends its input record (Sender.record, RECORD_SIZE bytes)
## whenever it changes, and again at least every few frames: which actions are held, a running
## press count per action (so a press is never lost with a dropped packet: the host counts the
## new ones), its aim (and the ground point a pumpkin bomb would land on), the weapon in hand,
## whether it is building or has the upgrade menu open, and where its scarecrow is. The kit
## classes (Scarecrow, Interactions, ScarecrowCombat) read this instead of the local Input when
## their remote is set.
const ACTIONS: Array[StringName] = [&"fire", &"fear", &"patch", &"interact", &"offhand"]
## Held bits, a 16-bit count per action, the aim (2 x s16), the aim and ground points and the
## scarecrow's position (3 x s16 cm each), device, weapon, flags, facing (s16), speed.
const RECORD_SIZE := 1 + 2 * 5 + 4 + 6 + 6 + 3 + 6 + 2 + 1
var aim := Vector2(0.0, -1.0)
var aim_point := Vector3.ZERO
@ -19,6 +23,10 @@ var device: int = 0
var weapon: int = -1
var build_active := false
var ui_open := false
## The partner's scarecrow, as its machine moved it (CoopSession puts this on the host's copy).
var position := Vector3.ZERO
var yaw: float = 0.0
var speed: float = 0.0
var _held := 0
var _presses := RemoteControls.counts()
@ -46,21 +54,29 @@ func take(action: StringName) -> bool:
return true
## The partner's input record (CoopSession): {"held": bits, "presses": counts, "aim": Vector2,
## "aim_point": Vector3, "ground": Vector3, "device", "weapon", "build", "ui"}.
func apply(rec: Dictionary) -> void:
_held = int(rec.get("held", 0))
var p: Variant = rec.get("presses", [])
var counts: Array = Array(p) if p is PackedInt32Array else (p if p is Array else [])
for i in mini(ACTIONS.size(), counts.size()):
_presses[i] = maxi(_presses[i], int(counts[i]))
aim = rec.get("aim", aim)
aim_point = rec.get("aim_point", aim_point)
ground_point = rec.get("ground", ground_point)
device = int(rec.get("device", device))
weapon = int(rec.get("weapon", weapon))
build_active = bool(rec.get("build", false))
ui_open = bool(rec.get("ui", false))
## The partner's input record (Sender.record). False if it isn't one.
func apply(rec: PackedByteArray) -> bool:
if rec.size() != RECORD_SIZE:
return false
var b := CoopLink.reader(rec)
_held = b.get_u8()
for i in ACTIONS.size():
var step := (b.get_u16() - _presses[i]) & 0xFFFF # the counts go round at 65536
if step < 0x8000:
_presses[i] += step
var ax := b.get_16() / 10000.0
aim = Vector2(ax, b.get_16() / 10000.0)
aim_point = CoopLink.get_v3(b)
ground_point = CoopLink.get_v3(b)
device = b.get_u8()
weapon = b.get_8()
var flags := b.get_u8()
build_active = (flags & 1) != 0
ui_open = (flags & 2) != 0
position = CoopLink.get_v3(b)
yaw = CoopLink.get_angle(b)
speed = b.get_u8() / 100.0
return true
## Forget held actions (the partner left, or a new morning).
@ -81,7 +97,9 @@ class Sender:
presses[i] += 1
_was[i] = 1
func record(aim: Vector2, aim_point: Vector3, device: int, build: bool, ui: bool) -> Dictionary:
## The input record (RemoteControls.apply): the actions held now (none while frozen: a menu
## is up), every press so far, and the scarecrow.
func record(combat: ScarecrowCombat, body: PlayerCharacter, build: bool, ui: bool, frozen: bool) -> PackedByteArray:
var bits := 0
for i in RemoteControls.ACTIONS.size():
var down := Input.is_action_pressed(RemoteControls.ACTIONS[i])
@ -90,5 +108,18 @@ class Sender:
if _was[i] == 0: # pressed without an event (simulated input)
presses[i] += 1
_was[i] = 1 if down else 0
return {"held": bits, "presses": presses.duplicate(), "aim": aim, "aim_point": aim_point, "device": device,
"build": build, "ui": ui}
var b := StreamPeerBuffer.new()
b.put_u8(0 if frozen else bits)
for i in RemoteControls.ACTIONS.size():
b.put_u16(presses[i] & 0xFFFF)
b.put_16(clampi(roundi(combat.aim.x * 10000.0), -32767, 32767))
b.put_16(clampi(roundi(combat.aim.y * 10000.0), -32767, 32767))
CoopLink.put_v3(b, combat.aim_point)
CoopLink.put_v3(b, combat.ground_point)
b.put_u8(int(combat.device))
b.put_8(int(combat.weapon))
b.put_u8((1 if build else 0) | (2 if ui else 0))
CoopLink.put_v3(b, body.global_position)
CoopLink.put_angle(b, body.model.rotation.y)
b.put_u8(clampi(roundi(body.move_strength() * 100.0), 0, 255))
return b.data_array