class_name CoopSession extends Node ## Co-op for two over a CoopLink (GD-Sync, or loopback in tests). The host's farm is the real ## one: it simulates both scarecrows, every enemy, all the loot, and the campaign, and saves. ## The partner's farm is a replica (FarmSim.replica): it simulates nothing and shows what the ## host sends, except its own scarecrow, which it moves itself (so moving never waits on the ## network) and whose buttons it sends to the host. ## ## 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 (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) 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 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 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 } signal partner_joined(name: String) signal partner_left(name: String) ## Partner: the host went away (or the session was closed). signal ended(reason: String) ## Partner: the first full state arrived; the game is on. signal welcomed ## The wire format: both machines must speak the same one (hello and welcome carry it). 3: #10 ## added a time field and two int32s (the upgrade target/progress) to _put_avatar/_read_avatar's ## per-avatar snapshot record. 4: #16 gave each scarecrow its own pouch (the farm state's ## resources.partner_pouch, FarmState.VERSION 7). const PROTOCOL := 4 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 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 var role: Role = Role.SOLO var sim: FarmSim var link: CoopLink var my_name := "" var partner_name := "" ## Ticks since the session started, and seconds since the other side was last heard. var ticks: int = 0 var quiet: float = 0.0 ## Voice chat: one per player (slot), and whether this machine's microphone is on. 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 var _connections: Array = [] # [Signal, Callable] to undo # Partner 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 := "" var _is_welcomed := false var _welcome_sent := false var _hello_wait: float = 0.0 func is_active() -> bool: return role != Role.SOLO func is_host() -> bool: return role == Role.HOST func is_client() -> bool: return role == Role.CLIENT ## The host's side: the partner (name) is in; their scarecrow joins the farm. func start_host(p_sim: FarmSim, p_link: CoopLink, p_my_name: String, p_partner_name: String) -> void: sim = p_sim link = p_link role = Role.HOST 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) a.body.remote_driven = true a.body.snap_to_net(a.body.global_position, 0.0) _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: _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]) _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])) _hook(sim.loot.loot_event, func(kind: StringName, id: int, at: Vector3) -> void: _events.append(["loot", String(kind), id, at])) _hook(sim.structures.destroyed, func(id: int, type: String, at: Vector3) -> void: _events.append(["destroyed", id, type, at])) for av in sim.avatars: var slot := av.slot _hook(av.kit.fear_used, func(_p: Vector3, _n: int) -> void: _events.append(["fear", slot])) _hook(av.combat.attacked, func(w: ScarecrowCombat.Weapon) -> void: _events.append(["attack", slot, int(w)])) _hook(sim.bombs.thrown, func(from: Vector3, to: Vector3) -> void: _events.append(["bomb", from, to])) _hook(a.interactions.message, func(text: String, color: Color) -> void: _events.append(["toast", text, color])) _hook(a.interactions.workbench_requested, func() -> void: _events.append(["workbench"])) _hook(a.interactions.shed_requested, func() -> void: _events.append(["shed"])) _hook(a.interactions.gathered, func(m: String, amount: int, n: GatherNode) -> void: _events.append(["popup", "+%d %s" % [amount, m], n.global_position + Vector3(0.0, n.top() + 1.4, 0.0), GatherNode.COLORS[m]])) _hook(a.kit.patch_denied, func(missing: Dictionary) -> void: _events.append(["toast", "Not enough straw to patch up: need %s more" % ResourceStore.describe(missing), Color(1.0, 0.8, 0.5)])) if sim.audio != null: sim.audio.forward = func(cue: String, at: Vector3) -> void: _events.append(["sound", cue, at]) _ensure_coop() _state_hash = 0 _loot_hash = 0 _welcome_sent = false # sent when the partner says hello (then it is surely listening) if sim.toasts != null: sim.toasts.push("%s joined: player 2's scarecrow is on the farm" % _display(partner_name, "P2"), Avatar.COLORS[1]) partner_joined.emit(partner_name) ## The partner's side: the farm becomes a replica of the host's; player 2's scarecrow is ours. func start_client(p_sim: FarmSim, p_link: CoopLink, p_my_name: String) -> void: sim = p_sim link = p_link 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 c.remote_request = func(what: String) -> void: _request([what]) sim.replica = true sim.replica_step = _replica_tick var a := sim.add_partner(true, my_name) sim.set_local(a) a.combat.replica = true # it only aims and shows its attacks: the host attacks for it sim.bombs.replica = true var first := sim.avatars[0] first.is_local = false first.body.remote_driven = true sim.build.place_request = func(type: String, x: float, z: float, rot: int) -> void: _request(["place", type, x, z, rot]) sim.build.dismantle_request = func(id: int) -> void: _request(["dismantle", id]) if sim.upgrade_panel != null: sim.upgrade_panel.buy_request = func(id: String) -> void: _request(["buy", id]) if sim.shed_panel != null: sim.shed_panel.buy_request = func(id: String) -> void: _request(["buy", id]) if sim.audio != null: sim.audio.remote_cues = true if sim.tutorial != null: sim.tutorial.enabled = false # the partner joins a game in progress _hello_wait = 0.0 # hello goes out (again every second) until the welcome arrives ## Ends the session on this side. The host carries on alone; the partner's game is left as a ## replica for Main to reset (it reloads the scene). func stop(reason: String = "") -> void: if role == Role.SOLO: return var was := role role = Role.SOLO for pair: Array in _connections: if (pair[0] as Signal).is_connected(pair[1]): (pair[0] as Signal).disconnect(pair[1]) _connections.clear() if link != null: if link.received.is_connected(_on_message): link.received.disconnect(_on_message) link.close() for v in voices: if is_instance_valid(v): v.queue_free() voices.clear() if sim != null and sim.audio != null: sim.audio.forward = Callable() if was == Role.HOST: var gone_name := partner_name var left_behind := sim.remove_partner() # their pouch, now in the shed sim.avatars[0].player_name = "" sim.player.set_tag("", Color.WHITE) if sim.toasts != null: var text := "%s left: you're on your own" % _display(gone_name, "Player 2") if not left_behind.is_empty(): text += " (%s from their pouch is in the shed)" % ResourceStore.describe(left_behind) sim.toasts.push(text, Color(1.0, 0.8, 0.5)) partner_left.emit(gone_name) else: ended.emit(reason) ## Voice chat over GD-Sync: owners[slot] is each player's GD-Sync client id. func start_voice(gdsync: Node, owners: Array, mic_on: bool) -> void: for v in voices: v.queue_free() voices.clear() for slot in owners.size(): var v := CoopVoice.make(slot) add_child(v) gdsync.set_gdsync_owner(v, int(owners[slot])) voices.append(v) set_microphone(mic_on) func set_microphone(on: bool) -> void: microphone = on for v in voices: if on: v.unmute_microphone() else: v.mute_microphone() ## Whether the other player's voice is coming through now. func partner_speaking() -> bool: var other := 1 if role == Role.HOST else 0 return other < voices.size() and voices[other].speaking() ## GD-Sync calls this on the other machine (GDSyncLink). func net_receive(kind: String, data: Variant) -> void: if link != null: 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() if _welcome_sent: _host_tick() elif quiet > TIMEOUT * 2.0: stop("Your friend didn't answer") else: if not _is_welcomed: link.poll() _hello_wait -= dt if _hello_wait <= 0.0: _hello_wait = 1.0 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") # --- Host ----------------------------------------------------------------------------------- func _host_tick() -> void: if ticks % SNAP_EVERY == 0: _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) if ticks % LOOT_EVERY == 0: var rec := sim.loot.replica_record() var h := hash(rec) if h != _loot_hash: _loot_hash = h link.send("loot", rec, true) if not _events.is_empty() or not _removed.is_empty(): link.send("batch", {"events": _events, "removed": _removed}, true) _events = [] _removed = [] 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, "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 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: _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 out := PackedByteArray() for d in es.active_count: if es.alive[d] == 0: continue 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(FOE_RECORD) b.encode_s32(0, es.handle_of(d)) b[4] = es.type[d] b[5] = es.state[d] b[6] = clampi(roundi(es.hurt[d] * 255.0), 0, 255) b[7] = clampi(roundi(es.alt[d] * 40.0), 0, 255) b.encode_s16(8, clampi(roundi(es.pos_x[d] * 100.0), -32768, 32767)) 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] * VEL_SCALE), -127, 127)) b.encode_s8(15, clampi(roundi(es.vel_z[d] * VEL_SCALE), -127, 127)) return b ## A scarecrow in a snapshot: slot, position, facing, speed, alive and patching, health, its ## timers (invulnerable, fear, bomb recharge, patch, gather, repair, structure level-up), the ## weapon, the channel clip and what it is focused on and gathering (names), and the repair's and ## the level-up's target and progress (#10: a structure upgrade is driven the same way as a ## repair -- entirely host-side off the partner's held interact button, nothing in "req" -- so ## this is the only wire change it needs). func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void: var it := a.interactions var k := a.kit 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, it.upgrade_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) b.put_32(it.upgrade_target) b.put_32(it.upgrading) func _on_message(kind: String, data: Variant) -> void: quiet = 0.0 if role == Role.HOST: _host_message(kind, data) elif role == Role.CLIENT: _client_message(kind, data) func _host_message(kind: String, data: Variant) -> void: var a := sim.partner if a == null: return match kind: "hello": 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": 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) func _do_request(r: Array) -> void: var c := sim.campaign var a := sim.partner match String(r[0]): "begin_day": c.begin_day() "start_night_early": c.start_night_early() "retry_night": if c.state.phase == CampaignController.Phase.GAME_OVER: c.retry_night() "place": var type := String(r[1]) var x := float(r[2]) var z := float(r[3]) var rot := int(r[4]) if not StructureSystem.ORDER.has(type): return var why := sim.structures.validate(type, x, z, rot, a.position(), a.slot) if why == "": sim.structures.place(type, x, z, rot, a.slot) # paid from P2's pouch, then the shed _events.append(["toast", "Built a %s" % StructureSystem.NAMES[type].to_lower(), Color(0.6, 1.0, 0.55)]) else: _events.append(["toast", why, Color(1.0, 0.8, 0.5)]) _events.append(["sound", "error", Vector3.INF]) "dismantle": var e := c.state.structure(int(r[1])) if e.is_empty() or a.position().distance_to(Vector2(e["x"], e["z"])) > sim.config.build_range: return var back := sim.structures.dismantle(int(r[1])) _events.append(["toast", "Dismantled the %s%s" % [StructureSystem.NAMES[e["type"]].to_lower(), (": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0)]) "buy": var id := String(r[1]) if Upgrades.shop_of(c.config, id) == "workbench" and (sim.structures == null or not sim.structures.workbench_available()): _events.append(["toast", "The work area isn't available", Color(1.0, 0.8, 0.5)]) return var text := Upgrades.buy(c, id, sim.structures, a.slot) # paid from P2's pouch, then the shed _events.append(["toast", text, Color(0.85, 0.75, 1.0) if text.contains("done:") else Color(1.0, 0.8, 0.5)]) ## Co-op is on for the farm state (after a retry, a new vacation, or a morning). func _ensure_coop() -> void: var s := sim.campaign.state if not s.coop: s.coop = true s.partner_max_hp = s.scarecrow_max_hp s.partner_hp = s.scarecrow_max_hp # --- Partner ---------------------------------------------------------------------------------- func _client_message(kind: String, data: Variant) -> void: match kind: "welcome": _welcome_received(data as Dictionary) "state": _apply_state(data as Dictionary) "loot": sim.loot.apply_replica(data as Dictionary, _local_handle) "snap": if data is PackedByteArray: _apply_snap(data) "foes": 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", []): _remove_foe(int(r[0]), int(r[1])) for e: Array in b.get("events", []): _apply_event(e) 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 _tag_all() var previous := c.state.phase _apply_state(w["state"], true) c.state.phase = int(w["phase"]) as CampaignController.Phase c.state.phase_time_left = float(w["time"]) c.outcome = int(w["outcome"]) as CampaignController.Outcome sim.waves.night_time = float(w["night_time"]) _reset_world() sim.loot.apply_replica(w["loot"], _local_handle) c.phase_changed.emit(c.state.phase, previous) if sim.day_night != null: sim.day_night.snap() _is_welcomed = true if sim.toasts != null: sim.toasts.push("Joined %s's farm: you're player 2" % _display(partner_name, "the host"), Avatar.COLORS[1]) welcomed.emit() ## The host's farm state, keeping this machine's phase until the phase news arrives (in order). func _apply_state(d: Dictionary, everything: bool = false) -> void: var s := FarmState.from_dict(d) if s == null: return var c := sim.campaign if not everything: s.phase = c.state.phase s.phase_time_left = c.state.phase_time_left c.state = s var structures_json := JSON.stringify(d["structures"]) if everything or structures_json != _structures_json: _structures_json = structures_json sim.structures.sync_from_state() sim.animals.update_pen_open() var shed_json := JSON.stringify(d["resources"]) if everything or shed_json != _shed_json: _shed_json = shed_json sim.shed_stock.refresh() if sim.upgrade_panel != null and sim.upgrade_panel.is_open: sim.upgrade_panel.refresh() if sim.shed_panel != null and sim.shed_panel.is_open: sim.shed_panel.refresh() if c.state.phase == CampaignController.Phase.MORNING and sim.review_panel != null: sim.review_panel.refresh() func _apply_event(e: Array) -> void: var c := sim.campaign match String(e[0]): "phase": var previous := c.state.phase _apply_state(e[3], true) c.state.phase = int(e[1]) as CampaignController.Phase c.state.phase_time_left = float(e[4]) if c.state.phase == CampaignController.Phase.MORNING: _map.clear() _gone.clear() _targets.clear() c.phase_changed.emit(c.state.phase, previous) "ended": _apply_state(e[2], true) c.outcome = int(e[1]) as CampaignController.Outcome var terminal := CampaignController.Phase.FARMERS_RETURN if c.outcome == CampaignController.Outcome.VACATION_COMPLETE \ else CampaignController.Phase.GAME_OVER if c.state.phase != terminal: var previous := c.state.phase c.state.phase = terminal c.phase_changed.emit(terminal, previous) c.campaign_ended.emit(c.outcome) "sound": if sim.audio != null: sim.audio.play_remote(String(e[1]), e[2]) "toast": if sim.toasts != null: sim.toasts.push(String(e[1]), e[2]) "loot": sim.loot.loot_event.emit(StringName(e[1]), int(e[2]), e[3]) "arrived": if sim.toasts != null: sim.toasts.push(FarmSim.arrival_message(int(e[1]), sim.zones.side_of(e[2])), Color(1.0, 0.75, 0.55)) "destroyed": sim.structures.show_debris(e[3]) sim.structures.destroyed.emit(int(e[1]), String(e[2]), e[3]) "fear": var slot := int(e[1]) if slot < sim.avatars.size(): sim.avatars[slot].kit.play_burst() "attack": # our own scarecrow's attacks already show here var slot := int(e[1]) if slot < sim.avatars.size() and not sim.avatars[slot].is_local: var combat := sim.avatars[slot].combat combat.show_weapon(int(e[2])) combat.models.attack(int(e[2])) "bomb": sim.bombs.throw(e[1], e[2], 0, 0.0) # drawn only (replica) "popup": sim.interactions._popup(String(e[1]), e[2], e[3]) "workbench": if sim.upgrade_panel != null and c.is_daytime(): sim.upgrade_panel.open() "shed": if sim.shed_panel != null and c.is_daytime(): sim.shed_panel.open() 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 = 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", "ue"]: 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() rec["ut"] = b.get_32() rec["up"] = b.get_32() return rec func _apply_avatar(a: Avatar, rec: Dictionary) -> void: var k := a.kit var body := a.body if not a.is_local: body.net_position = rec["p"] body.net_yaw = float(rec["y"]) body.net_speed = float(rec["v"]) var s := sim.campaign.state if a.slot == 0: s.scarecrow_hp = clampi(int(rec["hp"]), 0, s.scarecrow_max_hp) else: s.partner_hp = clampi(int(rec["hp"]), 0, s.partner_max_hp) var alive := bool(rec["a"]) if alive != k.alive: k.alive = alive if alive: body.revive() else: body.die() k.invulnerable_left = float(rec["inv"]) k.fear_left = float(rec["fl"]) a.combat.bomb_left = float(rec["bl"]) if not a.is_local: a.combat.show_weapon(int(rec["w"])) var pt := float(rec["pt"]) k.patching = pt >= 0.0 k.patch_elapsed = maxf(pt, 0.0) if a.is_local: var ch := String(rec["ch"]) if ch != "" and (not body.rooted or body.channel_clip != StringName(ch)): body.start_channel(StringName(ch)) elif ch == "" and body.rooted and not sim._menu_open(): body.stop_channel() var it := a.interactions it.focus = _gather_node(String(rec["fo"])) it.gathering = _gather_node(String(rec["ga"])) as GatherNode it.gather_elapsed = float(rec["ge"]) it.repair_target = int(rec["rt"]) it.repairing = int(rec["rp"]) it.repair_elapsed = float(rec["re"]) it.upgrade_target = int(rec["ut"]) it.upgrading = int(rec["up"]) it.upgrade_elapsed = float(rec["ue"]) func _gather_node(node_name: String) -> Node3D: if node_name == "": return null var it := sim.interactions if it.workbench != null and String(it.workbench.name) == node_name: return it.workbench for n in it.nodes: if String(n.name) == node_name: return n return null func _apply_foes(chunk: PackedByteArray) -> void: var es := sim.enemies for o in range(0, chunk.size() - FOE_RECORD + 1, FOE_RECORD): var host := chunk.decode_s32(o) if _gone.has(host): continue var type := chunk[o + 4] var x := chunk.decode_s16(o + 8) / 100.0 var z := chunk.decode_s16(o + 10) / 100.0 var h: int = _map.get(host, -1) var d := es.resolve_handle(h) if h >= 0 else -1 if d < 0: h = es.spawn(type, x, z, Vector2(chunk.decode_s8(o + 12), chunk.decode_s8(o + 13))) if h < 0: continue _map[host] = h d = es.resolve_handle(h) 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) / VEL_SCALE, chunk.decode_s8(o + 15) / VEL_SCALE, chunk[o + 7] / 40.0]) _targets[h] = t func _remove_foe(host: int, reason: int) -> void: _gone[host] = true var h: int = _map.get(host, -1) _map.erase(host) if h < 0: return _targets.erase(h) var es := sim.enemies var d := es.resolve_handle(h) if d < 0: return es.carry[d] = -1 # the host settles the loot; here it's only for show es.target[d] = -1 es.queue_removal(d, reason as EnemySystem.Removal) es.commit_removals() ## This machine's handle for a host enemy (-1 if it isn't here). func _local_handle(host: int) -> int: return int(_map.get(host, -1)) ## Each partner tick (FarmSim._step_replica): the news, then the enemies and shots move on ## toward where the host last had them. func _replica_tick(dt: float) -> void: if link != null: link.poll() var es := sim.enemies for h: int in _targets: var d := es.resolve_handle(h) if d < 0: continue var t: PackedFloat32Array = _targets[h] t[0] += t[4] * dt # carry on as the host said it was moving t[1] += t[5] * dt _targets[h] = t es.prev_x[d] = es.pos_x[d] es.prev_z[d] = es.pos_z[d] var k := 0.35 if Vector2(t[0] - es.pos_x[d], t[1] - es.pos_z[d]).length() > 5.0: k = 1.0 es.pos_x[d] = lerpf(es.pos_x[d], t[0], k) es.pos_z[d] = lerpf(es.pos_z[d], t[1], k) var hv := Vector2(t[2], t[3]) if hv.length_squared() > 1e-4: hv = hv.normalized() es.head_x[d] = hv.x es.head_z[d] = hv.y 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) func _reset_world() -> void: sim.enemies.clear() sim.projectiles.clear() _map.clear() _gone.clear() _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 ui := sim._menu_open() 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() func _unhandled_input(event: InputEvent) -> void: if role == Role.CLIENT: _sender.note(event) ## Either shop's menu closes here on the same rules as solo (Interactions): walking off its ## counter's reach, nightfall, build mode. func _close_menu_if_needed() -> void: _close_menu(sim.upgrade_panel, sim.interactions.workbench) _close_menu(sim.shed_panel, sim.interactions.shed_counter) ## counter: Workbench or ShedCounter (both just need global_position and reach). func _close_menu(panel: UpgradePanel, counter) -> void: if panel == null or not panel.is_open: return var p := sim.local_avatar.position() if not sim.campaign.is_daytime() or sim.build.active or counter == null \ or Vector2(counter.global_position.x, counter.global_position.z).distance_to(p) > counter.reach + 0.5: panel.close() func _request(r: Array) -> void: if link != null and role == Role.CLIENT: link.send("req", r, true) # --- Both ------------------------------------------------------------------------------------- func _hook(sig: Signal, callable: Callable) -> void: sig.connect(callable) _connections.append([sig, callable]) ## Name tags over both scarecrows ("P1 Ana", "P2 Ben"). func _tag_all() -> void: for a in sim.avatars: a.body.set_tag(a.label(), a.color()) static func _display(n: String, fallback: String) -> String: return n if n != "" else fallback