Task #10: per-instance Turret/Tar Patch leveling (L1-L3)

Adds a per-placed-structure "level" (1-3) to automated_defense and
slowing_trap, upgraded independently (not account-wide) by holding
interact at that specific structure, by day, once it's undamaged
(repair still takes priority while it isn't), for a config-tunable
per-level cost.

Turret L2 fires turret_level_fire_mult (3x, matching the live Rapid
Fire multiplier) as often; L3 keeps that rate and fires
turret_l3_projectiles shots at once in a fan. A tar patch's trigger
footprint and visual grow by trap_level_size_mult per level (L2
double, L3 triple its L1 size); a bigger footprint that would overlap
a neighbor or the world refuses the upgrade with a reason.

FarmState.VERSION bumps 5->6 (STRUCTURE_KEYS gains "level"; migrate()
backfills level 1 on older saves, following the v2->v3 precedent for
night_log). Co-op: an upgrade is driven the same way repair already
is -- entirely host-side, off the partner's held interact button, no
new "req" case -- so the only wire change is forwarding the upgrade
channel's target/progress in the avatar snapshot, same as repair's.

New test_structures.gd coverage: fire interval and projectile count
per turret level, tar patch footprint per level, each proven
independently for two separately-placed structures of the same type,
plus the upgrade rules (repair-first, room, afford) and that level
survives a save/retry round trip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-05 15:48:19 -04:00
parent 0613cca408
commit 62324ff4b1
8 changed files with 468 additions and 33 deletions

View file

@ -446,8 +446,11 @@ static func _enemy_bytes(es: EnemySystem, d: int) -> PackedByteArray:
## 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.
## 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
@ -457,7 +460,7 @@ func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
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]:
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 "")
@ -465,6 +468,8 @@ func _put_avatar(b: StreamPeerBuffer, a: Avatar) -> void:
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:
@ -730,7 +735,7 @@ func _read_avatar(b: StreamPeerBuffer) -> Dictionary:
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"]:
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
@ -740,6 +745,8 @@ func _read_avatar(b: StreamPeerBuffer) -> Dictionary:
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
@ -783,6 +790,9 @@ func _apply_avatar(a: Avatar, rec: Dictionary) -> void:
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:

View file

@ -8,14 +8,14 @@ extends RefCounted
## pouch live in resources). Gather points below full, bought upgrades, and the built structures
## are kept too.
const VERSION := 5
const VERSION := 6
const KEYS: Array[String] = [
"night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp",
"crops_total", "lost_crops", "animals_total", "lost_animals", "penned_animals", "supplies_total",
"shed_raided", "resources", "gather_charges", "upgrades", "structures", "next_structure_id",
"night_events", "night_log", "coop", "partner_max_hp", "partner_hp",
]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp"]
const STRUCTURE_KEYS: Array[String] = ["id", "type", "x", "z", "rot", "hp", "level"]
## Events counted from the morning to the end of the dawn grace, copied into the night's log
## entry when it closes. Theft: supply events count material units, the others crop units or
## animals. Then enemies killed by type and those that escaped with loot; the scarecrow's damage
@ -106,7 +106,8 @@ var gather_charges: Dictionary = {}
## Bought upgrades (id -> level).
var upgrades: Dictionary = {}
## Built structures: {"id", "type", "x", "z" (world position, on the 0.5 m build grid), "rot"
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow)}.
## (0..7, steps of 45 degrees), "hp" (for a slowing trap, the enemies it can still slow), "level"
## (1-3; account-wide upgrades are tracked separately, above -- this is per placed instance, #10)}.
var structures: Array[Dictionary] = []
var next_structure_id: int = 1
@ -131,7 +132,7 @@ static func create(cfg: GameConfig) -> FarmState:
for e in cfg.start_structures:
var t := String(e["type"])
s.structures.append({"id": s.next_structure_id, "type": t, "x": float(e["x"]), "z": float(e["z"]),
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t)})
"rot": int(e.get("rot", 0)), "hp": cfg.structure_hp(t), "level": 1})
s.next_structure_id += 1
return s
@ -393,8 +394,9 @@ static func from_dict(d: Dictionary) -> FarmState:
e["z"] = float(raw["z"])
e["rot"] = int(raw["rot"])
e["hp"] = int(raw["hp"])
e["level"] = int(raw["level"])
if e["id"] < 1 or e["id"] >= s.next_structure_id or ids.has(e["id"]) or e["type"] == "" \
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0:
or e["rot"] < 0 or e["rot"] > 7 or e["hp"] < 0 or e["level"] < 1 or e["level"] > 3:
return null
ids[e["id"]] = true
s.structures.append(e)

View file

@ -199,6 +199,28 @@ extends Resource
## Cells finalized per tick while flow fields rebuild after a structure change.
@export_range(100, 100000) var flow_slice_cells: int = 2000
## Per-instance leveling (StructureSystem.LEVELABLE: automated_defense, slowing_trap; L1-L3), not
## account-wide like the workbench upgrades above. Holding interact at a specific placed structure
## (by day; it must be undamaged first) pays structure_level_costs[type][level - 1] to take it from
## level to level + 1 (index 0: L1->L2, index 1: L2->L3).
@export var structure_level_costs: Dictionary = {
"automated_defense": [{"scrap": 10, "wood": 4, "straw": 2}, {"scrap": 16, "wood": 6, "straw": 4}],
"slowing_trap": [{"scrap": 5, "wood": 2}, {"scrap": 8, "wood": 4}],
}
## Turret L2 fires this many times as often (mirrors the Rapid Fire upgrade's live multiplier,
## 3.0 in game_config.tres); L3 keeps the same rate.
@export var turret_level_fire_mult: float = 3.0
## Turret L3 fires this many shots at once in a fan around the aim direction, turret_l3_spread_deg
## apart (a triangle spread: the outer two off by the full spread from the center shot).
@export_range(1, 8) var turret_l3_projectiles: int = 3
@export var turret_l3_spread_deg: float = 10.0
## A tar patch's footprint (trigger area) and visual grow by this multiple of its L1 size, per
## level (index 0 = L1, so always 1.0).
@export var trap_level_size_mult: Array[float] = [1.0, 2.0, 3.0]
## Holding interact for structure_upgrade_time levels up a structure, paying structure_level_costs
## at the end (by day only; see Interactions).
@export var structure_upgrade_time: float = 2.0
@export_group("Combat")
## Height of the gun muzzle, the bullets, and enemy hit proxies (shots fly horizontally). It
## clears the sunflowers (1.67 m) and the pen fence (1.69 m), so thieves in the field stay

View file

@ -17,6 +17,12 @@ extends Node3D
## * Repair: a damaged structure within REPAIR_REACH comes first. Hold interact for
## repair_time (any phase) to repair it fully for StructureSystem.repair_cost (paid at the
## end); it is refused, once per press, without the materials.
## * Upgrade (#10): a levelable structure (turret, tar patch) within REPAIR_REACH, undamaged
## (repair takes priority while it isn't), comes next. Hold interact by day for
## structure_upgrade_time to level it up one, for StructureSystem.upgrade_cost (paid at the
## end); refused, once per press, without the materials, room (a bigger tar patch may not fit),
## or at Max level. Night-gated like the workbench, unlike repair, since it's a build-mode-style
## decision, not an emergency fix.
## * Deposit: walking into the Supply Shed zone empties the pouch into the shed (no interact,
## and not gated by the shed counter's reach or the shed shop being open).
## * Overnight (the end of the dawn grace) every used point regains regen_per_night charges.
@ -61,6 +67,10 @@ var gather_elapsed: float = 0.0
var repair_target: int = -1
var repairing: int = -1
var repair_elapsed: float = 0.0
## Levelable structure in reach, undamaged (-1 = none), and the one being upgraded (#10).
var upgrade_target: int = -1
var upgrading: int = -1
var upgrade_elapsed: float = 0.0
var _shed: FarmZone
var _interact_requested := false
@ -68,6 +78,7 @@ var _interact_was_held := false
var _denied := false
var _popups: Array[Label3D] = []
var _repair_label: Label3D
var _upgrade_label: Label3D
var _popup_left := PackedFloat32Array()
@ -99,6 +110,17 @@ func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerChar
_repair_label.top_level = true
_repair_label.visible = false
add_child(_repair_label)
_upgrade_label = Label3D.new()
_upgrade_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_upgrade_label.no_depth_test = true
_upgrade_label.shaded = false
_upgrade_label.font_size = 40
_upgrade_label.outline_size = 10
_upgrade_label.pixel_size = 0.0075
_upgrade_label.modulate = Color(0.75, 0.95, 1.0)
_upgrade_label.top_level = true
_upgrade_label.visible = false
add_child(_upgrade_label)
_popup_left.resize(POPUPS)
for i in POPUPS:
var l := Label3D.new()
@ -120,7 +142,7 @@ func charges(n: GatherNode) -> int:
func channeling() -> bool:
return gathering != null or repairing >= 0
return gathering != null or repairing >= 0 or upgrading >= 0
func can_shoot() -> bool:
@ -145,6 +167,7 @@ func step(dt: float) -> void:
shed_panel.close()
cancel()
repair_target = -1
upgrade_target = -1
focus = null
return
var p := Vector2(player.global_position.x, player.global_position.z)
@ -170,6 +193,18 @@ func step(dt: float) -> void:
if structures.repair(id):
message.emit("Repaired (%s)" % ResourceStore.describe(cost), Color(0.6, 1.0, 0.55))
return
if upgrading >= 0:
if not held or not campaign.is_daytime() or structures.upgrade_blocker(upgrading) != "":
cancel()
return
upgrade_elapsed += dt
if upgrade_elapsed >= config.structure_upgrade_time:
var id := upgrading
var cost := structures.upgrade_cost(id)
cancel()
if structures.upgrade(id):
message.emit("Upgraded to L%d (%s)" % [structures.level_of(id), ResourceStore.describe(cost)], Color(0.6, 1.0, 0.55))
return
if gathering != null:
if not held or _blocker(gathering) != "":
cancel()
@ -194,6 +229,24 @@ func step(dt: float) -> void:
_denied = true
message.emit("Not enough to repair: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost)), Color(1.0, 0.8, 0.5))
return
upgrade_target = structures.upgradeable_near(p, REPAIR_REACH) if structures != null else -1
if upgrade_target >= 0:
focus = null
if held and not kit.patching:
if not campaign.is_daytime():
if not _denied:
_denied = true
message.emit("Upgrading is for daytime", Color(1.0, 0.8, 0.5))
else:
var why := structures.upgrade_blocker(upgrade_target)
if why == "":
upgrading = upgrade_target
upgrade_elapsed = 0.0
player.start_channel(&"Hammering")
elif not _denied:
_denied = true
message.emit(why, Color(1.0, 0.8, 0.5))
return
focus = _nearest(p)
if focus is GatherNode and held and not kit.patching:
var why := _blocker(focus)
@ -241,12 +294,25 @@ func _blocker(n: GatherNode) -> String:
return ""
## The upgrade prompt for a levelable structure in reach: what it costs, "Max level", why it
## can't right now, or that upgrading (unlike repair) is for daytime.
func _upgrade_prompt(id: int) -> String:
if not campaign.is_daytime():
return "Upgrading is for daytime"
var why := structures.upgrade_blocker(id)
if why == "":
return "[E / X] Upgrade to L%d (%s)" % [structures.level_of(id) + 1, ResourceStore.describe(structures.upgrade_cost(id))]
return why
func cancel() -> void:
if gathering != null or repairing >= 0:
if gathering != null or repairing >= 0 or upgrading >= 0:
gathering = null
gather_elapsed = 0.0
repairing = -1
repair_elapsed = 0.0
upgrading = -1
upgrade_elapsed = 0.0
player.stop_channel()
@ -337,6 +403,14 @@ func _process(delta: float) -> void:
var cost := structures.repair_cost(shown)
_repair_label.text = "%s %d/%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e["hp"]), structures.max_hp(e["type"]),
"Repairing..." if repairing >= 0 else "[E / X] Repair (%s)" % ResourceStore.describe(cost)]
var ushown := (upgrading if upgrading >= 0 else upgrade_target) if show_labels else -1
_upgrade_label.visible = ushown >= 0
if ushown >= 0:
var e := campaign.state.structure(ushown)
if not e.is_empty():
_upgrade_label.global_position = Vector3(e["x"], 3.3, e["z"])
_upgrade_label.text = "%s L%d\n%s" % [StructureSystem.NAMES[e["type"]], int(e.get("level", 1)),
"Upgrading..." if upgrading >= 0 else _upgrade_prompt(ushown)]
for i in POPUPS:
if _popup_left[i] <= 0.0:
continue

View file

@ -101,6 +101,12 @@ static func migrate(d: Dictionary) -> Dictionary:
penned.append(id)
out["penned_animals"] = penned
out["version"] = 5
5:
# Version 6 adds per-instance structure leveling (#10): older structures are level 1.
for entry: Variant in out.get("structures", []):
if entry is Dictionary and not (entry as Dictionary).has("level"):
entry["level"] = 1
out["version"] = 6
_:
return {}
return out

View file

@ -5,8 +5,8 @@ extends Node3D
## fence 2 m segment that ground enemies can't walk through.
## gate a fence segment the scarecrow walks through (it swings open as the
## scarecrow nears; it has no collision for the scarecrow) but enemies can't.
## slowing_trap 1.5 m patch: a ground enemy stepping on it moves at trap_slow_factor speed
## for trap_slow_time, using up one of its trap_triggers. Doesn't block.
## slowing_trap 1.5 m patch (at L1): a ground enemy stepping on it moves at trap_slow_factor
## speed for trap_slow_time, using up one of its trap_triggers. Doesn't block.
## automated_defense 1 m post that shoots the nearest enemy within turret_range with a clear
## line, from the shared shot pool, every turret_fire_interval (leading the
## target). Flying enemies are hit too (Step 9); fences, gates, and traps
@ -16,13 +16,23 @@ extends Node3D
## bar, a red tint, and wobble on each hit; a broken one leaves debris and emits destroyed
## ("breach"). Positions snap to a 0.5 m grid, rotations to 45 degree steps (fences run 2 m along
## the grid, 1.5 x 1.5 m on the diagonal, so chains line up either way).
##
## Leveling (#10): a turret or a tar patch (LEVELABLE) can be upgraded independently, L1-L3, from
## L1 (Interactions, holding interact at that specific structure; it must be undamaged and the
## cost affordable -- see upgrade_blocker). A turret at L2 fires turret_level_fire_mult times as
## often (3x, the same live multiplier as the player's Rapid Fire upgrade); L3 keeps that rate but
## fires turret_l3_projectiles shots at once in a fan. A tar patch's footprint and visual grow by
## trap_level_size_mult[level - 1] (L2 double, L3 triple its L1 size); upgrading refuses with a
## reason if the bigger footprint would overlap another structure or the world.
signal layout_changed
signal built(id: int, type: String)
signal destroyed(id: int, type: String, position: Vector3)
## Damaged but still standing; repaired fully; an automated defense shot; a trap slowed someone.
## Damaged but still standing; repaired fully; leveled up; an automated defense shot; a trap
## slowed someone.
signal hurt(id: int, position: Vector3)
signal repaired(id: int)
signal leveled_up(id: int, level: int)
signal turret_fired(position: Vector3)
signal trap_sprung(position: Vector3)
@ -34,6 +44,9 @@ const NAMES := {
"slowing_trap": "Tar patch",
"automated_defense": "Turret",
}
## Structure types with a per-instance level (#10); every other type is always level 1.
const LEVELABLE: Array[String] = ["automated_defense", "slowing_trap"]
const MAX_LEVEL := 3
const GRID := 0.5
const FENCE_LENGTH := 2.0
const DIAGONAL_FENCE_LENGTH := 2.1213 # 1.5 * sqrt(2)
@ -128,9 +141,10 @@ static func snap(p: Vector2) -> Vector2:
return Vector2(roundf(p.x / GRID) * GRID, roundf(p.y / GRID) * GRID)
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z).
func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
var half := Vector2(0.75, 0.75) if type == "slowing_trap" else Vector2(0.5, 0.5)
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z). level
## only matters for a slowing_trap (trap_level_size_mult); every other type ignores it.
func footprint(type: String, x: float, z: float, rot: int, level: int = 1) -> Dictionary:
var half := Vector2(0.75, 0.75) * trap_size_mult(level) if type == "slowing_trap" else Vector2(0.5, 0.5)
var angle := 0.0
if type == "fence" or type == "gate":
half = Vector2((DIAGONAL_FENCE_LENGTH if rot % 2 == 1 else FENCE_LENGTH) * 0.5, FENCE_THICKNESS * 0.5)
@ -138,6 +152,21 @@ func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
return {"center": Vector2(x, z), "half": half, "angle": angle}
## A slowing trap's footprint/visual size at level (1-3), relative to its L1 size.
func trap_size_mult(level: int) -> float:
var mults := config.trap_level_size_mult
return float(mults[clampi(level - 1, 0, mults.size() - 1)]) if not mults.is_empty() else 1.0
func is_levelable(type: String) -> bool:
return LEVELABLE.has(type)
func level_of(id: int) -> int:
var e := campaign.state.structure(id)
return int(e.get("level", 1)) if not e.is_empty() else 1
## Closed outline (5 points) of a footprint, optionally shrunk along its length / width.
static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float = 0.0) -> PackedVector2Array:
var c: Vector2 = fp["center"]
@ -167,7 +196,7 @@ func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) ->
return "Not on the crops"
var tight := corners(fp, 0.2, 0.02)
for e in campaign.state.structures:
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"]), 0.2, 0.02)):
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))), 0.2, 0.02)):
return "Something is built here already"
if _world_blocked(fp):
return "Blocked"
@ -196,7 +225,7 @@ func place(type: String, x: float, z: float, rot: int) -> int:
return -1
var id := s.next_structure_id
s.next_structure_id += 1
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type)})
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type), "level": 1})
s.record_event("structures_built")
_add_view(s.structures[s.structures.size() - 1])
_update_nav()
@ -274,6 +303,65 @@ func repair(id: int) -> bool:
return true
## What upgrading this structure to its next level costs now (empty if it isn't levelable or is
## already at MAX_LEVEL, regardless of whether it's otherwise affordable or in reach).
func upgrade_cost(id: int) -> Dictionary:
var e := campaign.state.structure(id)
if e.is_empty() or not is_levelable(e["type"]):
return {}
var level := int(e.get("level", 1))
if level >= MAX_LEVEL:
return {}
var tiers: Array = config.structure_level_costs.get(e["type"], [])
var idx := level - 1 # 0: L1 -> L2, 1: L2 -> L3
return tiers[idx] if idx >= 0 and idx < tiers.size() else {}
## Why id can't be upgraded right now ("" if it can): levelable, undamaged (repair takes
## priority), under MAX_LEVEL, a bigger tar patch footprint clear of neighbors and the world, and
## the cost affordable. Doesn't check the time of day (Interactions, like the build-mode rules).
func upgrade_blocker(id: int) -> String:
var e := campaign.state.structure(id)
if e.is_empty() or not is_levelable(e["type"]):
return "Can't be upgraded"
if int(e["hp"]) < max_hp(e["type"]):
return "Repair it first"
var level := int(e.get("level", 1))
var cost := upgrade_cost(id)
if level >= MAX_LEVEL or cost.is_empty():
return "Max level"
if e["type"] == "slowing_trap":
var fp := footprint(e["type"], e["x"], e["z"], e["rot"], level + 1)
var tight := corners(fp, 0.2, 0.02)
for other in campaign.state.structures:
if int(other["id"]) == id:
continue
var other_fp := footprint(other["type"], other["x"], other["z"], other["rot"], int(other.get("level", 1)))
if _overlap(tight, corners(other_fp, 0.2, 0.02)):
return "Not enough room to upgrade"
if _world_blocked(fp):
return "Not enough room to upgrade"
if not campaign.state.resources.can_afford(cost):
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
return ""
## Pays and levels a structure up by one (see upgrade_blocker). Returns false if it couldn't be.
func upgrade(id: int) -> bool:
if upgrade_blocker(id) != "":
return false
var cost := upgrade_cost(id)
if not campaign.state.pay(cost):
return false
var e := campaign.state.structure(id)
e["level"] = int(e.get("level", 1)) + 1
campaign.state.record_event("upgrades_bought")
_rebuild_view(id)
_update_nav()
leveled_up.emit(id, int(e["level"]))
return true
## The structure whose footprint is within reach of p, preferring damaged ones, or -1.
func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int:
var best := -1
@ -281,7 +369,22 @@ func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int
for e in campaign.state.structures:
if damaged_only and int(e["hp"]) >= max_hp(e["type"]):
continue
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"])))
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
if d <= reach and d < best_d:
best = int(e["id"])
best_d = d
return best
## The nearest levelable structure (turret, tar patch) whose footprint is within reach of p, or -1
## (whether or not it can actually be upgraded right now -- see upgrade_blocker).
func upgradeable_near(p: Vector2, reach: float) -> int:
var best := -1
var best_d := INF
for e in campaign.state.structures:
if not is_levelable(e["type"]):
continue
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1)))))
if d <= reach and d < best_d:
best = int(e["id"])
best_d = d
@ -294,7 +397,8 @@ func try_trap(x: float, z: float) -> bool:
for e in campaign.state.structures:
if e["type"] != "slowing_trap" or int(e["hp"]) <= 0:
continue
if absf(x - float(e["x"])) <= 0.75 and absf(z - float(e["z"])) <= 0.75:
var half := 0.75 * trap_size_mult(int(e.get("level", 1)))
if absf(x - float(e["x"])) <= half and absf(z - float(e["z"])) <= half:
e["hp"] = int(e["hp"]) - 1
trap_sprung.emit(Vector3(e["x"], 0.0, e["z"]))
return true
@ -329,9 +433,23 @@ func step(dt: float) -> void:
var aim := Vector2(enemies.pos_x[target] + enemies.vel_x[target] * lead, enemies.pos_z[target] + enemies.vel_z[target] * lead) - from
var dir := Vector3(aim.x, 0.0, aim.y).normalized()
var origin := Vector3(from.x, config.combat_height, from.y)
projectiles.fire(origin, origin + dir * 0.6, dir)
var level := int(e.get("level", 1))
if level >= 3:
# L3: turret_l3_projectiles shots at once, fanned turret_l3_spread_deg apart (a
# triangle spread: the center shot plus one off either side of dir).
var shots: int = config.turret_l3_projectiles
var spread := deg_to_rad(config.turret_l3_spread_deg)
for i in shots:
var offset := (float(i) - float(shots - 1) * 0.5) * spread
var shot_dir := dir.rotated(Vector3.UP, offset)
projectiles.fire(origin, origin + shot_dir * 0.6, shot_dir)
else:
projectiles.fire(origin, origin + dir * 0.6, dir)
turret_fired.emit(origin)
_turret_cd[id] = config.turret_fire_interval
var interval := config.turret_fire_interval
if level >= 2:
interval /= config.turret_level_fire_mult
_turret_cd[id] = interval
var head: Node3D = _heads.get(id)
if head != null:
head.rotation.y = atan2(-dir.x, -dir.z)
@ -414,18 +532,32 @@ func _remove(id: int) -> void:
_update_nav()
## Rebuilds a structure's view after a level change (its size or its gun may have changed), keeping
## its cooldown (a turret doesn't reset its reload on leveling up).
func _rebuild_view(id: int) -> void:
var e := campaign.state.structure(id)
if e.is_empty():
return
var view: Node3D = _views.get(id)
if view != null:
view.queue_free()
for d in [_views, _bars, _tints, _wobble, _heads]:
(d as Dictionary).erase(id)
_add_view(e)
func _update_nav() -> void:
var entries: Array = []
for e in campaign.state.structures:
if blocks(e["type"]):
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"]))})
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"], int(e.get("level", 1))))})
nav.set_structures(entries)
layout_changed.emit()
func _add_view(e: Dictionary) -> void:
var id: int = e["id"]
var view := _build_view(e["type"], e["rot"])
var view := _build_view(e["type"], e["rot"], int(e.get("level", 1)))
view.name = "%s_%d" % [e["type"], id]
add_child(view)
_views[id] = view
@ -460,11 +592,11 @@ func _add_view(e: Dictionary) -> void:
## The visual (and, for barriers other than gates, collision) of a structure, centered on its
## footprint and rotated to it.
func _build_view(type: String, rot: int) -> Node3D:
## footprint and rotated to it. level only changes a slowing_trap's size (trap_size_mult).
func _build_view(type: String, rot: int, level: int = 1) -> Node3D:
var root := Node3D.new()
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
var fp := footprint(type, 0.0, 0.0, rot)
var fp := footprint(type, 0.0, 0.0, rot, level)
root.rotation.y = -float(fp["angle"])
match type:
"fence":
@ -484,10 +616,11 @@ func _build_view(type: String, rot: int) -> Node3D:
post.position = Vector3(end * 0.95, 0.0, 0.0)
root.add_child(post)
"slowing_trap":
var mult := trap_size_mult(level)
var tar := MeshInstance3D.new()
tar.name = "Tar"
var box := BoxMesh.new()
box.size = Vector3(1.4, 0.06, 1.4)
box.size = Vector3(1.4, 0.06, 1.4) * mult
var mat := StandardMaterial3D.new()
mat.albedo_color = Color(0.1, 0.07, 0.05)
mat.roughness = 0.2
@ -497,7 +630,7 @@ func _build_view(type: String, rot: int) -> Node3D:
tar.position.y = 0.04
root.add_child(tar)
var bucket := _instance("prop/bucket_001.tscn")
bucket.position = Vector3(0.55, 0.0, 0.55)
bucket.position = Vector3(0.55 * mult, 0.0, 0.55 * mult)
_strip_collision(bucket)
root.add_child(bucket)
"automated_defense":