harvest/game/scripts/loot_system.gd
Forrest 62edb8e04c Task #13: two new crop fields with staged growth (Night 2 / Night 4)
Adds a Lettuce/Cabbage field (ids 31-40, x -11..-1 z 2..12) and a Corn field
(ids 41-50, x 2..12 z 2..12), each 2 plots of 5 units, placeholder plants
reusing plant_007/plant_008. CropUnit gains crop (cosmetic) and sprout_night
(0/2/4) fields. LootSystem gains a DORMANT status: a unit whose field hasn't
sprouted (FarmState.nights_survived < sprout_night) is hidden and never
claimable/recoverable, and is excluded from crops_total so it can't affect
scoring or the "farm stripped" check. sync_from_state() derives DORMANT vs.
HOME from nights_survived every morning (and after a retry/load), and
self-heals crops_total to the sprouted count; FarmSim.grow_crops_total() also
grows it right at night_ending so the morning snapshot (retry, the save file)
already has it right. FarmZones.crop_units() now gathers CropUnits from every
CROP_FIELD zone (there are three now), not just the first found; the same fix
applies to FarmSim's crop-area rect and the fence breakers' guarded areas.

Reworks test_farm_layout's zone-count and crop checks for the extra fields,
and test_theft's start-of-run and FarmState-consistency checks, which assumed
every crop unit was always in play; adds test_theft cases for both fields
sprouting on schedule, dormant units being unclaimable, and a sprouted unit
being stealable and scored, including a save/JSON round trip. Nudges
test_coop's co-op build spot into the 3 m walkway between the two new fields,
since its old spot now sits on the corn field's rows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 15:52:38 -04:00

766 lines
27 KiB
GDScript

class_name LootSystem
extends Node3D
## Runtime state and feedback of everything thieves can take, on top of the persistent record in
## FarmState. Three categories share one id space (1..item_count):
## CROP ids 1..unit_count: one crop unit each (CropUnit.unit_id), at home in its plot.
## ANIMAL the next animal_count ids: one animal each (AnimalSystem moves it), at home in the pen.
## SUPPLY the last SACKS ids: sacks for bundles of the shed's stock. A sack at home is "in the
## shed": it can be claimed while the shed has stock, and the thief takes it from the pile
## of the material the shed holds most of. Picking it up fills it with up to
## supply_bundle units of that material (never more than there is).
## Each item has a status:
## HOME in its plot, the pen, or the shed. One thief at a time may claim it: it is then
## targeted ("!" marker) and, while being taken, shows a filling progress ring.
## CARRIED on a thief, outlined in its category's color, with a badge over it.
## DROPPED its carrier was stopped. A crop or a sack lies on the ground, glowing; an animal is
## loose and makes for the farm's edge (AnimalSystem). The scarecrow walks up to it to
## recover it (a loose animal then follows it, at most max_following_animals at once),
## and another thief may claim it.
## FOLLOWING animals only: following the scarecrow; back inside the pen it is home.
## LOOSE animals only (#12): starts here, scattered outside the pen, grazing calmly in place
## (AnimalSystem) instead of making for the edge. A thief may still claim and carry one
## off (then it's DROPPED, same as any theft: it runs for the edge). The scarecrow
## walking up to it starts it following, same as a dropped animal; entering the pen
## makes it HOME, and FarmState records it as penned so sync_from_state() keeps it
## home each morning instead of resetting it loose.
## LOST carried (or, for an animal, wandered) off the farm. Crops and animals are recorded
## in FarmState and gone for the rest of the run; a sack's contents are gone and the
## sack is free for the next theft.
## DORMANT crops only (#13): a unit of one of the later fields (lettuce/cabbage, corn) that
## hasn't sprouted yet (FarmState.nights_survived < CropUnit.sprout_night). Hidden,
## never claimable or recoverable, not counted in FarmState.crops_total, and ignored
## by alerts. sync_from_state() derives this every morning (and after a retry/load);
## it never shows up mid-night, since a unit only sprouts between mornings.
## Supplies in a carried or dropped sack still count as on the farm (FarmState.supplies_in_transit).
## Claims and carriers are enemy handles (id + generation), so a stale handle from a reused enemy
## slot can never move an item. Every change emits loot_event (toasts now, sounds later); steals,
## recoveries, strays, and supply losses count toward the night's record.
enum Category { CROP, ANIMAL, SUPPLY }
enum Status { HOME, CARRIED, DROPPED, LOST, FOLLOWING, LOOSE, DORMANT }
enum Threat { NONE, TARGETED, CARRIED, DROPPED }
## EnemySystem.want for a thief with no set target (it goes by GameConfig.target_weights).
const ANY := 255
## Every category (a bit per Category), for claim()'s allowed mask.
const ALL := 7
const SACKS := 6
const CATEGORY_KEYS: Array[String] = ["crops", "animals", "supplies"]
const CATEGORY_COLORS := {
Category.CROP: Color(1.0, 0.8, 0.15),
Category.ANIMAL: Color(1.0, 0.45, 0.75),
Category.SUPPLY: Color(0.35, 0.8, 1.0),
}
## Badge interiors (loot_icon.gdshader): fill and center per category.
const BADGE_FILL := {
Category.CROP: [Color(1.0, 0.82, 0.18), Color(0.32, 0.18, 0.07)],
Category.ANIMAL: [Color(1.0, 0.62, 0.78), Color(1.0, 0.92, 0.95)],
Category.SUPPLY: [Color(0.78, 0.62, 0.4), Color(0.35, 0.8, 1.0)],
}
const TOKEN_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_007.tscn"
const SACK_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_002.tscn"
const THREAT_COLORS := {
Threat.TARGETED: Color(1.0, 0.6, 0.1),
Threat.CARRIED: Color(1.0, 0.22, 0.15),
Threat.DROPPED: Color(1.0, 0.9, 0.25),
}
## kind: &"targeted", &"stolen", &"dropped", &"recovered", &"returned" (back home without the
## scarecrow's help: auto at dawn, or an animal dropped inside the pen), &"lost", &"following",
## &"follow_full" (the scarecrow already leads the most animals it can), &"strayed" (an animal
## wandered out of an open pen).
signal loot_event(kind: StringName, id: int, position: Vector3)
var campaign: CampaignController
var enemies: EnemySystem
var config: GameConfig
## Set by FarmSim: animal positions and the shed's piles (where supply thieves stand).
var animals: AnimalSystem
var shed_stock: ShedStock
## Crop units (ids 1..unit_count), then animals, then sacks.
var unit_count: int = 0
var animal_count: int = 0
var item_count: int = 0
# Per item, indexed by id (index 0 unused).
var category := PackedByteArray()
var status := PackedByteArray()
var holder := PackedInt32Array()
var progress := PackedFloat32Array()
## Crops: the plot position. Sacks: the pile spot it is taken from (set when claimed).
var home := PackedVector2Array()
var ground := PackedVector2Array()
## Sacks: the material and how much of it they hold.
var sack_material: Array[String] = []
var sack_amount := PackedInt32Array()
## What the HUD should point at this frame, and where (filled in _process).
var threat := PackedByteArray()
var focus := PackedVector3Array()
var _units: Array[CropUnit] = []
var _markers: Array[Label3D] = []
var _rings: Array[MeshInstance3D] = []
var _ring_mats: Array[ShaderMaterial] = []
var _tokens: Array[Node3D] = []
var _icons: Array[MeshInstance3D] = []
var _icon_mats: Array[ShaderMaterial] = []
var _warned := PackedByteArray()
var _outline := {} # Category -> StandardMaterial3D
var _rng := RandomNumberGenerator.new()
var _time: float = 0.0
func setup(p_campaign: CampaignController, units: Array[CropUnit], p_enemies: EnemySystem, p_animal_count: int = 0) -> void:
campaign = p_campaign
config = p_campaign.config
enemies = p_enemies
unit_count = units.size()
animal_count = p_animal_count
item_count = unit_count + animal_count + SACKS
var n := item_count + 1
for a: PackedByteArray in [category, status, threat, _warned]:
a.resize(n)
for a: PackedInt32Array in [holder, sack_amount]:
a.resize(n)
progress.resize(n)
home.resize(n)
ground.resize(n)
focus.resize(n)
sack_material.resize(n)
sack_material.fill("")
_units.resize(unit_count + 1)
_markers.resize(n)
_rings.resize(n)
_ring_mats.resize(n)
_tokens.resize(n)
_icons.resize(n)
_icon_mats.resize(n)
_rng.seed = 20261003
for c: Category in CATEGORY_COLORS:
_outline[c] = outline_material(CATEGORY_COLORS[c])
var ring_shader := load("res://game/resources/steal_ring.gdshader") as Shader
var icon_shader := load("res://game/resources/loot_icon.gdshader") as Shader
var token_scene := load(TOKEN_SCENE) as PackedScene
var sack_scene := load(SACK_SCENE) as PackedScene
for id in range(1, n):
category[id] = _category_of(id)
_markers[id] = _marker()
_ring_mats[id] = ShaderMaterial.new()
_ring_mats[id].shader = ring_shader
_rings[id] = _billboard(1.1, _ring_mats[id])
_icon_mats[id] = ShaderMaterial.new()
_icon_mats[id].shader = icon_shader
var fill: Array = BADGE_FILL[category[id]]
_icon_mats[id].set_shader_parameter("fill_color", fill[0])
_icon_mats[id].set_shader_parameter("center_color", fill[1])
_icons[id] = _billboard(0.9, _icon_mats[id])
var token: Node3D = null
match category[id]:
Category.CROP:
token = token_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.6
Category.SUPPLY:
token = sack_scene.instantiate() as Node3D
token.scale = Vector3.ONE * 0.85
StructureSystem._strip_collision(token)
if token != null:
token.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
for mi in token.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_overlay = _outline[category[id]]
add_child(token)
_tokens[id] = token
for u in units:
_units[u.unit_id] = u
home[u.unit_id] = Vector2(u.global_position.x, u.global_position.z)
sync_from_state()
## Every item back home, or gone if the farm state records it as lost (new vacation, retry,
## load). Clears all claims and empties every sack. Crops (#13): a unit whose field hasn't
## sprouted yet (FarmState.nights_survived < CropUnit.sprout_night) goes DORMANT instead of HOME;
## crops_total is repaired to match the sprouted count here too, so a stale save (or one from
## before this field existed) can't disagree with what's actually shown.
func sync_from_state() -> void:
var s := campaign.state
var sprouted_count := 0
for id in range(1, item_count + 1):
match category[id]:
Category.CROP:
var sprouted: bool = s.nights_survived >= _units[id].sprout_night
if sprouted:
sprouted_count += 1
status[id] = Status.LOST if s.is_crop_lost(id) else (Status.HOME if sprouted else Status.DORMANT)
_units[id].visible = status[id] == Status.HOME
Category.ANIMAL:
var aid := animal_index(id)
if s.is_animal_lost(aid):
status[id] = Status.LOST
elif s.is_animal_penned(aid):
status[id] = Status.HOME
else:
status[id] = Status.LOOSE
Category.SUPPLY:
status[id] = Status.HOME
sack_amount[id] = 0
holder[id] = -1
progress[id] = 0.0
_warned[id] = 0
if sprouted_count > s.crops_total:
s.crops_total = sprouted_count
s.supplies_in_transit = 0
update_visuals()
## Grows crops_total to include a field the moment it sprouts (called from FarmSim at
## night_ending, with the night that just finished: FarmState.nights_survived isn't set to it
## until right after, so this can't use nights_survived yet). A plain FarmState var, so once
## grown it's part of the morning snapshot (retry and the save file) and sync_from_state() never
## has to repair it down again. Never shrinks crops_total.
func grow_crops_total(night_survived: int) -> void:
var s := campaign.state
var sprouted_count := 0
for id in range(1, unit_count + 1):
if night_survived >= _units[id].sprout_night:
sprouted_count += 1
if sprouted_count > s.crops_total:
s.crops_total = sprouted_count
## Co-op host: every item's status, holder (enemy handle), steal progress, ground spot, and sack.
func replica_record() -> Dictionary:
var shown := PackedByteArray()
shown.resize(unit_count + 1)
for id in range(1, unit_count + 1):
shown[id] = 1 if _units[id].visible else 0
return {"status": status, "holder": holder, "progress": progress, "ground": ground, "amount": sack_amount,
"material": sack_material.duplicate(), "transit": campaign.state.supplies_in_transit, "units": shown}
## Co-op partner: shows the host's items (resolve: host enemy handle -> this machine's handle).
func apply_replica(rec: Dictionary, resolve: Callable) -> void:
var st: PackedByteArray = rec.get("status", PackedByteArray())
if st.size() != status.size():
return
status = st
var hosts: PackedInt32Array = rec["holder"]
for id in hosts.size():
holder[id] = int(resolve.call(hosts[id])) if hosts[id] >= 0 else -1
progress = rec["progress"]
ground = rec["ground"]
sack_amount = rec["amount"]
for i in mini(sack_material.size(), (rec["material"] as Array).size()):
sack_material[i] = String(rec["material"][i])
campaign.state.supplies_in_transit = int(rec.get("transit", 0))
var shown: PackedByteArray = rec.get("units", PackedByteArray())
for id in range(1, mini(unit_count + 1, shown.size())):
_units[id].visible = shown[id] == 1
func is_valid_unit(id: int) -> bool:
return id >= 1 and id <= item_count
func is_home(id: int) -> bool:
return is_valid_unit(id) and status[id] == Status.HOME
## Animal ids in FarmState (1..animal_count) <-> item ids.
func animal_index(id: int) -> int:
return id - unit_count
func animal_item(index: int) -> int:
return unit_count + index
func first_sack() -> int:
return unit_count + animal_count + 1
func is_claimed_by(id: int, handle: int) -> bool:
return is_valid_unit(id) and handle >= 0 and holder[id] == handle \
and (status[id] == Status.HOME or status[id] == Status.DROPPED or status[id] == Status.LOOSE)
## Where a thief has to go for this item: its plot, the animal itself, the shed pile, or where it
## was dropped.
func position_of(id: int) -> Vector2:
if category[id] == Category.ANIMAL and animals != null:
return animals.position(animal_index(id))
return ground[id] if status[id] == Status.DROPPED else home[id]
## Seconds a thief needs to take this item.
func steal_time(id: int) -> float:
match category[id]:
Category.ANIMAL:
return config.animal_capture_time
Category.SUPPLY:
return config.supply_steal_time
return config.crop_steal_time
## Claims an item for a thief, only from the allowed categories (a bit per Category: what its
## enemy type takes): the nearest unclaimed dropped item in view within range (in clear view
## unless need_line is off, for flyers), else one at home in the wanted category (a random crop or
## animal, a sack at the pile of the material the shed holds most of), else in another allowed
## category, picked by target_weights. Returns the id, or -1 if nothing is left.
func claim(handle: int, from: Vector2, nav: FarmNavigation, view_range: float, want: int = ANY,
allowed: int = ALL, need_line: bool = true) -> int:
var best := -1
var best_d := view_range
for id in range(1, item_count + 1):
if status[id] == Status.DROPPED and holder[id] == -1 and (allowed & (1 << category[id])) != 0:
var at := position_of(id)
var d := at.distance_to(from)
if d < best_d and (not need_line or nav.line_clear(from.x, from.y, at.x, at.y)):
best = id
best_d = d
if best < 0:
for c in _preference(want):
if (allowed & (1 << c)) == 0:
continue
best = _claim_home(c)
if best > 0:
break
if best < 0:
return -1
holder[best] = handle
progress[best] = 0.0
loot_event.emit(&"targeted", best, _world(position_of(best)))
return best
## Whether a thief could claim anything at home (or, for an animal, loose) in this category now.
func available(c: Category) -> bool:
match c:
Category.SUPPLY:
return campaign.state.resources.shed_total() > 0 and _free_sack() > 0
_:
for id in _ids(c):
if (status[id] == Status.HOME or status[id] == Status.LOOSE) and holder[id] == -1:
return true
return false
func release(id: int, handle: int) -> void:
if is_claimed_by(id, handle):
holder[id] = -1
progress[id] = 0.0
func set_progress(id: int, handle: int, value: float) -> void:
if is_claimed_by(id, handle):
progress[id] = clampf(value, 0.0, 1.0)
## The claiming thief takes the item. Returns false if it doesn't hold the claim, or (for a sack)
## the shed has nothing left; the claim is released then.
func pick_up(id: int, handle: int) -> bool:
if not is_claimed_by(id, handle):
return false
var s := campaign.state
var at := position_of(id)
match category[id]:
Category.CROP:
_units[id].visible = false
s.record_event("crops_stolen")
Category.ANIMAL:
s.record_event("animals_stolen")
Category.SUPPLY:
if status[id] == Status.HOME:
var r := s.resources
var m := sack_material[id]
if m == "" or int(r.shed[m]) <= 0:
m = r.most_stocked()
if m == "":
release(id, handle)
return false
var amount := mini(config.supply_bundle, int(r.shed[m]))
r.shed[m] = int(r.shed[m]) - amount
sack_material[id] = m
sack_amount[id] = amount
s.supplies_in_transit += amount
s.record_event("supplies_stolen", amount)
if r.shed_total() == 0:
s.shed_raided = true
status[id] = Status.CARRIED
progress[id] = 0.0
loot_event.emit(&"stolen", id, _world(at))
return true
## The carrier was stopped at (x, z).
func drop(id: int, handle: int, x: float, z: float) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
status[id] = Status.DROPPED
holder[id] = -1
ground[id] = Vector2(x, z)
if category[id] == Category.ANIMAL and animals != null:
animals.place(animal_index(id), ground[id])
loot_event.emit(&"dropped", id, _world(ground[id]))
## The carrier left the farm with the item: it is lost for good (a sack's contents are).
func escape(id: int, handle: int) -> void:
if not is_valid_unit(id) or status[id] != Status.CARRIED or holder[id] != handle:
return
_lose(id)
## The scarecrow got a dropped (or loose, #12) item back: a crop returns to its plot, a sack to
## the shed, and an animal starts following (if the scarecrow has room for another) -- a dropped
## one recovered from a thief exactly as before, and a loose one led in for the first time.
func recover(id: int) -> bool:
if not is_valid_unit(id):
return false
var loose_animal := category[id] == Category.ANIMAL and status[id] == Status.LOOSE
if status[id] != Status.DROPPED and not loose_animal:
return false
var s := campaign.state
match category[id]:
Category.ANIMAL:
if followers() >= config.max_following_animals:
return false
status[id] = Status.FOLLOWING
holder[id] = -1
if animals != null:
animals.start_following(animal_index(id))
loot_event.emit(&"following", id, _world(position_of(id)))
return true
Category.CROP:
_return_home(id)
s.record_event("crops_recovered")
Category.SUPPLY:
s.record_event("supplies_recovered", sack_amount[id])
loot_event.emit(&"recovered", id, _world(ground[id]))
_empty_sack(id, true)
return true
loot_event.emit(&"recovered", id, _world(home[id]))
return true
## An animal (loose, or following the scarecrow) is back inside the pen.
func animal_home(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL:
return
if status[id] != Status.FOLLOWING and status[id] != Status.DROPPED:
return
var led := status[id] == Status.FOLLOWING
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
campaign.state.pen_animal(animal_index(id))
if led:
campaign.state.record_event("animals_recovered")
loot_event.emit(&"recovered" if led else &"returned", id, _world(position_of(id)))
## An animal at home walks out of the open pen: it is loose now.
func animal_strays(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.HOME or holder[id] != -1:
return
status[id] = Status.DROPPED
ground[id] = position_of(id)
campaign.state.record_event("animals_strayed")
loot_event.emit(&"strayed", id, _world(ground[id]))
## A loose animal got off the farm on its own.
func animal_escaped(id: int) -> void:
if not is_valid_unit(id) or category[id] != Category.ANIMAL or status[id] != Status.DROPPED:
return
_lose(id)
## End of the dawn grace (D6): dropped items still on the ground go home (crops to their plots,
## sacks to the shed); loose and following animals are back in the pen.
func return_dropped() -> void:
for id in range(1, item_count + 1):
var st := status[id]
if st == Status.DROPPED or (st == Status.FOLLOWING and category[id] == Category.ANIMAL):
var at := _world(position_of(id))
if category[id] == Category.SUPPLY:
_empty_sack(id, true)
else:
_return_home(id)
loot_event.emit(&"returned", id, at)
## Settles what a removed enemy held: a killed carrier drops its loot, one that left at the end
## of the night takes it along, and any claim is released.
func on_enemy_removed(handle: int, reason: EnemySystem.Removal, x: float, z: float, carried: int, targeted: int) -> void:
if carried >= 0:
if reason == EnemySystem.Removal.KILLED:
drop(carried, handle, x, z)
elif reason == EnemySystem.Removal.LEFT:
escape(carried, handle)
if targeted >= 0:
release(targeted, handle)
## Physics tick: the scarecrow recovers dropped items it walks up to (a loose animal starts
## following it; with no room left it says so once per approach).
## Co-op: which scarecrow (0 = player 1, 1 = player 2) recovered last (a loose animal follows it).
var recoverer: int = 0
## Recovery by touch for one scarecrow (who: 0 = player 1, 1 = player 2; call once each).
func step(scarecrow: Vector2, who: int = 0) -> void:
recoverer = who
var r2 := config.pickup_radius * config.pickup_radius
for id in range(1, item_count + 1):
var recoverable := status[id] == Status.DROPPED or (category[id] == Category.ANIMAL and status[id] == Status.LOOSE)
if not recoverable:
_warned[id] = 0
continue
var near := position_of(id).distance_squared_to(scarecrow) <= r2
if not near:
_warned[id] = 0
elif not recover(id) and _warned[id] == 0:
_warned[id] = 1
loot_event.emit(&"follow_full", id, _world(position_of(id)))
func followers() -> int:
return count(Status.FOLLOWING, Category.ANIMAL)
## Items with this status, in one category (or all, cat = -1).
func count(which: Status, cat: int = -1) -> int:
var n := 0
for id in range(1, item_count + 1):
if status[id] == which and (cat < 0 or category[id] == cat):
n += 1
return n
## "crop", "pig", "sack of wood": what an item is, for messages.
func noun(id: int) -> String:
match category[id]:
Category.ANIMAL:
return animals.kind(animal_index(id)) if animals != null else "animal"
Category.SUPPLY:
return "%d %s" % [sack_amount[id], sack_material[id]] if sack_amount[id] > 0 else "supplies"
return "crop"
func _process(delta: float) -> void:
_time += delta
update_visuals()
## Places markers, rings, tokens, and badges, and fills threat / focus for the HUD.
func update_visuals() -> void:
var bob := sin(_time * 5.0)
for id in range(1, item_count + 1):
var st := status[id]
var cat := category[id]
var h := position_of(id) if st == Status.HOME or st == Status.FOLLOWING else home[id]
var top := 2.0 if cat == Category.ANIMAL else 3.2
var targeted := st == Status.HOME and holder[id] >= 0
var marker := _markers[id]
var ring := _rings[id]
ring.visible = targeted and progress[id] > 0.0
marker.visible = targeted
if targeted:
marker.position = Vector3(h.x, (top + 0.55 if ring.visible else top) + bob * 0.12, h.y)
if ring.visible:
ring.position = Vector3(h.x, top - 0.75, h.y)
_ring_mats[id].set_shader_parameter("progress", progress[id])
var token := _tokens[id]
var icon := _icons[id]
threat[id] = Threat.TARGETED if targeted else Threat.NONE
focus[id] = Vector3(h.x, 2.0, h.y)
var shown := false
match st:
Status.CARRIED:
var d := enemies.resolve_handle(holder[id]) if enemies != null else -1
var p := enemies.visual_position(d) if d >= 0 else h
if token != null:
token.position = Vector3(p.x, config.combat_height + 0.25, p.y)
token.rotation.y = _time * 1.5
icon.position = Vector3(p.x, config.combat_height + 1.55, p.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.CARRIED])
_icon_mats[id].set_shader_parameter("pulse", 0.0)
threat[id] = Threat.CARRIED
focus[id] = Vector3(p.x, config.combat_height + 0.25, p.y)
shown = true
Status.DROPPED:
var g := position_of(id)
if token != null:
token.position = Vector3(g.x, 0.15 + (bob + 1.0) * 0.12, g.y)
token.rotation.y = _time * 0.8
icon.position = Vector3(g.x, 1.75 + bob * 0.12, g.y)
_icon_mats[id].set_shader_parameter("edge_color", THREAT_COLORS[Threat.DROPPED])
_icon_mats[id].set_shader_parameter("pulse", 0.5 + 0.5 * sin(_time * 7.0))
threat[id] = Threat.DROPPED
focus[id] = Vector3(g.x, 0.6, g.y)
shown = true
if token != null:
token.visible = shown
icon.visible = shown
## An unshaded, front-culled shell drawn over a mesh: a colored outline.
static func outline_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.cull_mode = BaseMaterial3D.CULL_FRONT
m.grow = true
m.grow_amount = 0.05
m.albedo_color = color
return m
func outline_for(c: Category) -> StandardMaterial3D:
return _outline[c]
func _category_of(id: int) -> Category:
if id <= unit_count:
return Category.CROP
if id <= unit_count + animal_count:
return Category.ANIMAL
return Category.SUPPLY
func _ids(c: Category) -> Array:
match c:
Category.CROP:
return range(1, unit_count + 1)
Category.ANIMAL:
return range(unit_count + 1, unit_count + animal_count + 1)
return range(first_sack(), item_count + 1)
## The categories to try, in order: the wanted one first (all of them by weight for ANY), then
## the others in a weighted random order.
func _preference(want: int) -> Array[int]:
var left: Array[int] = [Category.CROP, Category.ANIMAL, Category.SUPPLY]
var out: Array[int] = []
if want != ANY and left.has(want):
out.append(want)
left.erase(want)
while not left.is_empty():
var total := 0.0
for c in left:
total += _weight(c)
var pick := left[0]
if total > 0.0:
var roll := _rng.randf() * total
for c in left:
roll -= _weight(c)
if roll <= 0.0:
pick = c
break
out.append(pick)
left.erase(pick)
return out
func _weight(c: int) -> float:
return maxf(float(config.target_weights.get(CATEGORY_KEYS[c], 1.0)), 0.0)
func _claim_home(c: int) -> int:
if c == Category.SUPPLY:
var r := campaign.state.resources
var m := r.most_stocked()
var sack := _free_sack()
if m == "" or sack < 0:
return -1
sack_material[sack] = m
home[sack] = shed_stock.spot(m) if shed_stock != null else Vector2.ZERO
return sack
var free: Array[int] = []
for id in _ids(c):
if (status[id] == Status.HOME or status[id] == Status.LOOSE) and holder[id] == -1:
free.append(id)
if free.is_empty():
return -1
return free[_rng.randi() % free.size()]
func _free_sack() -> int:
for id in range(first_sack(), item_count + 1):
if status[id] == Status.HOME and holder[id] == -1:
return id
return -1
func _lose(id: int) -> void:
var s := campaign.state
var at := _world(position_of(id))
holder[id] = -1
match category[id]:
Category.CROP:
status[id] = Status.LOST
s.lose_crop(id)
_units[id].visible = false
Category.ANIMAL:
status[id] = Status.LOST
s.lose_animal(animal_index(id))
Category.SUPPLY:
s.record_event("supplies_lost", sack_amount[id])
loot_event.emit(&"lost", id, at)
_empty_sack(id, false)
return
loot_event.emit(&"lost", id, at)
## A sack is done with: its contents go back to the shed (or are gone), and it is free again.
func _empty_sack(id: int, to_shed: bool) -> void:
var s := campaign.state
if to_shed and sack_material[id] != "":
s.resources.shed[sack_material[id]] = int(s.resources.shed[sack_material[id]]) + sack_amount[id]
s.supplies_in_transit = maxi(s.supplies_in_transit - sack_amount[id], 0)
sack_amount[id] = 0
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
func _return_home(id: int) -> void:
status[id] = Status.HOME
holder[id] = -1
progress[id] = 0.0
if category[id] == Category.CROP:
_units[id].visible = true
elif category[id] == Category.ANIMAL:
campaign.state.pen_animal(animal_index(id))
func _world(p: Vector2) -> Vector3:
return Vector3(p.x, 0.0, p.y)
func _marker() -> Label3D:
var l := Label3D.new()
l.text = "!"
l.font_size = 128
l.outline_size = 28
l.pixel_size = 0.006
l.modulate = THREAT_COLORS[Threat.TARGETED]
l.outline_modulate = Color(0.1, 0.05, 0.0)
l.billboard = BaseMaterial3D.BILLBOARD_ENABLED
l.no_depth_test = true
l.shaded = false
l.visible = false
l.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(l)
return l
func _billboard(size: float, mat: ShaderMaterial) -> MeshInstance3D:
var quad := QuadMesh.new()
quad.size = Vector2(size, size)
var mi := MeshInstance3D.new()
mi.mesh = quad
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.visible = false
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi