extends SceneTree ## Measures co-op traffic over whole days and nights, for the GD-Sync data allowance. The host's ## farm and the partner's run in one process (as in test_coop.gd) over a loopback link that also ## packs every message the way GD-Sync does online (RequestProcessor.package_requests): the ## remote call's request, the auth stamp on unreliable ones, one packet per tick per channel ## (unreliable ones split at 1200 bytes), AES padding, and the compressed envelope. Reports the ## bytes each side sends to GD-Sync's server, by message kind and by phase, and what voice chat ## adds. The host plays the real night plans; an auto-guard kills an enemy every --kill-every ## seconds (carriers first), and both scarecrows are invulnerable, so every night runs to dawn. ## The partner walks circles all the time (so its input changes, as in play). ## godot --headless --path . --script res://game/tools/net_budget.gd -- --nights=5 ## Options: --nights=5, --day=180 (seconds of each day played; the rest is skipped), ## --kill-every=1.5, --mix=48000 (the microphone's mix rate, for the voice estimate), --fps=60. const DT := 1.0 / 60.0 const P := CampaignController.Phase var host: FarmSim var client: FarmSim var hs: CoopSession var cs: CoopSession var links: Array = [] ## Phase name -> seconds played there. var phase_time := {} var peak_enemies: int = 0 ## GD-Sync's online packing of one side's messages (see the class comment). class WireModel: const CALL_FUNCTION_CACHED := 6 const CLIENT_REQUESTS := 1 const LIMIT := 1200 const CLIENT_ID := 0x2345678 # online client ids are server-given; any 30-bit one sizes the same var reliable: Array = [] # [kind, request] var unreliable: Array = [] var nonce: int = 1 << 40 ## kind -> [messages, plain bytes (var_to_bytes([kind, data])), bytes on the wire] var by_kind := {} ## phase -> bytes on the wire var by_phase := {} var phase := "?" var packets: int = 0 var wire_bytes: int = 0 ## Ciphertext size -> enveloped size (zstd on random bytes). static var _enveloped := {} static var _noise := PackedByteArray() ## A message as sent (kind may be CoopLink's "z" for a compressed one), counted as label. func queue(label: String, kind: String, data: Variant, is_reliable: bool) -> void: var request: Array = [CALL_FUNCTION_CACHED, 3, 7, CLIENT_ID, CLIENT_ID, [kind, data]] var plain := var_to_bytes([kind, data]).size() var t: Array = by_kind.get(label, [0, 0, 0]) t[0] += 1 t[1] += plain by_kind[label] = t (reliable if is_reliable else unreliable).append([label, request]) ## One frame's packets (GD-Sync sends each channel's queue once per frame, at most eight ## unreliable packets). func flush() -> void: if not reliable.is_empty(): _packet(reliable) reliable = [] var n := 0 while not unreliable.is_empty() and n < 8: var fit := 1 while fit < unreliable.size() and _size(unreliable.slice(0, fit + 1), true) <= LIMIT: fit += 1 _packet(unreliable.slice(0, fit), true) unreliable = unreliable.slice(fit) n += 1 func _stamped(request: Array) -> Array: var mac := PackedByteArray() mac.resize(32) nonce += 1 return request + [{"_gdsn": [1, nonce, mac]}] func _size(batch: Array, stamped: bool = false) -> int: var reqs: Array = [] for e: Array in batch: reqs.append(_stamped(e[1]) if stamped else e[1]) var plain := var_to_bytes({CLIENT_REQUESTS: reqs}).size() var cipher := plain + (16 - plain % 16) if not _enveloped.has(cipher): if _noise.is_empty(): _noise.resize(1 << 16) for i in _noise.size(): _noise[i] = randi() & 0xFF # ciphertext: zstd can't shrink it var blob := _noise.slice(0, cipher) if cipher <= _noise.size() else _noise _enveloped[cipher] = var_to_bytes([plain, 0, blob.compress(FileAccess.COMPRESSION_ZSTD)]).size() return _enveloped[cipher] func _packet(batch: Array, stamped: bool = false) -> void: var size := _size(batch, stamped) packets += 1 wire_bytes += size by_phase[phase] = int(by_phase.get(phase, 0)) + size var total := 0 for e: Array in batch: total += var_to_bytes(e[1]).size() for e: Array in batch: var t: Array = by_kind[e[0]] t[2] += roundi(size * float(var_to_bytes(e[1]).size()) / total) class MeterLink extends CoopLink.Loopback: var wire := WireModel.new() var _label := "" func send(kind: String, data: Variant, reliable: bool) -> void: _label = kind super(kind, data, reliable) func _deliver(kind: String, data: Variant, reliable: bool) -> void: wire.queue(_label, kind, data, reliable) super(kind, data, reliable) func _initialize() -> void: _run.call_deferred() func _run() -> void: var nights := 5 var day := 180.0 var kill_every := 1.5 var mix := 48000.0 var fps := 60.0 for a in OS.get_cmdline_user_args(): var arg := String(a) if arg.begins_with("--nights="): nights = int(arg.trim_prefix("--nights=")) elif arg.begins_with("--day="): day = float(arg.trim_prefix("--day=")) elif arg.begins_with("--kill-every="): kill_every = float(arg.trim_prefix("--kill-every=")) elif arg.begins_with("--mix="): mix = float(arg.trim_prefix("--mix=")) elif arg.begins_with("--fps="): fps = float(arg.trim_prefix("--fps=")) await _setup() var a := MeterLink.new() var b := MeterLink.new() a.other = b b.other = a links = [a, b] hs.start_host(host, a, "Ana", "Ben") cs.start_client(client, b, "Ben") _pump(2) var c := host.campaign var kill_wait := kill_every var t0 := Time.get_ticks_msec() while c.state.nights_survived < nights and c.outcome != CampaignController.Outcome.VACATION_COMPLETE: match c.state.phase: P.MORNING: c.begin_day() P.GAME_OVER: print(" game over on night %d: retrying" % c.state.night) c.retry_night() P.DAY: if c.state.phase_time_left > 1.0 and host.config.day_length - c.state.phase_time_left >= day: c.state.phase_time_left = 1.0 # the rest of the day is more of the same for av in host.avatars: av.kit.invulnerable_left = 1.0 var walk := hs.ticks * DT * 0.8 client.local_avatar.body.global_position = Vector3(10.0 + 4.0 * cos(walk), 0.0, -8.0 + 4.0 * sin(walk)) if c.state.phase == P.NIGHT or c.state.phase == P.DAWN: kill_wait -= DT if kill_wait <= 0.0: kill_wait = kill_every _kill_one() var name := String(P.keys()[c.state.phase]) for l: MeterLink in links: l.wire.phase = name phase_time[name] = float(phase_time.get(name, 0.0)) + DT peak_enemies = maxi(peak_enemies, host.enemies.alive_count()) _pump() print("played %d nights (%.0f s of game time) in %.0f s" % [c.state.nights_survived, hs.ticks * DT, (Time.get_ticks_msec() - t0) / 1000.0]) _report(fps, mix) for l: CoopLink in links: l.close() quit(0) func _setup() -> void: var scene := load("res://game/scenes/farm.tscn") as PackedScene var host_farm := scene.instantiate() as Node3D root.add_child(host_farm) var viewport := SubViewport.new() viewport.own_world_3d = true viewport.size = Vector2i(320, 180) var box := SubViewportContainer.new() root.add_child(box) box.add_child(viewport) var client_farm := scene.instantiate() as Node3D viewport.add_child(client_farm) await process_frame await physics_frame host = host_farm.get_node("FarmSim") as FarmSim client = client_farm.get_node("FarmSim") as FarmSim for f: FarmSim in [host, client]: f.set_physics_process(false) f.coop.set_physics_process(false) if f.tutorial != null: f.tutorial.enabled = false client.waves.enabled = false hs = host.coop cs = client.coop func _pump(n: int = 1) -> void: for i in n: for f: FarmSim in [host, client]: for av in f.avatars: if av.body.remote_driven: av.body._follow_net(DT) host.step(DT) hs._physics_process(DT) client.step(DT) cs._physics_process(DT) for l: MeterLink in links: l.wire.flush() ## The auto-guard: a carrier if there is one, else any enemy. func _kill_one() -> void: var es := host.enemies var pick := -1 for d in es.active_count: if es.alive[d] == 0: continue if pick < 0 or (es.carry[d] >= 0 and es.carry[pick] < 0): pick = d if pick >= 0: es.apply_hit(pick, 99) func _report(fps: float, mix: float) -> void: var seconds := hs.ticks * DT print("peak enemies alive: %d; seconds by phase: %s" % [peak_enemies, _rounded(phase_time)]) var total := 0 for side in 2: var w: WireModel = links[side].wire total += w.wire_bytes print("\n%s -> server: %.1f MB, %.1f KB/s average, %d packets (%.0f/s)" % [["Host", "Partner"][side], w.wire_bytes / 1048576.0, w.wire_bytes / 1024.0 / seconds, w.packets, w.packets / seconds]) print(" %-8s %9s %10s %10s %9s %8s" % ["kind", "messages", "plain KB", "wire KB", "KB/s", "share"]) var kinds: Array = w.by_kind.keys() kinds.sort_custom(func(x: String, y: String) -> bool: return w.by_kind[x][2] > w.by_kind[y][2]) for k: String in kinds: var t: Array = w.by_kind[k] print(" %-8s %9d %10.0f %10.0f %9.2f %7.1f%%" % [k, t[0], t[1] / 1024.0, t[2] / 1024.0, t[2] / 1024.0 / seconds, 100.0 * t[2] / w.wire_bytes]) var by_phase := {} for ph: String in w.by_phase: by_phase[ph] = "%.1f KB/s" % (w.by_phase[ph] / 1024.0 / maxf(float(phase_time.get(ph, 1.0)), 0.001)) print(" by phase: %s" % [by_phase]) print("\nBoth sides to the server: %.1f MB in %.1f min of play (%.1f KB/s); if GD-Sync counts the relay out too, double it" % [total / 1048576.0, seconds / 60.0, total / 1024.0 / seconds]) # Voice: GD-Sync's own VoiceChat sent a PackedFloat32Array of the frame's audio, at a quarter # of the mix rate, every frame the microphone peaked over its threshold; CoopVoice sends ADPCM # pieces (measured here on a steady tone, so the gate stays open). var raw := WireModel.new() var samples := PackedFloat32Array() samples.resize(roundi(mix / 4.0 / fps)) var voice := CoopVoice.new() var coded := WireModel.new() var block := roundi(mix / fps) var frames := PackedVector2Array() frames.resize(block) for i in roundi(fps * 10.0): raw.queue("voice", "voice", samples, false) raw.flush() for j in block: var v := 0.2 * sin(TAU * 180.0 * (i * block + j) / mix) frames[j] = Vector2(v, v) for piece in voice.feed(frames, mix): coded.queue("voice", "voice", piece, false) coded.flush() voice.free() print("Voice chat while talking (mix %.0f Hz, %.0f fps), per player talking: %.1f KB/s (%.0f MB an hour); GD-Sync's raw VoiceChat would be %.1f KB/s" % [mix, fps, coded.wire_bytes / 1024.0 / 10.0, coded.wire_bytes / 10.0 * 3600.0 / 1048576.0, raw.wire_bytes / 1024.0 / 10.0]) static func _rounded(d: Dictionary) -> Dictionary: var out := {} for k in d: out[k] = roundi(d[k]) return out