Phase 4 — Trees, Rocks, Items, Stockpiles, Hauling

Three gdscript-refactor agents in parallel + Opus integration.

Entities (scenes/entities/, Agent A — 3 scripts + 3 .tscn, ~460 lines):
- item.gd: 16-type StringName registry (matches design.md filter chips);
  Node2D + _draw() colored square + stack-count badge; to_dict/from_dict
- tree.gd: class_name HarvestableTree (Godot 4 ships a built-in 'Tree'
  Control class — renamed to avoid the shadow); CHOP_TICKS=80; on_chop_tick
  advances progress, fells when complete, drops 3 wood items at tile +
  walkable neighbours
- rock.gd: MINE_TICKS=120; angular polygon _draw; mined() drops 1 stone

Toil + provider extensions (scenes/ai/, Agent B — 4 files modified/added,
~250 lines):
- Toil: new KIND_INTERACT (timed entity action), KIND_PICKUP, KIND_DEPOSIT
- JobRunner: _tick_interact resolves NodePath, calls target.<method>()
  each tick, marks done when is_choppable/is_mineable returns false;
  _tick_pickup finds Item at pawn.tile, transfers to pawn.carried_item;
  _tick_deposit places carried_item at pawn.tile + clears the
  items_needing_haul dirty flag
- ChopProvider (priority=5): nearest choppable tree; Job=[walk_to + interact]
- MineProvider (priority=4): same for rocks

Hauling system (scenes/world/ + scenes/ai/, Agent C — 4 files, ~330 lines):
- StorageDestination: abstract Node2D base; Priority enum CRITICAL=0..OFF=4;
  accepted_types (empty=wildcard); _filter_accepts() helper
- StockpileZone: concrete rect-region zone; _draw paints priority-tinted
  overlay (z_index=-1); find_drop_position scans for free cells respecting
  one-stack-per-tile rule
- HaulingProvider (priority=3): nearest dirty item × best destination →
  4-toil job [walk → pickup → walk → deposit]; sweep_for_better_destinations
  enables the priority cascade (items in lower-priority zones re-mark dirty
  when a higher-priority destination opens up)

Opus integration (~200 lines):
- World autoload: trees/rocks/items/items_needing_haul/stockpiles registries
  + register/unregister methods; pathfinder reference exposed for entity
  code (tree.fell needs is_walkable for neighbour drops)
- Pawn: carried_item slot + carry-indicator (small colored rect upper-right
  of body) via queue_redraw in _on_sim_tick
- World scene: registers chop/mine/haul/rest providers; spawns 6 trees
  (cluster east-north), 4 rocks (south-east), 2 stockpile zones (Zone A
  wood-only NORMAL, Zone B wildcard HIGH); periodic
  hauling_provider.sweep_for_better_destinations every 100 sim ticks

Acceptance — MCP-verified end-to-end (the full Phase 4 loop):
- 3 pawns boot, Decision picks chop (highest priority work), all walk to
  nearest tree, chop in parallel (3× speed because all 3 call on_chop_tick
  per tick). Trees fell, drop wood (18 items). Pawns move to rocks, mine,
  drop stone (4 items). Total 22 items spawn.
- HaulingProvider routes wood + stone toward Zone B (wildcard HIGH > Zone
  A's wood-only NORMAL). Pawns carry items one at a time, visual indicator
  shows during transit. Items deposit, items_needing_haul dirty flag
  clears.
- **Priority cascade test:** Zone A promoted from NORMAL to CRITICAL.
  Manually-triggered sweep marks 3 wood items in Zone B for re-haul.
  Within a few thousand ticks: Zone A has 5 wood (cascaded from Zone B),
  Zone B has 4 stone only (wood left, stone stayed because Zone A rejects
  stone). Filter + priority cascade working exactly per design.md spec.

Phase 4 gotchas (logged in implementation.md):
- 'Tree' shadows Godot 4's built-in Tree Control class — class_name had to
  be renamed to HarvestableTree. Scene/file names stayed as 'tree' since
  the game concept is still 'tree'; the rename only affects code-side
  type references.
- draw_colored_polygon(points, color) takes a SINGLE Color, not a
  PackedColorArray. Agent C had to be reminded; draw_polygon(points, colors)
  is the variant that takes per-vertex colors.
- Godot's class-name cache lags behind file changes — a full editor scan
  ('godot --headless --editor --quit') is needed to flush. Even after
  reload_project, type-annotation assignments can fail; duck-typed
  variables ('var x = scene.instantiate()') sidestep the issue.
- JobRunner's _tick_deposit had to explicitly call
  World.clear_item_haul_flag — the dirty set persisted otherwise and
  items appeared 'needing haul' even after deposit.

Delegation report this phase:
- Agent A (Sonnet, gdscript-refactor): Tree + Rock + Item entities + i18n
  keys. ~460 lines.
- Agent B (Sonnet, gdscript-refactor): Toil extensions + JobRunner handlers
  + ChopProvider + MineProvider. ~250 lines.
- Agent C (Sonnet, gdscript-refactor): StorageDestination + StockpileZone
  + HaulingProvider with cascade sweep. ~330 lines.
- Opus: World autoload extensions (entity registries + pathfinder ref),
  Pawn carry slot + visual, world.tscn/gd wiring, the Tree rename, the
  draw_colored_polygon fix, the dirty-set-clear fix, MCP-driven runtime
  verification including the full chop-mine-haul loop and the priority
  cascade demo.

~75% of Phase 4's GDScript was subagent-authored.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
megaproxy 2026-05-10 21:32:39 +01:00
parent 5bf0f51efb
commit 91bceeebe8
28 changed files with 1252 additions and 23 deletions

View file

@ -0,0 +1,49 @@
class_name ChopProvider extends WorkProvider
## WorkProvider for the "chop" work category.
##
## Scans World.trees for the nearest choppable Tree (Manhattan distance from
## the requesting pawn) and returns a two-toil Job:
## walk_to(tree.tile) → interact(tree.get_path(), "on_chop_tick")
##
## The INTERACT toil calls Tree.on_chop_tick() once per sim tick; the Tree
## internally tracks chop_progress and calls fell() when CHOP_TICKS is
## reached. The toil finishes automatically when is_choppable() returns
## false (felled) or when the node is freed.
##
## Phase 4 simplification: trees do not block pathfinding, so walking directly
## to tree.tile is valid. No adjacency-offset needed.
##
## Duck-typing note: Tree is referenced without class_name (class may not be
## registered yet when this provider loads). We rely only on:
## tree.tile: Vector2i
## tree.is_choppable() -> bool
## tree.get_path() -> NodePath
func _init() -> void:
category = &"chop"
priority = 5 # Higher than rest (priority 0); scanned before it by Decision.
## Returns a Job targeting the nearest choppable Tree, or null if none exists.
## `pawn` is duck-typed: must expose .tile (Vector2i).
func find_best_for(pawn) -> Job:
var best = null
var best_dist: int = 999999
for tree in World.trees:
if not tree.is_choppable():
continue
var d: int = abs(tree.tile.x - pawn.tile.x) + abs(tree.tile.y - pawn.tile.y)
if d < best_dist:
best_dist = d
best = tree
if best == null:
return null
var j := Job.new()
j.label = "Chop tree at %s" % best.tile
j.toils.append(Toil.walk_to(best.tile))
j.toils.append(Toil.interact(best.get_path(), &"on_chop_tick"))
return j

View file

@ -0,0 +1 @@
uid://b5wgnawgoqy1v

View file

@ -0,0 +1,148 @@
class_name HaulingProvider extends WorkProvider
## WorkProvider for the Hauling work category. Slots into the 5-layer pawn AI
## (Decision → WorkProvider → Job + JobRunner) as layer 2.
##
## Each call to find_best_for(pawn) scans World.items_needing_haul for the
## item closest to `pawn` that has a valid, reachable destination, then builds
## a 4-toil haul job: walk → pickup → walk → deposit.
##
## sweep_for_better_destinations() is a periodic helper (called by World every
## ~100 sim ticks) that marks items in lower-priority destinations dirty when a
## higher-priority destination has space — enabling the "items flow upward"
## priority cascade described in design.md.
##
## Pawn is intentionally duck-typed (no class_name reference) to match the
## WorkProvider convention and avoid init-order issues.
##
## See docs/architecture.md "HaulingProvider".
func _init() -> void:
category = &"haul"
# Priority 3 — below chop (5) and mine (4); above rest (1).
# Adjusted once the full 9-category matrix is authored in Phase 17.
priority = 3
# ── WorkProvider override ─────────────────────────────────────────────────────
## Returns a haul Job for `pawn`, or null if no valid work exists.
## Picks the item closest to `pawn` (Manhattan distance) that has an open
## slot in the highest-priority destination accepting its type.
## Phase 4 simplification: one carry at a time — skip if pawn is already holding something.
func find_best_for(pawn) -> Job:
# One carry at a time — skip if the pawn is already holding an item.
if pawn.get("carried_item") != null:
return null
var best_item = null
var best_dest = null
var best_drop_cell: Vector2i = Vector2i(-1, -1)
var best_dist: int = 999999
for item in World.items_needing_haul.keys():
# Skip items another pawn is already carrying.
if item.being_carried:
continue
# Find the best destination for this item type + priority.
var dest = _find_best_destination_for(item)
if dest == null:
continue
var drop: Vector2i = dest.find_drop_position(item)
if drop == Vector2i(-1, -1):
continue
# Skip an item that is already sitting in the destination we'd haul it to.
# Avoids pointless re-haul of an item that is exactly where it should be.
# (Phase 16 refines this once the item→destination link is persisted.)
var current_dest = _destination_for_tile(item.tile)
if current_dest != null and current_dest == dest:
continue
# Nearest-first heuristic (pawn → item only).
var d: int = abs(item.tile.x - pawn.tile.x) + abs(item.tile.y - pawn.tile.y)
if d < best_dist:
best_dist = d
best_item = item
best_dest = dest
best_drop_cell = drop
if best_item == null:
return null
var j := Job.new()
j.label = "Haul %s x%d -> (%d,%d)" % [
best_item.item_type,
best_item.stack_size,
best_drop_cell.x,
best_drop_cell.y,
]
j.toils.append(Toil.walk_to(best_item.tile))
j.toils.append(Toil.pickup())
j.toils.append(Toil.walk_to(best_drop_cell))
j.toils.append(Toil.deposit())
return j
# ── priority cascade ──────────────────────────────────────────────────────────
## Periodic sweep (called by World every ~100 sim ticks).
## Walks all items NOT already in the dirty set and marks them dirty when:
## (a) they are loose on the floor with no destination covering their tile, OR
## (b) they are in a stockpile but a higher-priority destination now has room.
## Returns the count of newly marked items (logged when > 0).
## This is the mechanism that makes "items flow up" to Critical stockpiles.
func sweep_for_better_destinations() -> int:
var count: int = 0
for item in World.items:
if item.being_carried:
continue
# Already flagged — HaulingProvider will handle it.
if World.items_needing_haul.has(item):
continue
var current = _destination_for_tile(item.tile)
var best = _find_best_destination_for(item)
if current == null and best != null:
# Loose item with a valid destination — mark it.
World.items_needing_haul[item] = true
count += 1
elif current != null and best != null:
# Item is stored, but a better destination exists.
if int(best.priority) < int(current.priority):
World.items_needing_haul[item] = true
count += 1
if count > 0:
Audit.log("hauling", "sweep marked %d items for re-haul" % count)
return count
# ── private helpers ───────────────────────────────────────────────────────────
## Returns the highest-priority StorageDestination that accepts `item` and has
## at least one open slot. Among equal-priority destinations, first found wins.
## Returns null when no destination qualifies.
func _find_best_destination_for(item):
var best = null
for dest in World.stockpiles:
if not dest.accepts(item):
continue
if dest.find_drop_position(item) == Vector2i(-1, -1):
continue
# Lower enum int = higher priority (CRITICAL=0 beats HIGH=1).
if best == null or int(dest.priority) < int(best.priority):
best = dest
return best
## Returns the StorageDestination whose region contains `tile`, or null if the
## tile is not inside any registered destination.
func _destination_for_tile(tile: Vector2i):
for dest in World.stockpiles:
if dest.covers_tile(tile):
return dest
return null

View file

@ -0,0 +1 @@
uid://6mkqd2t286tn

View file

@ -91,6 +91,12 @@ func tick() -> void:
_tick_wait(t)
Toil.KIND_IDLE:
pass # Never completes on its own — Decision or player overrides.
Toil.KIND_INTERACT:
_tick_interact(t)
Toil.KIND_PICKUP:
_tick_pickup(t)
Toil.KIND_DEPOSIT:
_tick_deposit(t)
if t.done:
job.advance()
@ -173,6 +179,109 @@ func _tick_wait(t) -> void:
t.done = true
## Execute one tick of an INTERACT toil.
##
## First tick: resolve the target node from the stored NodePath string.
## If the target is gone or freed, log and skip immediately (done=true).
## Otherwise mark started and log the action start.
##
## Every subsequent tick: call tick_method on the target. After the call,
## check whether the target has been consumed (is_choppable/is_mineable
## returns false, or the node was freed). If so, mark done.
func _tick_interact(t) -> void:
var target_path := NodePath(t.data.get("target", ""))
var target = get_tree().get_root().get_node_or_null(target_path)
if not t.data.get("started", false):
if target == null or not is_instance_valid(target):
Audit.log(
"job_runner",
"%s interact target gone — skipping" % pawn.pawn_name
)
t.done = true
return
t.data["started"] = true
Audit.log(
"job_runner",
"%s interact start: %s.%s" % [pawn.pawn_name, target.name, t.data.get("tick_method", "")]
)
# Re-resolve each tick in case the node was freed between ticks.
target = get_tree().get_root().get_node_or_null(target_path)
if target == null or not is_instance_valid(target):
t.done = true
return
target.call(StringName(t.data.get("tick_method", "")))
# Re-check validity after the call (the call may have freed the node).
if target == null or not is_instance_valid(target):
t.done = true
return
if target.has_method("is_choppable") and not target.is_choppable():
Audit.log("job_runner", "%s interact done: %s chopped" % [pawn.pawn_name, target.name])
t.done = true
return
if target.has_method("is_mineable") and not target.is_mineable():
Audit.log("job_runner", "%s interact done: %s mined" % [pawn.pawn_name, target.name])
t.done = true
## Execute one tick of a PICKUP toil.
##
## Finds the first unheld Item at pawn.tile in World.items.
## Transfers it into pawn.carried_item via set_being_carried(true).
## Completes in a single tick.
func _tick_pickup(t) -> void:
var item = null
for it in World.items:
if it.tile == pawn.tile and not it.being_carried:
item = it
break
if item == null:
Audit.log(
"job_runner",
"%s pickup: no item at %s" % [pawn.pawn_name, pawn.tile]
)
t.done = true
return
pawn.carried_item = item
item.set_being_carried(true)
Audit.log(
"job_runner",
"%s pickup: %s ×%d" % [pawn.pawn_name, item.item_type, item.stack_size]
)
t.done = true
## Execute one tick of a DEPOSIT toil.
##
## Places pawn.carried_item at pawn.tile (pixel-centred in the 16 px grid).
## Clears pawn.carried_item. Completes in a single tick.
func _tick_deposit(t) -> void:
if pawn.carried_item == null:
Audit.log(
"job_runner",
"%s deposit: nothing to deposit" % pawn.pawn_name
)
t.done = true
return
var item = pawn.carried_item
item.tile = pawn.tile
item.position = Vector2(pawn.tile.x * 16 + 8, pawn.tile.y * 16 + 8)
item.set_being_carried(false)
pawn.carried_item = null
# Phase 4: clear the haul-dirty flag — item has landed at its destination.
# The periodic sweep_for_better_destinations will re-mark it if a higher-
# priority destination opens up later.
World.clear_item_haul_flag(item)
Audit.log(
"job_runner",
"%s deposit: %s ×%d at %s" % [pawn.pawn_name, item.item_type, item.stack_size, pawn.tile]
)
t.done = true
# ── helpers ──────────────────────────────────────────────────────────────────
## Emit job_completed, log, and clear the job reference.

View file

@ -0,0 +1,50 @@
class_name MineProvider extends WorkProvider
## WorkProvider for the "mine" work category.
##
## Scans World.rocks for the nearest mineable Rock (Manhattan distance from
## the requesting pawn) and returns a two-toil Job:
## walk_to(rock.tile) → interact(rock.get_path(), "on_mine_tick")
##
## The INTERACT toil calls Rock.on_mine_tick() once per sim tick; the Rock
## internally tracks mine_progress and handles removal when MINE_TICKS is
## reached. The toil finishes automatically when is_mineable() returns
## false (exhausted) or when the node is freed.
##
## Phase 4 simplification: rocks are assumed walkable during mining approach
## (they may block movement in a later phase once obstruction is added to the
## pathfinder).
##
## Duck-typing note: Rock is referenced without class_name (class may not be
## registered yet when this provider loads). We rely only on:
## rock.tile: Vector2i
## rock.is_mineable() -> bool
## rock.get_path() -> NodePath
func _init() -> void:
category = &"mine"
priority = 4 # Slightly lower than chop (5); both higher than rest (0).
## Returns a Job targeting the nearest mineable Rock, or null if none exists.
## `pawn` is duck-typed: must expose .tile (Vector2i).
func find_best_for(pawn) -> Job:
var best = null
var best_dist: int = 999999
for rock in World.rocks:
if not rock.is_mineable():
continue
var d: int = abs(rock.tile.x - pawn.tile.x) + abs(rock.tile.y - pawn.tile.y)
if d < best_dist:
best_dist = d
best = rock
if best == null:
return null
var j := Job.new()
j.label = "Mine rock at %s" % best.tile
j.toils.append(Toil.walk_to(best.tile))
j.toils.append(Toil.interact(best.get_path(), &"on_mine_tick"))
return j

View file

@ -0,0 +1 @@
uid://dgnufybspp1ja

View file

@ -13,6 +13,9 @@ class_name Toil extends RefCounted
const KIND_WALK: StringName = &"walk"
const KIND_WAIT: StringName = &"wait"
const KIND_IDLE: StringName = &"idle"
const KIND_INTERACT: StringName = &"interact" # Timed action on a target entity (Tree, Rock, …)
const KIND_PICKUP: StringName = &"pickup" # Transfer Item at pawn.tile into pawn.carried_item
const KIND_DEPOSIT: StringName = &"deposit" # Place pawn.carried_item at pawn.tile
var kind: StringName = KIND_IDLE
## Toil-specific params — all values must be int, float, bool, String, Dict, or Array.
@ -51,6 +54,41 @@ static func idle() -> Toil:
return t
## Timed action on a scene-node target (Tree, Rock, …).
## `target_node_path` is the NodePath of the entity; stored as String for JSON safety.
## `tick_method` is the method to call each sim tick (e.g. "on_chop_tick").
## JobRunner resolves the node at first-tick and calls tick_method every sim tick
## until the target is no longer choppable/mineable (method source sets done via
## is_choppable() / is_mineable() returning false).
static func interact(target_node_path: NodePath, tick_method: StringName) -> Toil:
var t := Toil.new()
t.kind = KIND_INTERACT
t.data = {
"target": String(target_node_path),
"tick_method": String(tick_method),
"started": false,
}
return t
## Pick up an Item at pawn.tile into pawn.carried_item. Single-tick action.
## data is empty — the item is located at pawn.tile at execution time.
static func pickup() -> Toil:
var t := Toil.new()
t.kind = KIND_PICKUP
t.data = {}
return t
## Place pawn.carried_item at pawn.tile. Single-tick action.
## data is empty — the item comes from pawn.carried_item at execution time.
static func deposit() -> Toil:
var t := Toil.new()
t.kind = KIND_DEPOSIT
t.data = {}
return t
# ── save / load ──────────────────────────────────────────────────────────────
func to_dict() -> Dictionary: