rimlike/autoload/world.gd
megaproxy 43e52ffe75 Phase 8 — Beds, sleep need, thoughts, mood, Sulking soft-break
Three gdscript-refactor agents in parallel; Opus integrated and verified
the sleep+wake cycle via MCP runtime.

Bed entity (Agent A, scenes/entities/bed.{gd,tscn} + world.gd, ~280 lines):
- class Bed extends Node2D — bottom-anchored 3/4 perspective like Wall/Workbench
- BuildJob interface (is_buildable / on_build_tick / _complete) — same pattern
  as Wall / Crate / Workbench. blocks_pathing_when_complete=false (walkable).
- Quality-tinted sheet colours by Item.Quality tier (drab grey → blue →
  gold-brown → regal pink); white pillow + dark frame constant across tiers.
- claim(pawn) / release() / is_available() — atomic occupancy; claim re-checks
  is_available() inside to avoid race conditions during pawn walk-to-bed.
- World.beds registry + register_bed / unregister_bed (mirrors workbench pattern)

Sleep need + SleepProvider + KIND_SLEEP toil (Agent B, ~220 lines):
- Pawn.sleep: float 0..100. SLEEP_DECAY_PER_TICK=0.015 (~6667 ticks / 5.5 min
  at 1× / 1 min at Ultra to fully tire). Slower than hunger.
- is_tired() at <30; is_exhausted() at <5 (Phase 9 status interrupt hook)
- SleepProvider priority=8 (highest — sleep beats eat=7 when both urgent)
- Toil.KIND_SLEEP + Toil.sleep_in_bed(NodePath) factory
- JobRunner._tick_sleep: first-tick bed claim (with race-loss → floor fallback),
  per-tick recovery (bed=0.5/tick, floor=0.25/tick), wake-when-full at ≥99,
  emergency ceiling SLEEP_TICKS_MAX=2000 prevents stuck-asleep loops

Thoughts + mood + Sulking (Agent C, ~290 lines):
- scenes/ai/thought.gd: class Thought (RefCounted) with id, modifier, lifetime
  (PERSISTENT/EVENT), stacks, ticks_remaining; MAX_STACKS_PER_THOUGHT=5 locked
- scenes/ai/thought_catalog.gd: ThoughtCatalog with 5 Phase 8 thoughts —
  hungry(-6, PERSISTENT) / tired(-4, PERSISTENT) / well_rested(+5, EVENT 1200t)
  / slept_on_floor(-5, EVENT 1200t) / ate_meal(+3, EVENT 800t, stacks up to 3)
- Pawn extended: thoughts: Array, mood: float (base 50), sulking: bool,
  _sulk_low_ticks. add_thought (stack-merge by id), remove_thought_by_id,
  has_thought, is_sulking. _process_thoughts in sim_tick decays EVENT thoughts,
  syncs PERSISTENT thoughts to state (hungry/tired), recomputes mood, checks
  sulking transition: mood < 25 for MOOD_SULK_SUSTAIN_TICKS=600 ticks → SULKING;
  mood >= 35 → recover.
- Decision Layer 1 extended: pawn.is_sulking() → return null (sulking pawns
  refuse all work; Phase 17 may add Wandering variant)
- EventBus.pawn_mood_changed signal
- JobRunner._tick_eat: fires ate_meal thought when consuming MEAL/BREAD
- JobRunner._tick_sleep: fires well_rested or slept_on_floor on wake

Opus integration:
- world.tscn: SleepProvider node added (9 providers total)
- world.gd registers in priority order:
  sleep=8 > eat=7 > construction=6 > chop=5 ≈ plant=5 > mine=4 ≈ crafting=4 > haul=3 > rest=0
- Demo seed: 3 beds along cabin's north row at (45/47/49, 24), pre-built
  so pawns can sleep immediately when tired

Acceptance — MCP-verified end-to-end:
- Pre-tired Bram at sleep=25 → SleepProvider issued 'Sleep at (45, 24)' job
- Bram walked to bed, claimed, slept 200 ticks, woke at sleep≥99
- Bed released back to available; well_rested thought fired (+5 mood)
- After ~12000 ticks total: all 3 pawns slept (sleep recovered to 67/86/51),
  thoughts active (1-2 per pawn — well_rested + ate_meal from Phase 7 cooked
  bread consumption), beds all back to available, no claim leaks
- Mood compute working (base 50 + thought modifiers); sulking transition
  ready but didn't fire — would need misery accumulation (Phase 9 Cold +
  Bleeding statuses) to drive mood < 25 sustained

Phase 8 followups for later phases:
- Sulking returns null (stand still); Phase 17 may add Wandering soft-break
  that issues a random-walk job
- Bed ownership (_owner_pawn) reserved but not used in Phase 8 — Phase 17
  may add 'bedrooms' where each pawn claims a specific bed
- _tick_sleep's using_bed local-var reset pattern is correct but fragile;
  cleanup pass when status interrupts (Phase 9) wire into the eat/sleep
  cancellation path

Delegation report this phase:
- Agent A: Bed entity (buildable, quality-tinted, claim/release)
- Agent B: Pawn.sleep + SleepProvider + KIND_SLEEP toil + JobRunner._tick_sleep
- Agent C: Thought + ThoughtCatalog + Pawn mood/sulking + Decision Layer 1
  + JobRunner thought hooks in _tick_eat / _tick_sleep
- Opus: scene wiring + 3 beds in demo seed + MCP runtime verification

~75% of Phase 8 GDScript was subagent-authored.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 13:21:15 +01:00

229 lines
6.7 KiB
GDScript

extends Node
## Runtime entity registry + tile-related sim state.
##
## All gameplay entities (pawns, items, furniture, animals, corpses) live here.
## TileMap data is owned by the world-view scene; World holds the *indirect*
## state (designation queue, dirty-haul set, zone records, etc.) that doesn't
## belong on the TileMap itself.
##
## See docs/architecture.md.
# Phase 2 — pawn registry. items/furniture/animals/corpses arrive in later phases.
var pawns: Array[Pawn] = []
# Phase 3 — work providers (e.g. RestProvider, ChopProvider, HaulingProvider).
# World scene registers them on _ready. Decision.pick_next_job() iterates by .priority desc.
var work_providers: Array = []
# Phase 4 — harvestables + items + stockpiles. Entities call register_*/unregister_*
# from their _ready/_exit_tree. Phase 16 will add stable IDs and persistence wiring.
var trees: Array = [] # Array of Tree
var rocks: Array = [] # Array of Rock
var items: Array = [] # Array of Item (on-floor stacks)
var stockpiles: Array = [] # Array of StorageDestination (StockpileZone for now; containers Phase 5)
# Phase 4 — pathfinder reference exposed for entity code that needs walkability
# checks (e.g. Tree.fell() picking neighbour tiles for wood drops). The actual
# Pathfinder node lives on the World scene as a child; the scene sets this in
# its _ready(). Don't access before the world scene is mounted.
var pathfinder = null
# Phase 5 — build queue. Holds Wall/Floor/Door/Crate ghost entities (not yet
# completed). ConstructionProvider iterates this for the nearest buildable site.
# Entities call register_build_site() in _ready and unregister_build_site() when
# they finish or are cancelled.
var build_queue: Array = []
# Phase 5 — completed Door entities, keyed for future open/close logic.
# Door._complete() calls register_door(); Phase 7+ uses this for toggling.
var doors: Array = []
# Phase 6 — workbench entities. Workbench._ready() calls register_workbench();
# _exit_tree() calls unregister_workbench(). CraftingProvider iterates this
# to find bench+bill pairs for eligible pawns.
var workbenches: Array = []
# Phase 7 — crop entities. Crop._ready() calls register_crop();
# _exit_tree() calls unregister_crop(). PlantProvider iterates this to find
# harvestable (READY) and sowable (TILLED) crops for eligible pawns.
var crops: Array = []
# Phase 8 — bed entities. Bed._ready() calls register_bed();
# _exit_tree() calls unregister_bed(). SleepProvider iterates this to find
# available (completed, unoccupied) beds for tired pawns.
# Storyteller also reads beds.size() for the "First Beds" state predicate.
var beds: Array = []
# Phase 4 — hauling dirty set. Keys are Items, value is unused (we just use .keys()).
# An Item is added when it spawns (Tree.fell, Rock.mined, workbench drop, ...)
# and removed when it lands at its highest-priority valid destination.
# HaulingProvider.sweep_for_better_destinations() re-marks items when a higher
# priority stockpile opens up (the priority cascade per design.md).
var items_needing_haul: Dictionary = {}
func register_work_provider(wp) -> void:
assert(wp != null, "World.register_work_provider: provider is null")
if not work_providers.has(wp):
work_providers.append(wp)
func clear_work_providers() -> void:
work_providers.clear()
func register_pawn(p: Pawn) -> void:
assert(p != null, "World.register_pawn: pawn is null")
if pawns.has(p):
return
pawns.append(p)
func unregister_pawn(p: Pawn) -> void:
pawns.erase(p)
func pawn_at_tile(tile: Vector2i) -> Pawn:
for p in pawns:
if p.tile == tile:
return p
return null
func clear_pawns() -> void:
# For save-load / new-game flow in Phase 16.
pawns.clear()
# ── Phase 4: harvestables + items + stockpiles ──────────────────────────────
func register_tree(t) -> void:
if not trees.has(t):
trees.append(t)
func unregister_tree(t) -> void:
trees.erase(t)
func register_rock(r) -> void:
if not rocks.has(r):
rocks.append(r)
func unregister_rock(r) -> void:
rocks.erase(r)
func register_item(it) -> void:
if items.has(it):
return
items.append(it)
# Newly-spawned items always start as "needs haul" — HaulingProvider will
# clear the flag once the item lands in its highest-priority destination.
items_needing_haul[it] = true
func unregister_item(it) -> void:
items.erase(it)
items_needing_haul.erase(it)
func register_stockpile(s) -> void:
if not stockpiles.has(s):
stockpiles.append(s)
func unregister_stockpile(s) -> void:
stockpiles.erase(s)
func mark_item_needs_haul(it) -> void:
items_needing_haul[it] = true
func clear_item_haul_flag(it) -> void:
items_needing_haul.erase(it)
# ── Phase 5: build queue + tile-data stamping for walls / floors ────────────
func register_build_site(entity) -> void:
if not build_queue.has(entity):
build_queue.append(entity)
func unregister_build_site(entity) -> void:
build_queue.erase(entity)
func register_door(d) -> void:
if not doors.has(d):
doors.append(d)
func unregister_door(d) -> void:
doors.erase(d)
func register_workbench(wb) -> void:
if not workbenches.has(wb):
workbenches.append(wb)
func unregister_workbench(wb) -> void:
workbenches.erase(wb)
func register_crop(c) -> void:
if not crops.has(c):
crops.append(c)
func unregister_crop(c) -> void:
crops.erase(c)
func register_bed(b) -> void:
if not beds.has(b):
beds.append(b)
func unregister_bed(b) -> void:
beds.erase(b)
# Called by Wall.on_build_tick() when construction completes.
# Stamps the data-only Wall TileMap layer so room/roof/save logic sees the
# wall. World scene exposes wall_layer via a getter set during _ready.
var wall_layer = null
var floor_layer = null
var designation_layer = null
func mark_wall_tile(tile: Vector2i, material: StringName) -> void:
if wall_layer == null:
Audit.log("world", "mark_wall_tile: layer not yet wired — skipping")
return
# Atlas coord encodes material — for Phase 5 placeholder atlas:
# stone → (2, 0), dark stone → (3, 0)
# Real material→atlas mapping lands when assets are imported.
var atlas := Vector2i(2, 0) if material == &"stone" else Vector2i(3, 0)
wall_layer.set_cell(tile, 0, atlas)
func mark_floor_tile(tile: Vector2i, material: StringName) -> void:
if floor_layer == null:
return
var atlas := Vector2i(1, 0) if material == &"dirt" else Vector2i(2, 0)
floor_layer.set_cell(tile, 0, atlas)
# Returns the first StockpileZone OR Crate covering `tile`, or null.
# Used by JobRunner._tick_deposit (Phase 5 refactor) to route deposits into
# Crate contents when applicable.
func stockpile_at_tile(tile: Vector2i):
for sp in stockpiles:
if sp.covers_tile(tile):
return sp
return null