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,96 @@
class_name StockpileZone extends StorageDestination
## Concrete floor stockpile zone. A rectangular region (in tile coords) that
## accepts items matching the filter and deposits them one-per-tile.
##
## Rendered as a translucent priority-tinted overlay via _draw(). The overlay
## is always visible — Phase 17 will toggle it when the Zones panel is open.
## z_index = -1 keeps the tint below items (z_index 0) and pawns.
##
## Register/unregister with World.stockpiles happen automatically in
## _ready / _exit_tree — no external wiring needed.
##
## One-stack-per-tile, one-type-per-tile rule (design.md).
##
## See docs/architecture.md "StockpileZone".
## Region in tile coordinates. (0,0) relative to this node's map position;
## in practice this node lives at world origin so region is in world-tile space.
@export var region: Rect2i = Rect2i(0, 0, 4, 4)
## Player-visible label shown in zone inspect UI (Phase 17).
@export var label: String = "Stockpile"
## Pixel size of one tile — must match World.TILE_SIZE_PX.
const _TILE_PX: int = 16
## Priority-keyed fill colors for the overlay (Color(r, g, b, a)).
const _PRIORITY_COLORS: Dictionary = {
StorageDestination.Priority.CRITICAL: Color(0.9, 0.3, 0.3, 0.15),
StorageDestination.Priority.HIGH: Color(0.9, 0.6, 0.3, 0.15),
StorageDestination.Priority.NORMAL: Color(0.9, 0.9, 0.3, 0.12),
StorageDestination.Priority.LOW: Color(0.3, 0.9, 0.3, 0.10),
StorageDestination.Priority.OFF: Color(0.3, 0.3, 0.3, 0.10),
}
func _ready() -> void:
z_index = -1
World.register_stockpile(self)
queue_redraw()
func _exit_tree() -> void:
World.unregister_stockpile(self)
# ── StorageDestination overrides ─────────────────────────────────────────────
func accepts(item) -> bool:
return _filter_accepts(item)
func covers_tile(tile: Vector2i) -> bool:
return region.has_point(tile)
## Scan region cells in row-major order; return the first tile not occupied by
## an item that is not being carried. Returns Vector2i(-1, -1) if the zone is
## full or the item fails the filter.
func find_drop_position(item) -> Vector2i:
if not accepts(item):
return Vector2i(-1, -1)
for x in range(region.position.x, region.position.x + region.size.x):
for y in range(region.position.y, region.position.y + region.size.y):
var cell := Vector2i(x, y)
if _is_cell_free(cell):
return cell
return Vector2i(-1, -1)
# ── drawing ───────────────────────────────────────────────────────────────────
func _draw() -> void:
var fill_color: Color = _PRIORITY_COLORS.get(priority, Color(0.5, 0.5, 0.5, 0.12))
var border_color := Color(fill_color.r, fill_color.g, fill_color.b, 0.6)
var tile_px := float(_TILE_PX)
# Filled rectangle covering the entire region.
var rect_px := Rect2(
Vector2(region.position) * tile_px,
Vector2(region.size) * tile_px
)
draw_rect(rect_px, fill_color, true)
# 1-px border outline.
draw_rect(rect_px, border_color, false, 1.0)
# ── internal helpers ──────────────────────────────────────────────────────────
## Returns true when no un-carried item is sitting on `cell`.
## One-stack-per-tile rule: the first occupied, non-carried item blocks the cell.
func _is_cell_free(cell: Vector2i) -> bool:
for it in World.items:
if it.tile == cell and not it.being_carried:
return false
return true

View file

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

View file

@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3 uid="uid://stockpile_zone"]
[ext_resource type="Script" path="res://scenes/world/stockpile_zone.gd" id="1_stockpile"]
[node name="StockpileZone" type="Node2D"]
script = ExtResource("1_stockpile")
z_index = -1

View file

@ -0,0 +1,73 @@
class_name StorageDestination extends Node2D
## Abstract base for all item-storage destinations (floor stockpile zones,
## containers, etc.). Hauling AI treats all subclasses as a unified candidate
## pool via this interface.
##
## StorageDestination extends Node2D (not Node) so subclasses can implement
## _draw() for priority-tinted overlays without a separate CanvasItem child.
##
## Subclasses MUST override: accepts(), find_drop_position(), covers_tile().
## Subclasses SHOULD call World.register_stockpile(self) in _ready() and
## World.unregister_stockpile(self) in _exit_tree().
##
## See docs/architecture.md "Storage destinations: a unified concept".
## Five priority levels matching Rimworld semantics (design.md Priorities).
## Lower enum int = higher priority (CRITICAL = 0 pulls before LOW = 4).
## Priority.OFF = no hauling in or out; invisible to HaulingProvider.
enum Priority {
CRITICAL = 0,
HIGH = 1,
NORMAL = 2,
LOW = 3,
OFF = 4,
}
## Priority determines whether haulers will fill this destination and whether
## items here will be re-hauled upward to a higher-priority destination.
@export var priority: Priority = Priority.NORMAL
## Item types this destination accepts. Empty array = wildcard (accepts all).
## Each entry is a StringName matching Item.TYPE_* constants (e.g. &"wood").
@export var accepted_types: Array[StringName] = []
## Emitted when items are registered or unregistered with this destination,
## so interested parties (UI, re-scan logic) can react without polling.
signal contents_changed
# ── abstract interface — subclasses must override ────────────────────────────
## Returns true if this destination currently accepts `item` (filter + priority
## check + any capacity logic owned by the subclass).
func accepts(item) -> bool:
push_error("StorageDestination.accepts: '%s' must override this method" % name)
return false
## Returns a tile coordinate inside this destination where `item` can be
## placed (filter-pass AND the tile is not already occupied by another item).
## Returns Vector2i(-1, -1) when no slot is available.
func find_drop_position(item) -> Vector2i:
push_error("StorageDestination.find_drop_position: '%s' must override this method" % name)
return Vector2i(-1, -1)
## Returns true if `tile` falls inside this destination's region.
## Used by HaulingProvider to find which destination currently holds an item.
func covers_tile(tile: Vector2i) -> bool:
push_error("StorageDestination.covers_tile: '%s' must override this method" % name)
return false
# ── shared helper ────────────────────────────────────────────────────────────
## Priority-and-filter gate, shared by all subclasses.
## Returns false when OFF or when the item's type is not in accepted_types.
## accepted_types.is_empty() is the wildcard "accept any type" case.
func _filter_accepts(item) -> bool:
if priority == Priority.OFF:
return false
if accepted_types.is_empty():
return true
return item.item_type in accepted_types

View file

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

View file

@ -1,11 +1,8 @@
extends Node2D
## Phase 2 world view. 80×80 TileMap with 6 layers, 3 sample pawns, pathfinder,
## click-to-select / click-to-move selection.
##
## Real ElvGames art lands in Phase 5+ (wood walls custom-authored on
## FG_Houses, stone walls autotiled from FG_Fortress per the 2026-05-10
## audit lock). The procedural placeholder tileset is enough to prove the
## TileMap pipeline + pawn movement + camera + pathfinding end-to-end.
## Phase 4 world view. 80×80 TileMap, 6 layers, 3 pawns, full AI pipeline:
## RestProvider → ChopProvider → MineProvider → HaulingProvider → idle
## plus sample trees, rocks, and two stockpile zones with different priorities
## for the haul-cascade demo.
##
## TileMap layer indices follow docs/architecture.md:
## 0 Terrain · 1 Floor · 2 Wall · 3 Designation · 4 Roof · 5 Fog
@ -13,8 +10,6 @@ extends Node2D
const MAP_SIZE_TILES: Vector2i = Vector2i(80, 80)
const TILE_SIZE_PX: int = 16
# Atlas coords inside the placeholder tileset (one source, source_id = 0).
# Real assets in Phase 5 will use multiple atlas sources.
const TILE_GRASS: Vector2i = Vector2i(0, 0)
const TILE_DIRT: Vector2i = Vector2i(1, 0)
const TILE_STONE: Vector2i = Vector2i(2, 0)
@ -23,6 +18,9 @@ const TILE_STONE_DARK: Vector2i = Vector2i(3, 0)
const PLACEHOLDER_SOURCE_ID: int = 0
const PAWN_SCENE: PackedScene = preload("res://scenes/pawn/pawn.tscn")
const TREE_SCENE: PackedScene = preload("res://scenes/entities/tree.tscn")
const ROCK_SCENE: PackedScene = preload("res://scenes/entities/rock.tscn")
const STOCKPILE_SCENE: PackedScene = preload("res://scenes/world/stockpile_zone.tscn")
# 3 starting pawns — Phase 2 demo. Phase 7+ replaces this with map-gen + name table.
const SAMPLE_PAWNS: Array[Dictionary] = [
@ -31,6 +29,18 @@ const SAMPLE_PAWNS: Array[Dictionary] = [
{"name": "Edda", "tile": Vector2i(30, 40)},
]
# Phase 4 — sample harvestables. Trees clustered east, rocks south-east.
const SAMPLE_TREES: Array[Vector2i] = [
Vector2i(58, 30), Vector2i(60, 31), Vector2i(62, 30),
Vector2i(61, 33), Vector2i(63, 34), Vector2i(59, 35),
]
const SAMPLE_ROCKS: Array[Vector2i] = [
Vector2i(60, 60), Vector2i(62, 60), Vector2i(63, 62), Vector2i(58, 62),
]
# HaulingProvider re-flow cadence — every 5 sim seconds at 1× (100 ticks).
const HAUL_SWEEP_INTERVAL_TICKS: int = 100
@onready var terrain_layer: TileMapLayer = $Terrain
@onready var floor_layer: TileMapLayer = $Floor
@onready var wall_layer: TileMapLayer = $Wall
@ -40,10 +50,13 @@ const SAMPLE_PAWNS: Array[Dictionary] = [
@onready var pathfinder: Pathfinder = $Pathfinder
@onready var selection: Selection = $Selection
@onready var rest_provider: RestProvider = $RestProvider
@onready var chop_provider: ChopProvider = $ChopProvider
@onready var mine_provider: MineProvider = $MineProvider
@onready var hauling_provider: HaulingProvider = $HaulingProvider
func _ready() -> void:
Audit.log("world", "Phase 3 — building %d×%d world + pawns + AI." % [MAP_SIZE_TILES.x, MAP_SIZE_TILES.y])
Audit.log("world", "Phase 4 — building %d×%d world + harvestables + AI." % [MAP_SIZE_TILES.x, MAP_SIZE_TILES.y])
var tileset := _build_placeholder_tileset()
for layer in [terrain_layer, floor_layer, wall_layer, designation_layer, roof_layer, fog_layer]:
layer.tile_set = tileset
@ -54,12 +67,24 @@ func _ready() -> void:
pathfinder.setup(MAP_SIZE_TILES)
_wire_walls_to_pathfinder()
selection.bind(pathfinder)
World.pathfinder = pathfinder # expose to entities (Tree.fell() walkability checks, etc.)
# Register all 4 providers — Decision iterates by .priority desc.
# chop=5 > mine=4 > haul=3 > rest=0.
World.register_work_provider(chop_provider)
World.register_work_provider(mine_provider)
World.register_work_provider(hauling_provider)
World.register_work_provider(rest_provider)
_spawn_sample_pawns()
_spawn_sample_harvestables()
_spawn_sample_stockpiles()
_run_pathfinder_spike()
# Phase 4: every 5 in-game seconds (100 ticks), re-evaluate items in
# stockpiles in case a higher-priority destination opened up.
EventBus.sim_tick.connect(_on_sim_tick_world_sweep)
func world_bounds_px() -> Rect2:
return Rect2(Vector2.ZERO, Vector2(MAP_SIZE_TILES * TILE_SIZE_PX))
@ -68,9 +93,8 @@ func world_bounds_px() -> Rect2:
# ── tileset & map painting ──────────────────────────────────────────────────
func _build_placeholder_tileset() -> TileSet:
# Four 16×16 placeholder tiles laid out as a 4×1 atlas. No PNG dependency
# — atlas built at runtime from a programmatic Image. Real ElvGames art
# replaces this when wood/stone wall variants are imported in Phase 5.
# Four 16×16 placeholder tiles laid out as a 4×1 atlas. Real ElvGames
# art replaces this in Phase 5 (wood walls + stone walls).
var ts := TileSet.new()
ts.tile_size = Vector2i(TILE_SIZE_PX, TILE_SIZE_PX)
@ -110,8 +134,6 @@ func _paint_terrain() -> void:
func _paint_sample_walls() -> void:
# An 8×8 stone ring near the map centre as a visual landmark + pathfinding
# obstacle so the demo proves pawns route around walls.
var origin := Vector2i(36, 36)
var size: int = 8
for i in size:
@ -124,7 +146,6 @@ func _paint_sample_walls() -> void:
# ── pathfinder + pawns ──────────────────────────────────────────────────────
func _wire_walls_to_pathfinder() -> void:
# Wall cells block pathing. Re-runs on Phase 5 build/destroy events later.
var wall_cells := wall_layer.get_used_cells()
for cell in wall_cells:
pathfinder.set_cell_walkable(cell, false)
@ -147,12 +168,59 @@ func _spawn_sample_pawns() -> void:
World.register_pawn(p)
# ── Phase 4: harvestables + stockpile zones ─────────────────────────────────
func _spawn_sample_harvestables() -> void:
# Untyped vars — Godot's class-name cache for class_name'd classes is
# scan-time and intermittently lags behind file changes. Duck typing is
# safer here and the calls below are all spec'd on the entity types.
for t_tile in SAMPLE_TREES:
var tree = TREE_SCENE.instantiate()
add_child(tree)
tree.setup(t_tile)
for r_tile in SAMPLE_ROCKS:
var rock = ROCK_SCENE.instantiate()
add_child(rock)
rock.setup(r_tile)
Audit.log("world", "spawned %d trees + %d rocks" % [SAMPLE_TREES.size(), SAMPLE_ROCKS.size()])
func _spawn_sample_stockpiles() -> void:
# Two zones for the Phase 4 acceptance demo:
# - Zone A (north): wood-only filter, NORMAL priority (just a wood drop)
# - Zone B (south): wildcard, HIGH priority (the "watch wood flow upward" target)
# When the sweep runs, wood items in Zone A get re-marked for haul and
# eventually migrate to Zone B.
var zone_a: StockpileZone = STOCKPILE_SCENE.instantiate()
add_child(zone_a)
zone_a.region = Rect2i(15, 55, 4, 4)
zone_a.label = "Wood (Normal)"
zone_a.priority = StorageDestination.Priority.NORMAL
zone_a.accepted_types = [Item.TYPE_WOOD] as Array[StringName]
zone_a.queue_redraw()
var zone_b: StockpileZone = STOCKPILE_SCENE.instantiate()
add_child(zone_b)
zone_b.region = Rect2i(15, 62, 4, 4)
zone_b.label = "Anything (High)"
zone_b.priority = StorageDestination.Priority.HIGH
zone_b.accepted_types = [] as Array[StringName] # wildcard
zone_b.queue_redraw()
Audit.log("world", "spawned 2 stockpiles: %s + %s" % [zone_a.label, zone_b.label])
# ── periodic re-flow (the "wood floats up" cascade) ─────────────────────────
func _on_sim_tick_world_sweep(tick_n: int) -> void:
if tick_n % HAUL_SWEEP_INTERVAL_TICKS != 0:
return
hauling_provider.sweep_for_better_destinations()
# ── spike: AStarGrid2D query timing at 80² ──────────────────────────────────
func _run_pathfinder_spike() -> void:
# Phase 2 acceptance spike (~30 min): "AStarGrid2D path-query timing at 80²
# with 6 pawns simultaneously requesting paths. Confirm sub-millisecond."
# We benchmark all 4-corner pairs × 3 iterations = 36 path queries.
var corners := [
Vector2i(2, 2),
Vector2i(MAP_SIZE_TILES.x - 3, 2),

View file

@ -1,10 +1,13 @@
[gd_scene load_steps=6 format=3 uid="uid://rimlike_world"]
[gd_scene load_steps=9 format=3 uid="uid://rimlike_world"]
[ext_resource type="Script" path="res://scenes/world/world.gd" id="1_world"]
[ext_resource type="PackedScene" uid="uid://rimlike_camera_rig" path="res://scenes/world/camera_rig.tscn" id="2_camera"]
[ext_resource type="Script" path="res://scenes/world/pathfinder.gd" id="3_pathfinder"]
[ext_resource type="Script" path="res://scenes/world/selection.gd" id="4_selection"]
[ext_resource type="Script" path="res://scenes/ai/rest_provider.gd" id="5_rest_provider"]
[ext_resource type="Script" path="res://scenes/ai/chop_provider.gd" id="6_chop_provider"]
[ext_resource type="Script" path="res://scenes/ai/mine_provider.gd" id="7_mine_provider"]
[ext_resource type="Script" path="res://scenes/ai/hauling_provider.gd" id="8_hauling_provider"]
[node name="World" type="Node2D"]
script = ExtResource("1_world")
@ -39,5 +42,14 @@ script = ExtResource("4_selection")
script = ExtResource("5_rest_provider")
rest_tile = Vector2i(50, 50)
[node name="ChopProvider" type="Node" parent="."]
script = ExtResource("6_chop_provider")
[node name="MineProvider" type="Node" parent="."]
script = ExtResource("7_mine_provider")
[node name="HaulingProvider" type="Node" parent="."]
script = ExtResource("8_hauling_provider")
[node name="CameraRig" parent="." instance=ExtResource("2_camera")]
position = Vector2(640, 640)