804 lines
30 KiB
GDScript
804 lines
30 KiB
GDScript
class_name FarmSim
|
|
extends Node
|
|
## Drives the farm's simulation in a fixed order each physics tick, after the scarecrow has
|
|
## moved (PlayerCharacter runs earlier in the tree):
|
|
## scarecrow kit (fear, patch, timers) -> build mode -> interactions (gather, workbench,
|
|
## repair, shed drop-off) -> weapons (recharge, switching) -> aim and attack (pitchfork, corn
|
|
## shooter, pumpkin bombs) -> enemies (behavior, steering, motion, collision, traps) -> enemy
|
|
## melee -> automated defenses -> shots -> pumpkin bombs -> recovery by touch -> animals
|
|
## (wander, roam, follow) -> night arrivals (WaveDirector) -> deferred enemy removals ->
|
|
## flow-field rebuild slice -> render upload -> campaign phase timers and outcome.
|
|
## Whenever the structures change (built, broken, dismantled), the flow fields are rebuilt as
|
|
## FieldJobs in slices of flow_slice_cells per tick; thieves keep using the old fields until the
|
|
## new ones are complete.
|
|
## It builds the farm navigation and the theft flow fields at load (toward the crop rows, the
|
|
## inside of the pen, each of the shed's piles, and the farm's edge, where enemies arrive and
|
|
## escape: WaveDirector.ground_spawns are the edge cells with a route in), owns the combat and theft systems,
|
|
## and applies the phase rules: thieves arrive only at night (the night's NightPlan, run by
|
|
## WaveDirector), sunrise makes them retreat (carriers keep running), the end of the dawn grace
|
|
## sends the rest off the farm with whatever they carry, returns dropped loot (and the animals
|
|
## still following the scarecrow) home, and regrows the gather points, and every new morning (also after a retry) resets the
|
|
## theft state from the farm state. DayNight lights the phases; PhaseHud, AssetHud, ReviewPanel,
|
|
## and the other HUD parts show them. Co-op (CoopSession): a second scarecrow (add_partner) is
|
|
## simulated alongside the first, and on the partner's machine the farm is a replica: nothing is
|
|
## simulated there, the host's state is applied instead (replica = true), and player, scarecrow,
|
|
## combat, and interactions are that machine's own scarecrow's (player 2's).
|
|
## FarmAudio plays every sound, Tutorial shows the first
|
|
## day's and night's tips, and FarmersReturn plays the ending. Debug: T / G / H send in a
|
|
## thief / a crow / a fence breaker at any time.
|
|
|
|
const SCARECROW_RADIUS := 0.4
|
|
const HUNT_INTERVAL := 0.4
|
|
## Night n's plan file (night_plan_path), for n in 1..GameConfig.campaign_nights.
|
|
const NIGHT_PLAN_PATH := "res://game/resources/nights/night_%d.tres"
|
|
|
|
@export var campaign: CampaignController
|
|
@export var zones: FarmZones
|
|
@export var player: PlayerCharacter
|
|
@export var camera: Camera3D
|
|
@export var alerts: AlertManager
|
|
@export var hud: ScarecrowHud
|
|
@export var end_panel: EndPanel
|
|
@export var resource_hud: ResourceHud
|
|
@export var build_hud: BuildHud
|
|
@export var phase_hud: PhaseHud
|
|
@export var asset_hud: AssetHud
|
|
@export var review_panel: ReviewPanel
|
|
@export var upgrade_panel: UpgradePanel
|
|
@export var shed_panel: UpgradePanel
|
|
@export var sun: DirectionalLight3D
|
|
@export var world_environment: WorldEnvironment
|
|
|
|
var config: GameConfig
|
|
var nav := FarmNavigation.new()
|
|
var crop_field := PackedInt32Array()
|
|
var escape_field := PackedInt32Array()
|
|
var animal_field := PackedInt32Array()
|
|
## Material -> the field toward that material's pile at the shed.
|
|
var supply_fields := {}
|
|
var enemies: EnemySystem
|
|
var behavior := ThiefBehavior.new()
|
|
var loot: LootSystem
|
|
var animals: AnimalSystem
|
|
var shed_stock: ShedStock
|
|
var projectiles: FarmProjectiles
|
|
var bombs: PumpkinBombs
|
|
var combat: ScarecrowCombat
|
|
var scarecrow: Scarecrow
|
|
var interactions: Interactions
|
|
var structures: StructureSystem
|
|
var build: BuildMode
|
|
var waves: WaveDirector
|
|
var day_night: DayNight
|
|
## Every scarecrow in play (player 1's first), the one this machine plays, and the other one
|
|
## (co-op; null solo). On the partner's machine the farm is a replica of the host's.
|
|
var avatars: Array[Avatar] = []
|
|
var local_avatar: Avatar
|
|
var partner: Avatar
|
|
var replica := false
|
|
## Co-op menus don't pause the farm: this machine's scarecrow ignores the input meanwhile.
|
|
var local_frozen := false
|
|
## Set by CoopSession on the partner's machine: applies the host's state each tick.
|
|
var replica_step: Callable
|
|
## Co-op: the session with the other machine (idle solo).
|
|
var coop: CoopSession
|
|
var audio: FarmAudio
|
|
var tutorial: Tutorial
|
|
var ending: FarmersReturn
|
|
## Flow-field rebuild after a structure change: running, and stats of the last one.
|
|
var rebuilding := false
|
|
var rebuilds: int = 0
|
|
var last_rebuild_usec: int = 0
|
|
var last_rebuild_ticks: int = 0
|
|
var max_rebuild_slice_usec: int = 0
|
|
var load_msec: int = 0
|
|
|
|
## Flow-field jobs by name: "escape" (the farm's edge), "pen" (inside the pen), one per shed pile (by
|
|
## material), "breaker" (barriers guarding valuables), and "crops" (the crop rows) only when a
|
|
## ground enemy type goes for crops.
|
|
var _jobs := {}
|
|
var _goals := {} # name -> goal cells (the breaker's are worked out at every rebuild)
|
|
var breaker_field := PackedInt32Array()
|
|
## Toward the scarecrow, for enemies hunting it: rebuilt in slices (HUNT_INTERVAL apart at most)
|
|
## while any enemy fights and the scarecrow has moved to another cell.
|
|
var hunt_field := PackedInt32Array()
|
|
var characters: EnemyCharacters
|
|
var _hunt_job: FarmNavigation.FieldJob
|
|
var _hunt_cell: int = -1
|
|
var _hunt_wait: float = 0.0
|
|
var _rebuild_usec: int = 0
|
|
var _rebuild_ticks: int = 0
|
|
## Alien Goop's drop-on-kill roll (Decision 11): seeded like LootSystem's category RNG, for
|
|
## reproducible trials.
|
|
var _goop_rng := RandomNumberGenerator.new()
|
|
|
|
|
|
## Where night n's plan lives: game/resources/nights/night_<n>.tres.
|
|
static func night_plan_path(n: int) -> String:
|
|
return NIGHT_PLAN_PATH % n
|
|
|
|
|
|
## The plans of nights 1..nights, by night_plan_path. A missing (or unreadable) file is an error,
|
|
## and that night plays the last plan that loaded (as WaveDirector.plan_for does past the end).
|
|
static func load_night_plans(nights: int) -> Array[NightPlan]:
|
|
var plans: Array[NightPlan] = []
|
|
var last: NightPlan = null
|
|
for n in range(1, nights + 1):
|
|
var path := night_plan_path(n)
|
|
var plan: NightPlan = load(path) as NightPlan if ResourceLoader.exists(path) else null
|
|
if plan == null:
|
|
push_error("Night %d has no plan at %s: it plays %s" % [n, path, "night %d's" % (n - 1) if last != null else "none"])
|
|
plan = last
|
|
else:
|
|
last = plan
|
|
plans.append(plan)
|
|
return plans
|
|
|
|
|
|
func _ready() -> void:
|
|
var t0 := Time.get_ticks_msec()
|
|
config = campaign.config
|
|
campaign.set_physics_process(false) # ticked from step(), after the simulation
|
|
player.config = config # the sprint
|
|
player.campaign = campaign
|
|
var shed_zone := zones.zone(FarmZone.Kind.SUPPLY_SHED)
|
|
var pen_zone := zones.zone(FarmZone.Kind.ANIMAL_PEN)
|
|
shed_stock = ShedStock.new()
|
|
shed_stock.name = "ShedStock"
|
|
add_child(shed_stock)
|
|
shed_stock.setup(campaign, shed_zone, player) # every pile prop in place for the navigation
|
|
nav.build(get_parent(), zones.playable.grow(5.0), config.nav_cell_size, config.enemy_radius + config.nav_inflate_margin)
|
|
shed_stock.refresh()
|
|
# #13: three CROP_FIELD zones (the original field, lettuce/cabbage, corn). #20: each keeps its
|
|
# own rectangle (ThiefBehavior.area_for: "close enough, go straight" once inside the target's
|
|
# field); their bounding box would span most of the map now that the later fields lie south.
|
|
var field_rects: Array[Rect2] = []
|
|
for z in zones.zones_of(FarmZone.Kind.CROP_FIELD):
|
|
field_rects.append(z.rect())
|
|
# Goals are the crop rows themselves (not the whole zone), so a fence around the crops
|
|
# encloses every goal and thieves have to break in. Likewise the inside of the pen.
|
|
var crop_goals := PackedInt32Array()
|
|
for u in zones.crop_units():
|
|
var lo := Vector2(INF, INF)
|
|
var hi := Vector2(-INF, -INF)
|
|
for plant in u.get_children():
|
|
var at := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
|
|
lo = lo.min(at)
|
|
hi = hi.max(at)
|
|
crop_goals.append_array(nav.free_cells_in(Rect2(lo, hi - lo).grow(0.3)))
|
|
_goals = {"escape": nav.free_cells_on_outline(zones.edge(config.spawn_margin), nav.cell_size * 0.75),
|
|
"pen": nav.free_cells_in(pen_zone.rect().grow(-1.0)), "breaker": PackedInt32Array()}
|
|
for m in ResourceStore.MATERIALS:
|
|
_goals[m] = nav.free_cells_near(PackedVector2Array([shed_stock.spot(m)]), 0.8)
|
|
if _ground_takes_crops():
|
|
_goals["crops"] = crop_goals
|
|
for job_name in _goals:
|
|
_jobs[job_name] = FarmNavigation.FieldJob.new(nav)
|
|
_hunt_job = FarmNavigation.FieldJob.new(nav)
|
|
|
|
enemies = EnemySystem.new()
|
|
enemies.name = "Enemies"
|
|
add_child(enemies)
|
|
loot = LootSystem.new()
|
|
loot.name = "Loot"
|
|
add_child(loot)
|
|
animals = AnimalSystem.new()
|
|
animals.name = "Animals"
|
|
add_child(animals)
|
|
behavior.setup(config, nav, loot, crop_field, escape_field, field_rects)
|
|
behavior.pen_rect = pen_zone.rect()
|
|
behavior.shed_rect = shed_zone.rect()
|
|
behavior.farm_rect = zones.playable
|
|
characters = EnemyCharacters.new()
|
|
characters.name = "EnemyCharacters"
|
|
add_child(characters)
|
|
var mat := ShaderMaterial.new()
|
|
mat.shader = load("res://game/resources/thief.gdshader") as Shader
|
|
var ufo_mat := ShaderMaterial.new()
|
|
ufo_mat.shader = load("res://game/resources/ufo.gdshader") as Shader
|
|
enemies.setup(config, nav, behavior, EnemySystem.build_bird_mesh(0.0055), mat, zones.playable.grow(12.0),
|
|
EnemySystem.build_ufo_mesh(), ufo_mat)
|
|
characters.setup(enemies, config)
|
|
enemies.characters = characters
|
|
loot.animals = animals
|
|
loot.shed_stock = shed_stock
|
|
loot.setup(campaign, zones.crop_units(), enemies, AnimalSystem.find_animals(pen_zone).size())
|
|
animals.setup(campaign, pen_zone, nav, loot, enemies, player, zones.playable)
|
|
if animals.count != config.start_animals:
|
|
push_warning("The pen holds %d animals but GameConfig.start_animals is %d" % [animals.count, config.start_animals])
|
|
enemies.enemy_removed.connect(loot.on_enemy_removed)
|
|
enemies.enemy_removed.connect(_count_removal)
|
|
_goop_rng.seed = 20261005
|
|
enemies.enemy_removed.connect(_drop_alien_goop)
|
|
projectiles = FarmProjectiles.new()
|
|
projectiles.name = "Shots"
|
|
add_child(projectiles)
|
|
projectiles.setup(config, enemies, zones.playable.grow(8.0), player.get_rid())
|
|
bombs = PumpkinBombs.new()
|
|
bombs.name = "Bombs"
|
|
add_child(bombs)
|
|
bombs.setup(config, enemies)
|
|
structures = StructureSystem.new()
|
|
structures.name = "Structures"
|
|
add_child(structures)
|
|
structures.setup(campaign, nav, zones, enemies, projectiles, player)
|
|
enemies.structures = structures
|
|
behavior.structures = structures
|
|
_start_field_rebuild()
|
|
_finish_field_rebuild(1 << 30) # at load, all at once
|
|
max_rebuild_slice_usec = 0
|
|
structures.layout_changed.connect(_start_field_rebuild)
|
|
structures.layout_changed.connect(animals.update_pen_open)
|
|
animals.update_pen_open()
|
|
combat = ScarecrowCombat.new()
|
|
combat.name = "Combat"
|
|
add_child(combat)
|
|
combat.setup(config, player, camera, projectiles)
|
|
combat.campaign = campaign
|
|
combat.enemies = enemies
|
|
combat.bombs = bombs
|
|
scarecrow = Scarecrow.new()
|
|
scarecrow.name = "Scarecrow"
|
|
add_child(scarecrow)
|
|
scarecrow.setup(config, campaign, player, enemies, behavior)
|
|
interactions = Interactions.new()
|
|
interactions.name = "Interactions"
|
|
add_child(interactions)
|
|
interactions.setup(config, campaign, player, scarecrow, zones)
|
|
scarecrow.interactions = interactions
|
|
interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
|
|
campaign.state.record_event("gathered_" + material, amount))
|
|
var first := Avatar.new()
|
|
first.slot = 0
|
|
first.body = player
|
|
first.kit = scarecrow
|
|
first.combat = combat
|
|
first.interactions = interactions
|
|
avatars = [first]
|
|
local_avatar = first
|
|
waves = WaveDirector.new()
|
|
waves.name = "Waves"
|
|
add_child(waves)
|
|
waves.setup(campaign, enemies, zones, load_night_plans(config.campaign_nights))
|
|
for c in _goals["escape"]:
|
|
if animal_field[c] < FarmNavigation.UNREACHABLE: # not shut in by the props around it
|
|
waves.ground_spawns.append(nav.cell_center(c))
|
|
campaign.night_length_for = waves.night_length
|
|
if sun != null and world_environment != null:
|
|
day_night = DayNight.new()
|
|
day_night.name = "DayNight"
|
|
add_child(day_night)
|
|
day_night.characters = characters
|
|
day_night.setup(campaign, sun, world_environment.environment, player, [mat, ufo_mat])
|
|
build = BuildMode.new()
|
|
build.name = "Build"
|
|
add_child(build)
|
|
build.setup(config, campaign, player, camera, structures, combat, scarecrow)
|
|
build.toggled.connect(func(_on: bool) -> void: combat.reset())
|
|
interactions.structures = structures
|
|
interactions.build = build
|
|
if upgrade_panel != null:
|
|
upgrade_panel.setup(campaign, structures, player)
|
|
interactions.upgrade_panel = upgrade_panel
|
|
upgrade_panel.bought.connect(func(id: String) -> void: # a new weapon goes into its hand
|
|
var w := ScarecrowCombat.WEAPON_IDS.find(id)
|
|
if w > 0:
|
|
combat.equip(w))
|
|
if shed_panel != null:
|
|
shed_panel.setup(campaign, structures, player, "shed")
|
|
interactions.shed_panel = shed_panel
|
|
shed_panel.bought.connect(func(id: String) -> void: # a new weapon goes into its hand
|
|
var w := ScarecrowCombat.WEAPON_IDS.find(id)
|
|
if w > 0:
|
|
combat.equip(w))
|
|
if resource_hud != null:
|
|
resource_hud.setup(campaign)
|
|
resource_hud.structures = structures
|
|
if build_hud != null:
|
|
build_hud.setup(build, campaign)
|
|
if phase_hud != null:
|
|
phase_hud.setup(campaign, waves, enemies)
|
|
if asset_hud != null:
|
|
asset_hud.setup(campaign)
|
|
if review_panel != null:
|
|
review_panel.setup(campaign, structures)
|
|
review_panel.animals = animals
|
|
review_panel.waves = waves
|
|
review_panel.refresh()
|
|
if hud != null:
|
|
hud.setup(scarecrow, campaign, combat)
|
|
if hud != null and hud.get_parent() != null:
|
|
var radar_hud := RadarHud.new()
|
|
radar_hud.name = "RadarHud"
|
|
hud.get_parent().add_child(radar_hud)
|
|
radar_hud.setup(self)
|
|
ending = FarmersReturn.new()
|
|
ending.name = "FarmersReturn"
|
|
add_child(ending)
|
|
ending.setup(self)
|
|
if end_panel != null:
|
|
end_panel.setup(campaign)
|
|
end_panel.ending = ending
|
|
end_panel.waves = waves
|
|
if hud != null and hud.get_parent() != null:
|
|
tutorial = Tutorial.new()
|
|
tutorial.name = "Tutorial"
|
|
hud.get_parent().add_child(tutorial)
|
|
tutorial.setup(self)
|
|
if end_panel != null:
|
|
end_panel.get_parent().move_child(end_panel, -1) # over the banners and the tips
|
|
audio = FarmAudio.new()
|
|
audio.name = "Audio"
|
|
add_child(audio)
|
|
audio.setup(self)
|
|
coop = CoopSession.new()
|
|
coop.name = "Coop" # the same path on both machines (GD-Sync calls it by path)
|
|
add_child(coop)
|
|
|
|
campaign.phase_changed.connect(_on_phase_changed)
|
|
campaign.night_ending.connect(_on_night_ending)
|
|
if alerts != null:
|
|
alerts.setup(self)
|
|
load_msec = Time.get_ticks_msec() - t0
|
|
|
|
|
|
func _physics_process(dt: float) -> void:
|
|
step(dt)
|
|
|
|
|
|
func step(dt: float) -> void:
|
|
if replica:
|
|
_step_replica(dt)
|
|
return
|
|
if not campaign.is_over():
|
|
var first := avatars[0]
|
|
var p := first.position()
|
|
behavior.scarecrow = p if first.kit.alive else Vector2(INF, INF)
|
|
var second := avatars[1] if avatars.size() > 1 else null
|
|
behavior.scarecrow2 = second.position() if second != null and second.kit.alive else Vector2(INF, INF)
|
|
enemies.scarecrow2 = behavior.scarecrow2
|
|
for a in avatars:
|
|
a.kit.step(dt)
|
|
if not local_frozen:
|
|
build.step(dt)
|
|
for a in avatars:
|
|
a.interactions.step(dt)
|
|
for a in avatars:
|
|
a.combat.tick(dt, a.is_local and not build.active and not local_frozen and not _menu_open())
|
|
for a in avatars:
|
|
var building := build.active if a.is_local else (a.remote != null and a.remote.build_active)
|
|
if a.kit.can_shoot() and a.interactions.can_shoot() and not building:
|
|
enemies.attacker = a.slot # its kills (and its shots') are its own (Alien Goop)
|
|
a.combat.step(dt)
|
|
enemies.attacker = -1
|
|
enemies.step(dt, p, SCARECROW_RADIUS)
|
|
for a in avatars:
|
|
if a.kit.alive:
|
|
enemies.evaluate_attacks(a.position(), SCARECROW_RADIUS, a.kit)
|
|
structures.step(dt)
|
|
projectiles.step(dt)
|
|
bombs.step(dt)
|
|
for a in avatars:
|
|
if a.kit.alive:
|
|
loot.step(a.position(), a.slot)
|
|
animals.step(dt)
|
|
waves.step(dt)
|
|
enemies.commit_removals()
|
|
if rebuilding:
|
|
_finish_field_rebuild(config.flow_slice_cells)
|
|
_update_hunt(dt)
|
|
enemies.commit_render()
|
|
projectiles.commit_render()
|
|
campaign.tick(dt)
|
|
|
|
|
|
## The partner's machine: only its own scarecrow acts locally (aiming, build mode as a UI); the
|
|
## host's state is applied (replica_step), then drawn.
|
|
func _step_replica(dt: float) -> void:
|
|
if replica_step.is_valid():
|
|
replica_step.call(dt)
|
|
combat.tick(dt, not build.active and not local_frozen and not _menu_open())
|
|
bombs.step(dt) # the host's throws, drawn
|
|
if not campaign.is_over() and scarecrow.alive and not local_frozen:
|
|
build.step(dt)
|
|
if interactions.can_shoot() and not build.active and not _menu_open():
|
|
combat.step(dt)
|
|
enemies.commit_render()
|
|
projectiles.commit_render()
|
|
|
|
|
|
func _menu_open() -> bool:
|
|
return (upgrade_panel != null and upgrade_panel.is_open) or (shed_panel != null and shed_panel.is_open)
|
|
|
|
|
|
## Co-op: while this machine's scarecrow is down, the camera watches the partner's.
|
|
func _process(_delta: float) -> void:
|
|
if partner == null or not (camera is FollowCamera):
|
|
return
|
|
var other := avatars[0] if local_avatar == partner else partner
|
|
var want := local_avatar.body if local_avatar.kit.alive or not other.kit.alive else other.body
|
|
if (camera as FollowCamera).target != want:
|
|
(camera as FollowCamera).target = want
|
|
|
|
|
|
## Co-op: while a menu is up, this machine's scarecrow takes no input (its kit, hands, and gun
|
|
## read an empty RemoteControls; its body doesn't move).
|
|
func freeze_local(on: bool) -> void:
|
|
local_frozen = on
|
|
var a := local_avatar
|
|
var none := RemoteControls.new() if on else null
|
|
a.kit.remote = none
|
|
a.interactions.remote = none
|
|
a.combat.remote = none
|
|
a.body.input_enabled = not on
|
|
if on:
|
|
build.set_active(false)
|
|
|
|
|
|
## Co-op: brings player 2's scarecrow onto the farm (next to player 1's): a second body with its
|
|
## own kit, gun, and hands. local: whether this machine plays it (the partner's machine) or the
|
|
## partner's game does (the host: then it reads remote). Returns it.
|
|
func add_partner(local: bool, name_text: String = "") -> Avatar:
|
|
if partner != null:
|
|
return partner
|
|
var a := Avatar.new()
|
|
a.slot = 1
|
|
a.is_local = local
|
|
a.player_name = name_text
|
|
var body := (load("res://game/scenes/player.tscn") as PackedScene).instantiate() as PlayerCharacter
|
|
body.name = "Player2"
|
|
get_parent().add_child(body)
|
|
body.global_position = player.global_position + Vector3(1.8, 0.0, 0.6)
|
|
body.set_tint(Color(0.55, 0.75, 1.0))
|
|
body.config = config
|
|
body.campaign = campaign
|
|
a.body = body
|
|
a.kit = Scarecrow.new()
|
|
a.kit.name = "Scarecrow2"
|
|
a.kit.slot = 1
|
|
add_child(a.kit)
|
|
a.kit.setup(config, campaign, body, enemies, behavior)
|
|
a.combat = ScarecrowCombat.new()
|
|
a.combat.name = "Combat2"
|
|
add_child(a.combat)
|
|
a.combat.setup(config, body, camera, projectiles)
|
|
a.combat.campaign = campaign
|
|
a.combat.enemies = enemies
|
|
a.combat.bombs = bombs
|
|
a.combat.show_marker = local
|
|
a.interactions = Interactions.new()
|
|
a.interactions.name = "Interactions2"
|
|
add_child(a.interactions)
|
|
a.interactions.setup(config, campaign, body, a.kit, zones)
|
|
a.interactions.structures = structures
|
|
a.interactions.show_labels = local
|
|
a.kit.interactions = a.interactions
|
|
a.interactions.gathered.connect(func(material: String, amount: int, _n: GatherNode) -> void:
|
|
if not replica:
|
|
campaign.state.record_event("gathered_" + material, amount))
|
|
if not local:
|
|
a.remote = RemoteControls.new()
|
|
a.kit.remote = a.remote
|
|
a.combat.remote = a.remote
|
|
a.interactions.remote = a.remote
|
|
avatars.append(a)
|
|
partner = a
|
|
animals.leaders.append(body)
|
|
structures.partner = body
|
|
if day_night != null:
|
|
day_night.add_lantern(body)
|
|
if audio != null:
|
|
audio.wire_avatar(a)
|
|
if not replica:
|
|
var s := campaign.state
|
|
if not s.coop:
|
|
s.coop = true
|
|
s.partner_max_hp = s.scarecrow_max_hp
|
|
s.partner_hp = s.scarecrow_max_hp
|
|
return a
|
|
|
|
|
|
## Co-op: player 2 left. Their scarecrow goes; if player 1's is down, that's the end of the night.
|
|
## What they carried goes into the shed (on the host). Returns what moved (material -> amount).
|
|
func remove_partner() -> Dictionary:
|
|
if partner == null:
|
|
return {}
|
|
var a := partner
|
|
var moved := {} if replica else campaign.state.resources.deposit(a.slot)
|
|
if not moved.is_empty():
|
|
shed_stock.refresh()
|
|
partner = null
|
|
avatars.erase(a)
|
|
if camera is FollowCamera and (camera as FollowCamera).target == a.body:
|
|
(camera as FollowCamera).target = local_avatar.body
|
|
animals.leaders.erase(a.body)
|
|
if structures.partner == a.body:
|
|
structures.partner = null
|
|
for n: Node in [a.kit, a.combat, a.interactions, a.body]:
|
|
if is_instance_valid(n):
|
|
n.queue_free()
|
|
if not replica:
|
|
campaign.state.coop = false
|
|
behavior.scarecrow2 = Vector2(INF, INF)
|
|
enemies.scarecrow2 = Vector2(INF, INF)
|
|
return moved
|
|
|
|
|
|
## Makes another scarecrow this machine's own (the partner's machine plays player 2): the HUD,
|
|
## the camera, build mode, the upgrade menu, the materials readout (its own pouch), sounds, and
|
|
## tips follow it.
|
|
func set_local(a: Avatar) -> void:
|
|
for other in avatars:
|
|
other.is_local = other == a
|
|
other.combat.show_marker = other == a
|
|
other.interactions.show_labels = other == a
|
|
local_avatar = a
|
|
player = a.body
|
|
scarecrow = a.kit
|
|
combat = a.combat
|
|
interactions = a.interactions
|
|
interactions.structures = structures
|
|
interactions.build = build
|
|
interactions.upgrade_panel = upgrade_panel
|
|
interactions.shed_panel = shed_panel
|
|
build.player = a.body
|
|
build.combat = a.combat
|
|
build.kit = a.kit
|
|
if upgrade_panel != null:
|
|
upgrade_panel.player = a.body
|
|
upgrade_panel.slot = a.slot
|
|
if shed_panel != null:
|
|
shed_panel.player = a.body
|
|
shed_panel.slot = a.slot
|
|
if resource_hud != null:
|
|
resource_hud.slot = a.slot
|
|
if camera is FollowCamera:
|
|
(camera as FollowCamera).target = a.body
|
|
(camera as FollowCamera).snap_to_target()
|
|
if hud != null:
|
|
hud.retarget(a.kit, a.combat)
|
|
if audio != null:
|
|
audio.focus = a.body
|
|
if alerts != null:
|
|
alerts.player = a.body
|
|
shed_stock.player = a.body
|
|
|
|
|
|
## Restarts every flow-field job for the current structure layout.
|
|
func _start_field_rebuild() -> void:
|
|
_goals["breaker"] = _breaker_goals()
|
|
for job_name in _jobs:
|
|
(_jobs[job_name] as FarmNavigation.FieldJob).start(_goals[job_name])
|
|
rebuilding = true
|
|
_rebuild_usec = 0
|
|
_rebuild_ticks = 0
|
|
|
|
|
|
## Runs up to budget cells of the rebuild, one job after another; swaps the new fields in once
|
|
## all are complete.
|
|
func _finish_field_rebuild(budget: int) -> void:
|
|
var t0 := Time.get_ticks_usec()
|
|
var left := budget
|
|
for job: FarmNavigation.FieldJob in _jobs.values():
|
|
if left <= 0:
|
|
break
|
|
if not job.done:
|
|
var before := job.processed
|
|
job.step(left)
|
|
left -= job.processed - before
|
|
var slice := Time.get_ticks_usec() - t0
|
|
_rebuild_usec += slice
|
|
_rebuild_ticks += 1
|
|
max_rebuild_slice_usec = maxi(max_rebuild_slice_usec, slice)
|
|
if _jobs.values().all(func(j: FarmNavigation.FieldJob) -> bool: return j.done):
|
|
if _jobs.has("crops"):
|
|
crop_field = _jobs["crops"].dist.duplicate()
|
|
escape_field = _jobs["escape"].dist.duplicate()
|
|
animal_field = _jobs["pen"].dist.duplicate()
|
|
breaker_field = _jobs["breaker"].dist.duplicate()
|
|
for m in ResourceStore.MATERIALS:
|
|
supply_fields[m] = _jobs[m].dist.duplicate()
|
|
behavior.crop_field = crop_field
|
|
behavior.escape_field = escape_field
|
|
behavior.animal_field = animal_field
|
|
behavior.supply_fields = supply_fields
|
|
behavior.breaker_field = breaker_field
|
|
animals.escape_field = escape_field
|
|
rebuilding = false
|
|
rebuilds += 1
|
|
last_rebuild_usec = _rebuild_usec
|
|
last_rebuild_ticks = _rebuild_ticks
|
|
|
|
|
|
## Sends a ground thief in at a random point along the farm's edge (or at the given point), going
|
|
## for the given target (a LootSystem.Category, or LootSystem.ANY: its type's targets by weight).
|
|
## Returns its handle.
|
|
func spawn_thief(want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
|
|
return spawn_enemy(EnemySystem.TYPE_THIEF, want, at)
|
|
|
|
|
|
## Sends an enemy of any type in at a random point along the farm's edge (or at the given
|
|
## point). Returns its handle.
|
|
func spawn_enemy(type: int, want: int = LootSystem.ANY, at: Vector2 = WaveDirector.ANYWHERE) -> int:
|
|
return waves.spawn(type, want, at)
|
|
|
|
|
|
## Counts the night's kills by type, and the enemies that got away with loot.
|
|
func _count_removal(handle: int, reason: EnemySystem.Removal, _x: float, _z: float, _carry: int, _target: int) -> void:
|
|
match reason:
|
|
EnemySystem.Removal.KILLED:
|
|
var d := enemies.resolve_handle(handle)
|
|
if d >= 0:
|
|
campaign.state.record_event("killed_" + EnemySystem.TYPE_NAMES[enemies.type[d]])
|
|
EnemySystem.Removal.ESCAPED:
|
|
campaign.state.record_event("escaped")
|
|
|
|
|
|
## Alien Goop (Decision 11): a killed Alien (the thief type, display-named "Alien") has a
|
|
## config-tunable chance to drop goop, credited like a gathered material straight into the
|
|
## pouch (respecting its capacity; a full pouch simply loses the drop, same as any overflow).
|
|
## Co-op: into the killer's pouch (EnemySystem.killer_of); a turret's or a bomb's kill goes to the
|
|
## scarecrow nearest to it (goop_slot). Only the host rolls it: the partner's farm state follows.
|
|
func _drop_alien_goop(handle: int, reason: EnemySystem.Removal, x: float, z: float, _carry: int, _target: int) -> void:
|
|
if reason != EnemySystem.Removal.KILLED or replica:
|
|
return
|
|
var d := enemies.resolve_handle(handle)
|
|
if d < 0 or enemies.type[d] != EnemySystem.TYPE_THIEF:
|
|
return
|
|
if _goop_rng.randf() >= config.alien_goop_drop_chance:
|
|
return
|
|
var slot := goop_slot(enemies.killer_of(handle), Vector2(x, z))
|
|
var added := campaign.state.resources.add_to_pouch("alien_goop", config.alien_goop_drop_qty, slot)
|
|
if added > 0:
|
|
campaign.state.record_event("gathered_alien_goop", added)
|
|
|
|
|
|
## Whose pouch a kill's goop goes to: the killer's (an avatar slot still on the farm), else the
|
|
## scarecrow nearest to where it fell, a standing one before a downed one (solo: always slot 0).
|
|
func goop_slot(killer: int, at: Vector2) -> int:
|
|
var best := -1
|
|
var best_d := INF
|
|
for a in avatars:
|
|
if a.slot == killer:
|
|
return killer
|
|
var d := a.position().distance_squared_to(at) + (0.0 if a.kit.alive else 1e12)
|
|
if d < best_d:
|
|
best_d = d
|
|
best = a.slot
|
|
return maxi(best, 0)
|
|
|
|
|
|
## Keeps the field toward the scarecrow fresh while anything is fighting it.
|
|
func _update_hunt(dt: float) -> void:
|
|
_hunt_wait = maxf(_hunt_wait - dt, 0.0)
|
|
if not _hunt_job.done:
|
|
if _hunt_job.step(config.flow_slice_cells):
|
|
hunt_field = _hunt_job.dist.duplicate()
|
|
behavior.hunt_field = hunt_field
|
|
return
|
|
var hunting := false
|
|
for d in enemies.active_count:
|
|
if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.FIGHT:
|
|
hunting = true
|
|
break
|
|
if not hunting:
|
|
return
|
|
# Toward every scarecrow standing (each enemy follows it to the nearer one).
|
|
var goals := PackedInt32Array()
|
|
var key := 0
|
|
for a in avatars:
|
|
if not a.kit.alive:
|
|
continue
|
|
var p := a.position()
|
|
var c := nav.nearest_free(nav.cell_of(p.x, p.y), 64)
|
|
if c >= 0:
|
|
goals.append(c)
|
|
key = key * 100003 + c + 1
|
|
if goals.is_empty() or (key == _hunt_cell and not hunt_field.is_empty()) or _hunt_wait > 0.0:
|
|
return
|
|
_hunt_cell = key
|
|
_hunt_wait = HUNT_INTERVAL
|
|
_hunt_job.start(goals)
|
|
|
|
|
|
## Whether any ground enemy type goes for crops (then the crop rows get a flow field).
|
|
func _ground_takes_crops() -> bool:
|
|
for type_name: String in config.enemy_types:
|
|
var row := config.enemy(type_name)
|
|
if not bool(row.get("flying", false)) and (row.get("targets", []) as Array).has("crops"):
|
|
return true
|
|
return false
|
|
|
|
|
|
## Where fence breakers head: the walkable cells next to every barrier within guard_range of the
|
|
## crop rows, the pen, or the shed (or next to any barrier, when none guards anything).
|
|
func _breaker_goals() -> PackedInt32Array:
|
|
if structures == null:
|
|
return PackedInt32Array()
|
|
var areas: Array[Rect2] = [zones.zone(FarmZone.Kind.ANIMAL_PEN).rect(), zones.zone(FarmZone.Kind.SUPPLY_SHED).rect()]
|
|
for z in zones.zones_of(FarmZone.Kind.CROP_FIELD): # #13: all three crop fields, not just one
|
|
areas.append(z.rect())
|
|
var guarding: Array[Dictionary] = []
|
|
var barriers: Array[Dictionary] = []
|
|
for e in campaign.state.structures:
|
|
if not structures.blocks(e["type"]):
|
|
continue
|
|
if e["type"] == "workbench" and int(e["hp"]) <= 0:
|
|
continue # broken: nothing left to gain by sending a breaker at it
|
|
barriers.append(e)
|
|
if e["type"] == "workbench":
|
|
guarding.append(e) # #9 Decision 3: it guards its own work area, unconditionally
|
|
continue
|
|
var at := Vector2(e["x"], e["z"])
|
|
for a in areas:
|
|
if a.grow(config.guard_range).has_point(at):
|
|
guarding.append(e)
|
|
break
|
|
var out := PackedInt32Array()
|
|
for e in (guarding if not guarding.is_empty() else barriers):
|
|
var outline := StructureSystem.corners(structures.footprint(e["type"], e["x"], e["z"], e["rot"]))
|
|
var lo := outline[0]
|
|
var hi := outline[0]
|
|
for q in outline:
|
|
lo = lo.min(q)
|
|
hi = hi.max(q)
|
|
for c in nav.free_cells_in(Rect2(lo, hi - lo).grow(1.2)):
|
|
if nav.is_walkable(c) and StructureSystem._distance_to_outline(nav.cell_center(c), outline) <= 1.1:
|
|
out.append(c)
|
|
return out
|
|
|
|
|
|
func _on_phase_changed(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void:
|
|
match phase:
|
|
CampaignController.Phase.DAWN:
|
|
behavior.retreat_all(enemies)
|
|
CampaignController.Phase.MORNING:
|
|
if partner == null and not replica:
|
|
campaign.state.coop = false # a co-op save continued alone: solo rules
|
|
campaign.state.resources.deposit(1) # and player 2's pouch, saved that morning, is in the shed
|
|
enemies.clear()
|
|
projectiles.clear()
|
|
bombs.clear()
|
|
loot.sync_from_state()
|
|
animals.sync_from_state()
|
|
structures.sync_from_state()
|
|
shed_stock.refresh()
|
|
build.set_active(false)
|
|
for a in avatars:
|
|
a.combat.ready_for_morning()
|
|
a.kit.reset_for_morning()
|
|
a.interactions.cancel()
|
|
if a.remote != null:
|
|
a.remote.release()
|
|
if upgrade_panel != null:
|
|
upgrade_panel.close()
|
|
if shed_panel != null:
|
|
shed_panel.close()
|
|
if review_panel != null:
|
|
review_panel.refresh() # after the farm is back in sync (the pen's gate)
|
|
|
|
|
|
## End of the dawn grace: whoever is still on the farm leaves (carrying their loot off), and
|
|
## loot still lying on the ground goes home (crops to their plots, sacks to the shed, animals
|
|
## still following the scarecrow to the pen; #21: loose animals stay loose). #13: grows crops_total for any field that just sprouted (state.night is
|
|
## the night that just finished; nights_survived isn't set to it until right after this signal),
|
|
## so the morning snapshot (retry, the save file) already has it right. The new field's units
|
|
## themselves flip from DORMANT to HOME in loot.sync_from_state(), at the morning that follows.
|
|
func _on_night_ending() -> void:
|
|
enemies.remove_all()
|
|
loot.return_dropped()
|
|
interactions.regen_overnight()
|
|
loot.grow_crops_total(campaign.state.night)
|
|
|
|
|
|
func _unhandled_input(event: InputEvent) -> void:
|
|
var key := event as InputEventKey
|
|
if key == null or not key.pressed or key.echo or not OS.is_debug_build():
|
|
return
|
|
match key.physical_keycode:
|
|
KEY_T:
|
|
spawn_enemy(EnemySystem.TYPE_THIEF)
|
|
KEY_G:
|
|
spawn_enemy(EnemySystem.TYPE_CROW)
|
|
KEY_H:
|
|
spawn_enemy(EnemySystem.TYPE_BREAKER)
|