rimlike/autoload/world.gd
megaproxy a1e5b38dd6 Phase 11 — Day/night cycle + Lighting (taken before Phase 9 per recommendation)
Three gdscript-refactor agents in parallel; Opus integrated and verified
the day-night transition + torch lighting via MCP runtime + screenshot.

Clock autoload (Agent A, autoload/clock.gd, ~138 lines):
- TICKS_PER_DAY = 4800 → 4 min/day at 1× / 48 s at Fast / 20 s at Ultra
- TICKS_PER_HOUR = 200 (so 60 min × ~3 ticks per minute)
- 4-phase day: night → dawn (5–7) → day (7–19) → dusk (19–22) → night
- darkness_factor() returns 0..1 with linear ramps across dawn/dusk
- phase_changed signal fires on phase transitions
- save_dict / apply_dict for save round-trip
- Boots at Day 1, 06:00 (mid-dawn for atmospheric start)
- Registered in project.godot autoload list (Opus)

Top-bar clock UI (Agent A):
- ClockLabel added to top_bar.tscn (center-anchored at ±80 px)
- _on_clock_refresh in top_bar.gd; early-out string compare to skip text
  assignments when unchanged (cheap per-tick)

Torch entity + lights registry (Agent B, scenes/entities/torch.{gd,tscn} +
workbench.gd + world.gd, ~210 lines):
- class Torch: buildable furniture, BUILD_TICKS=30, LIGHT_RADIUS=6
- Procedural radial gradient texture (64×64) generated at runtime with
  smoothstep falloff → no PNG dependency
- PointLight2D child with the gradient texture, warm fire tint, energy 1.2
- is_on / get_light_tile / get_light_radius duck-typed interface; same
  shape exposed by Workbench when label_text='Hearth' (HEARTH_LIGHT_RADIUS=5)
- World.light_sources registry + register/unregister + is_tile_lit(tile)
  (Manhattan distance, no occlusion — Phase 13 may add wall-occlusion)

CanvasModulate darkness + in_darkness thought (Agent C, ~30 lines mod +
new factory):
- DarkOverlay CanvasModulate node added to world.tscn (first child of
  World root so it tints all sibling layers + entities)
- world.gd._update_dark_overlay lerps DAY_TINT (white) ↔ NIGHT_TINT
  (0.20, 0.22, 0.40 deep cool blue) by Clock.darkness_factor() each tick
- ThoughtCatalog.in_darkness(): persistent, -3 mood, fires when
  darkness > 0.3 AND World.is_tile_lit(pawn.tile) is false
- Pawn._process_thoughts syncs in_darkness alongside hungry/tired

Opus integration:
- project.godot: Clock autoload registered
- world.tscn: DarkOverlay CanvasModulate node, plus the agent additions
- Demo seed: 2 torches inside cabin at (46, 26) + (49, 26), pre-built
- MCP-driven runtime test verified day→night transition + lighting
  effects:
  - Noon: world bright green, torches barely visible (over-bright at noon
    is minor polish — Phase 17 may scale torch energy by darkness)
  - Midnight: world deep blue/green tinted, torches cast yellow halos,
    Hearth ember glows orange, cabin interior warmly lit, exterior dark
- top_bar clock label updates each sim tick (early-out on no-change)

Phase 11 followups for later phases:
- Torch energy should scale with darkness — visible halos at noon are
  silly. Phase 17 will likely tie PointLight2D.energy to clamp(darkness,
  0.2, 1.0) so they're invisible at midday
- Wall-occlusion for light_map — Phase 13's room-detection BFS could
  treat completed wall tiles as occluders so light doesn't bleed through
- 'In darkness' thought currently treats ALL unlit cells as darkness;
  Phase 13's roof flag could differentiate 'indoors-dark' (different
  thought) from 'outdoors-dark'
- Light source visibility through CanvasModulate works correctly thanks
  to PointLight2D's additive blend mode

Acceptance — MCP-verified via play_scene + get_game_screenshot:
-  Day → Dusk → Night cycle visible (Clock.current_phase emits events)
-  CanvasModulate tints world deep blue at night
-  Torches cast visible yellow halos via PointLight2D additive blend
-  Hearth opts-in as a light source via label_text='Hearth' check
-  Top-bar clock shows 'Day N, HH:MM' format and updates each tick
-  in_darkness thought wires through _process_thoughts (would fire if
  a pawn were standing in an unlit night tile — demo didn't capture this
  specifically but the code path is verified)

Delegation report this phase:
- Agent A: Clock autoload + 4-phase day cycle + top-bar UI extension
- Agent B: Torch entity + PointLight2D + procedural radial texture +
  Workbench Hearth opt-in + World.light_sources registry
- Agent C: CanvasModulate world.tscn node + day/night colour lerp +
  in_darkness ThoughtCatalog entry + Pawn persistent thought sync
- Opus: Clock autoload registration in project.godot + 2 torches in
  demo seed + MCP runtime verification at midnight vs noon

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

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

263 lines
8 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 11 — light-source entities (Torch + Hearth workbench). Entities call
# register_light_source() in _ready and unregister_light_source() in _exit_tree.
# is_tile_lit() is queried by the "in darkness" thought and any future
# darkness-rendering shader bridge. All entries expose the duck-type interface:
# is_on() → bool | get_light_tile() → Vector2i | get_light_radius() → int
var light_sources: 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)
# ── Phase 11: light-source registry ────────────────────────────────────────
func register_light_source(ls) -> void:
if not light_sources.has(ls):
light_sources.append(ls)
func unregister_light_source(ls) -> void:
light_sources.erase(ls)
## Returns true if `tile` is within get_light_radius() of any is_on() light
## source. Uses Manhattan distance (no wall-occlusion in Phase 11; Phase 13
## may add BFS-based occlusion through the room/roof system).
##
## Called by the "in darkness" Thought trigger on each pawn sim tick.
## O(light_sources) per call; trivial at our scale (< 50 sources in MVP).
func is_tile_lit(p_tile: Vector2i) -> bool:
for ls in light_sources:
if not ls.is_on():
continue
var d: int = abs(ls.get_light_tile().x - p_tile.x) + abs(ls.get_light_tile().y - p_tile.y)
if d <= ls.get_light_radius():
return true
return false
# 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