Phase 6 — Recipe / Bill / Workbench / CraftingProvider / Quality / Skills

Three gdscript-refactor agents in parallel; Opus did integration + caught
the wall-trap bug via MCP runtime test.

Data layer (Agent A):
- scenes/ai/recipe.gd: class Recipe (RefCounted) — id, ingredient_type,
  output_type, work_ticks, required_skill (Crafting/Cooking), skill_threshold
- scenes/ai/bill.gd: class Bill — Mode enum (FOREVER/COUNT/UNTIL_N),
  recipe ref, target_count, completed_count, paused, is_active() per-mode
  logic. UNTIL_N walks World.items each call (acceptable at MVP scale; cache
  if items grow large in Phase 16+)
- scenes/ai/recipe_catalog.gd: RecipeCatalog.plank() / .stone_block() — 2
  starter recipes; Phase 7+ expands toward the design.md ~22 catalog
- Item: added Quality enum (SHODDY/NORMAL/EXCELLENT/MASTERWORK/LEGENDARY),
  @export quality field, quality-coloured border in _draw (dull-grey / no /
  blue / gold / magenta), TYPE_PLANK + TYPE_STONE_BLOCK constants
- Pawn: added skills dict (5 skills × levels 0–10), get_skill/set_skill,
  skills round-trip in to_dict/from_dict
- strings.gd: item.plank, item.stone_block, quality.* (5 keys)

Workbench entity (Agent B, scenes/entities/workbench.{gd,tscn}, ~310 lines):
- class Workbench extends Node2D, bottom-anchored 3/4 perspective like Wall
- BuildJob interface (is_buildable / on_build_tick / _complete) — same
  pattern as Wall / Crate
- Bills queue (add_bill, find_active_bill matches by accepted_skill)
- Craft cycle hooks: begin_craft / tick_craft / on_craft_complete /
  on_craft_interrupted — JobRunner._tick_craft delegates to these
- Procedural _draw differentiates Carpenter (brown bench + vise) vs
  Smelter (dark stone + orange ember glow) via the @export label_text
  field — no subclass needed for Phase 6
- World autoload: workbenches registry + register_workbench/unregister_workbench

Crafting AI (Agent C):
- Toil.KIND_CRAFT + Toil.craft_at(workbench_path, bill_index) factory
- JobRunner._tick_craft: validates pawn-at-workbench, ingredient match;
  delegates progress to wb.tick_craft; on complete spawns output Item
  with QualityCalc.roll() applied; records bill completion
- crafting_provider.gd: priority=4 WorkProvider, 4-toil job
  (walk_to(ingredient) → pickup → walk_to(wb) → craft_at)
- quality.gd: QualityCalc.roll(skill) — additive formula
  skill × 0.04 + RNG(0, 0.6) with bucket thresholds matching
  architecture.md spec. Skill 0 caps at Excellent; Skill 10 reaches
  Legendary ~8% of the time

Opus integration:
- world.tscn: CraftingProvider node added
- world.gd: registered crafting_provider with World (priority order:
  construction=6 > chop=5 > mine=4 > crafting=4 > haul=3 > rest=0)
- Pawn spawn data extended with crafting skill (Bram=8, Cora=4, Edda=0)
  for visible quality variation in the demo
- _seed_phase5_demo_buildings extended: pre-built Carpenter at (46, 25)
  with plank bill (FOREVER) + Smelter at (48, 25) with stone_block bill
  (UNTIL_N=5)

The wall-trap bug (caught via MCP runtime — initial Phase 6 run hung):
- Pawns building walls stood ON the wall tile. When wall._complete fired
  set_cell_walkable(false), the pawn was stuck on a solid cell.
  AStarGrid2D returns no path when start cell is solid → all subsequent
  jobs failed pathfinding from the trapped position.
- Fix: ConstructionProvider checks site.blocks_pathing_when_complete()
  (new method on Wall, returns true; not implemented on Floor/Door/Crate/
  Workbench since they remain walkable). Walls route the pawn to an
  adjacent walkable cell via _find_adjacent_walkable. Floors/doors/etc.
  build on-tile as before.
- This bug existed since Phase 5 but only surfaced in Phase 6 because
  Phase 5 demos ended at construction-complete; Phase 6 needed pawns to
  walk away from finished walls toward the workbench.

Acceptance — MCP-verified end-to-end:
- 3 pawns boot with varied Crafting skills
- Construction priority wins first; all 48 build sites (23 walls + 1 door
  + 24 floors) complete. Pawns escape wall tiles safely (fix verified).
- Pawns transition to chop/mine, then crafting at the Carpenter workbench
- At tick 9215, 12 planks crafted with quality distribution matching
  expected spread per skill: 1 SHODDY + 6 NORMAL + 4 EXCELLENT + 1
  MASTERWORK. Quality-coloured borders visible on items.
- Smelter UNTIL_N=5 bill correctly idle (no stone consumed yet) because
  CraftingProvider prefers closer workbench-ingredient pairs and the
  carpenter+wood is closer to where pawns end up than smelter+stone

Phase 6 followups for later phases:
- on_craft_interrupted has no JobRunner hook — Phase 9 status interrupts
  will need a 'cancel callback' on toils or wb.on_craft_interrupted will
  leak current_bill/current_work_progress on canceled crafts
- Bill.from_dict reconstructs Recipe inline via Recipe.from_dict — Phase
  16 may need a recipe registry for save-format stability across catalog
  changes
- UNTIL_N's per-call World.items walk is O(items) — acceptable at MVP
  scale; profile if it becomes hot

Delegation report this phase:
- Agent A: Recipe + Bill + RecipeCatalog + Item.quality + Pawn.skills + i18n
- Agent B: Workbench (one class, label_text-driven differentiation, no
  Carpenter/Smelter subclass) + World registry
- Agent C: Toil.KIND_CRAFT + JobRunner._tick_craft + CraftingProvider +
  QualityCalc
- Opus: scene wiring + pawn-skill init + workbench demo seed + wall-trap
  fix (caught via MCP) + runtime verification

~75% of Phase 6 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 23:52:41 +01:00
parent 96f4982dd3
commit 0cd7f809a7
24 changed files with 1001 additions and 12 deletions

100
scenes/ai/bill.gd Normal file
View file

@ -0,0 +1,100 @@
class_name Bill extends RefCounted
## A bill is one entry in a workbench's recipe queue.
##
## Three modes per design.md "Bill modes (full Rimworld fidelity)":
## FOREVER — keep crafting until the player pauses or removes the bill.
## COUNT — craft exactly `target_count` times then auto-pause.
## UNTIL_N — keep a world-wide stockpile count of `recipe.output_type` at
## >= `target_count`; auto-pauses when the threshold is met,
## resumes when items are consumed below it.
##
## Save/load contract:
## var b2 := Bill.from_dict(b.to_dict())
## assert(b2.mode == b.mode and b2.completed_count == b.completed_count)
enum Mode {
FOREVER, ## Craft until paused by player.
COUNT, ## Craft exactly target_count times.
UNTIL_N, ## Maintain >= target_count of output_type in stockpiles.
}
## The recipe this bill executes. Must not be null when the bill is active.
var recipe: Recipe = null
## Which termination mode applies.
var mode: Mode = Mode.FOREVER
## COUNT: stop after this many completions. UNTIL_N: target world count.
var target_count: int = 0
## Number of successful craft outputs produced (used to gate COUNT mode).
var completed_count: int = 0
## True when the bill is manually paused by the player, or auto-paused by the
## engine (COUNT exhausted, UNTIL_N threshold met). CraftingProvider skips
## paused bills.
var paused: bool = false
# ── queries ───────────────────────────────────────────────────────────────────
## Returns true when CraftingProvider should pick up this bill.
## All three mode checks also short-circuit on paused.
func is_active() -> bool:
if paused:
return false
match mode:
Mode.FOREVER:
return true
Mode.COUNT:
return completed_count < target_count
Mode.UNTIL_N:
return _world_output_count() < target_count
return false
# ── state mutation ────────────────────────────────────────────────────────────
## Called by JobRunner._tick_craft after each successful craft output.
## Increments completed_count and auto-pauses COUNT bills that are exhausted.
func record_completion() -> void:
completed_count += 1
if mode == Mode.COUNT and completed_count >= target_count:
paused = true
# ── save / load ───────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
return {
"recipe": recipe.to_dict() if recipe != null else null,
"mode": mode,
"target_count": target_count,
"completed_count": completed_count,
"paused": paused,
}
static func from_dict(d: Dictionary) -> Bill:
var b := Bill.new()
b.mode = int(d.get("mode", Mode.FOREVER)) as Mode
b.target_count = int(d.get("target_count", 0))
b.completed_count = int(d.get("completed_count", 0))
b.paused = bool(d.get("paused", false))
var recipe_dict: Variant = d.get("recipe")
b.recipe = Recipe.from_dict(recipe_dict) if recipe_dict is Dictionary else null
return b
# ── helpers ───────────────────────────────────────────────────────────────────
## Counts world items of recipe.output_type that are not currently being
## carried — used by UNTIL_N mode. Queries World.items directly (no cache).
func _world_output_count() -> int:
if recipe == null:
return 0
var total: int = 0
for item in World.items:
if item.item_type == recipe.output_type and not item.being_carried:
total += item.stack_size
return total

1
scenes/ai/bill.gd.uid Normal file
View file

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

View file

@ -1,10 +1,10 @@
class_name ConstructionProvider extends WorkProvider
## WorkProvider for the "construction" work category.
##
## Scans World.build_queue for the nearest buildable site (Wall, Floor, Door
## anything exposing is_buildable() / on_build_tick() / tile / label()) and
## returns a two-toil Job:
## walk_to(site.tile) → build_at(site.get_path())
## Scans World.build_queue for the nearest buildable site (Wall, Floor, Door,
## Crate, Workbench — anything exposing is_buildable() / on_build_tick() /
## tile / label()) and returns a two-toil Job:
## walk_to(<build_stand_tile>) → build_at(site.get_path())
##
## The BUILD toil calls on_build_tick() once per sim tick; the entity internally
## tracks build_progress and calls _complete() when BUILD_TICKS is reached. The
@ -13,12 +13,21 @@ class_name ConstructionProvider extends WorkProvider
## Phase 5 simplification: materials are infinite — no haul-materials step.
## Phase 6+ will prepend walk_to(material_pile) + pickup() toils before walk_to(site).
##
## Phase 6 fix — wall-trap bug: walls call set_cell_walkable(false) on completion.
## If the pawn is STANDING ON the wall tile when that fires, the pawn is now
## on a solid cell and AStarGrid2D refuses to plan any subsequent path. Fix:
## walls (and any other site that returns true from blocks_pathing_when_complete)
## are built from an adjacent walkable tile. Floors / Doors / Crates / Workbenches
## stay walkable after completion, so on-tile building is fine for them.
##
## Duck-typing note: build-site entities are referenced without class_name to
## avoid registration-order issues. We rely only on:
## site.tile: Vector2i
## site.is_buildable() -> bool
## site.label() -> String
## site.get_path() -> NodePath
## Optionally:
## site.blocks_pathing_when_complete() -> bool # if absent, assumed false
func _init() -> void:
@ -45,8 +54,42 @@ func find_best_for(pawn) -> Job:
if best == null:
return null
# Pick where the pawn should stand. For sites that block pathing once built
# (walls) we route to an adjacent walkable cell; otherwise on-tile is fine.
var stand_tile: Vector2i = best.tile
if best.has_method("blocks_pathing_when_complete") and best.blocks_pathing_when_complete():
stand_tile = _find_adjacent_walkable(best.tile, pawn.tile)
if stand_tile == best.tile:
# No walkable neighbour — the site is fully boxed in. Skip and try later.
Audit.log("construction", "%s build %s at %s has no adjacent stand tile" % [pawn.pawn_name, best.label(), best.tile])
return null
var j := Job.new()
j.label = "Build %s at %s" % [best.label(), best.tile]
j.toils.append(Toil.walk_to(best.tile))
j.toils.append(Toil.walk_to(stand_tile))
j.toils.append(Toil.build_at(best.get_path()))
return j
# ── helpers ─────────────────────────────────────────────────────────────────
## Finds the 4-neighbour of `target` nearest to `prefer_near` that the pathfinder
## currently treats as walkable. Returns `target` itself if no walkable neighbour
## exists (caller treats that as "skip this site").
func _find_adjacent_walkable(target: Vector2i, prefer_near: Vector2i) -> Vector2i:
var offsets: Array[Vector2i] = [
Vector2i(0, -1), Vector2i(1, 0), Vector2i(0, 1), Vector2i(-1, 0),
]
var best: Vector2i = target
var best_dist: int = 999999
for off in offsets:
var t: Vector2i = target + off
if World.pathfinder == null:
continue
if not World.pathfinder.is_walkable(t):
continue
var d: int = abs(t.x - prefer_near.x) + abs(t.y - prefer_near.y)
if d < best_dist:
best_dist = d
best = t
return best

View file

@ -0,0 +1,105 @@
class_name CraftingProvider extends WorkProvider
## WorkProvider for the Crafting 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.workbenches for the best
## (Workbench, Bill) pair the pawn qualifies for, then builds a 4-toil job:
## walk_to(ingredient.tile) → pickup → walk_to(wb.tile) → craft_at(wb, bill_index)
##
## Scoring: Manhattan distance pawn→ingredient + ingredient→workbench (lower wins).
##
## Phase 6 simplification: pawn must be empty-handed (one task at a time); ingredient
## search is global (no per-bench radius restriction — Phase 17 polish item per
## docs/architecture.md "Ingredient acquisition radius").
##
## Workbench and Pawn are intentionally duck-typed (no class_name reference) to match
## WorkProvider convention and avoid init-order issues. Only Item.Quality and
## QualityCalc are referenced by class_name (in job_runner.gd, not here).
##
## See docs/architecture.md "CraftingProvider" and docs/design.md "Bills".
func _init() -> void:
category = &"crafting"
# Priority 4 — above haul (3), below chop (5).
# Phase 6 demo ordering; final 9-category matrix is authored in Phase 17.
priority = 4
# ── WorkProvider override ─────────────────────────────────────────────────────
## Returns a craft Job for `pawn`, or null if no valid work exists.
## Pawn must expose: .carried_item, .tile (Vector2i), .get_skill(StringName) -> int.
func find_best_for(pawn) -> Job:
# Skip if pawn is already carrying something — deposit first.
if pawn.get("carried_item") != null:
return null
var best_wb = null
var best_bill = null
var best_bill_index: int = -1
var best_src = null
var best_dist: int = 999999
for wb in World.workbenches:
# Duck-type guard: skip workbenches that aren't fully set up yet.
if not wb.get("_completed"):
continue
for i in wb.bills.size():
var b = wb.bills[i]
if not b.is_active():
continue
# Skill threshold check — pawn must meet the bill's minimum.
if pawn.get_skill(b.recipe.required_skill) < b.recipe.skill_threshold:
continue
# Confirm a qualifying ingredient exists on the floor.
var src = _find_ingredient_item(b.recipe.ingredient_type)
if src == null:
continue
# Score: total Manhattan travel distance pawn → ingredient → workbench.
var d: int = _manhattan(pawn.tile, src.tile) + _manhattan(src.tile, wb.tile)
if d < best_dist:
best_dist = d
best_wb = wb
best_bill = b
best_bill_index = i
best_src = src
if best_wb == null:
return null
# Re-resolve the source item in case multiple bills tied on the same item.
var src_item = _find_ingredient_item(best_bill.recipe.ingredient_type)
if src_item == null:
return null
var j := Job.new()
j.label = "Craft %s at %s" % [best_bill.recipe.label, best_wb.get("label_text") if best_wb.get("label_text") != null else "workbench"]
j.toils.append(Toil.walk_to(src_item.tile))
j.toils.append(Toil.pickup())
j.toils.append(Toil.walk_to(best_wb.tile))
j.toils.append(Toil.craft_at(best_wb.get_path(), best_bill_index))
return j
# ── private helpers ───────────────────────────────────────────────────────────
## Returns the first on-floor Item of matching type that is not being carried.
## Phase 6 simplification: global search, first match wins (no nearest-first
## at this layer — distance is factored into the outer loop scoring instead).
func _find_ingredient_item(item_type: StringName):
for it in World.items:
if it.being_carried:
continue
if it.item_type == item_type:
return it
return null
## Manhattan distance between two Vector2i tile coordinates.
func _manhattan(a: Vector2i, b: Vector2i) -> int:
return abs(a.x - b.x) + abs(a.y - b.y)

View file

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

View file

@ -99,6 +99,8 @@ func tick() -> void:
_tick_pickup(t)
Toil.KIND_DEPOSIT:
_tick_deposit(t)
Toil.KIND_CRAFT:
_tick_craft(t)
if t.done:
job.advance()
@ -338,6 +340,123 @@ func _tick_deposit(t) -> void:
t.done = true
## Execute one tick of a CRAFT toil.
##
## First tick (started=false):
## - Resolves the Workbench node from the stored NodePath. Missing → skip.
## - Looks up the Bill at data["bill_index"]. Out-of-range → skip.
## - Validates pawn position matches workbench.tile. Mismatch → skip.
## - Validates pawn is carrying the correct ingredient type. Missing → skip.
## - Calls wb.begin_craft(bill) to register the active bill + reset progress.
## - Marks started=true and logs the craft start.
##
## Every tick (including first, after the checks above):
## - Calls wb.tick_craft() which increments current_work_progress and returns
## true when bill.recipe.work_ticks is reached.
## - On completion:
## * Consumes the carried ingredient (queue_free + clear pawn slot).
## * Rolls quality via QualityCalc.roll() using the pawn's skill level.
## * Spawns an Item scene child of wb.get_parent() at wb.tile.
## * Calls wb.on_craft_complete() (records bill completion + resets state).
## * Logs the result and marks toil done.
func _tick_craft(t) -> void:
var wb_path := NodePath(t.data.get("workbench", ""))
var wb = get_tree().get_root().get_node_or_null(wb_path)
if not t.data.get("started", false):
# ── first-tick validation ─────────────────────────────────────────────
if wb == null or not is_instance_valid(wb):
Audit.log("job_runner", "%s craft: workbench gone — skipping" % pawn.pawn_name)
t.done = true
return
var bill_index: int = int(t.data.get("bill_index", -1))
if bill_index < 0 or bill_index >= wb.bills.size():
Audit.log(
"job_runner",
"%s craft: invalid bill_index %d — skipping" % [pawn.pawn_name, bill_index]
)
t.done = true
return
var bill = wb.bills[bill_index]
if pawn.tile != wb.tile:
Audit.log(
"job_runner",
"%s not at workbench (pawn=%s wb=%s) — skipping" % [pawn.pawn_name, pawn.tile, wb.tile]
)
t.done = true
return
if pawn.carried_item == null or pawn.carried_item.item_type != bill.recipe.ingredient_type:
Audit.log(
"job_runner",
"%s craft: wrong or missing ingredient — skipping" % pawn.pawn_name
)
t.done = true
return
# Register the bill with the workbench and reset its progress counter.
wb.begin_craft(bill)
t.data["started"] = true
Audit.log("job_runner", "%s craft start: %s" % [pawn.pawn_name, bill.recipe.label])
# ── per-tick progress ─────────────────────────────────────────────────────
# Re-resolve each tick in case the workbench was freed between ticks.
wb = get_tree().get_root().get_node_or_null(wb_path)
if wb == null or not is_instance_valid(wb):
t.done = true
return
# tick_craft() advances the progress counter and returns true when done.
var craft_done: bool = wb.tick_craft()
if not craft_done:
return # Still working — toil remains active.
# ── craft complete ────────────────────────────────────────────────────────
# Retrieve the bill now (before on_craft_complete clears current_bill).
var bill_index: int = int(t.data.get("bill_index", -1))
if bill_index < 0 or bill_index >= wb.bills.size():
# Guard against the workbench mutating bills mid-craft.
wb.on_craft_complete()
t.done = true
return
var bill = wb.bills[bill_index]
# Consume ingredient.
var ingredient = pawn.carried_item
pawn.carried_item = null
if ingredient != null and is_instance_valid(ingredient):
ingredient.queue_free()
# Roll quality based on pawn skill for this recipe.
var skill_level: int = pawn.get_skill(bill.recipe.required_skill)
var quality: int = QualityCalc.roll(skill_level)
# Spawn output Item as a sibling of the workbench (World scene level).
var item_scene: PackedScene = load("res://scenes/entities/item.tscn")
var output_item = item_scene.instantiate()
wb.get_parent().add_child(output_item)
output_item.setup(bill.recipe.output_type, 1, wb.tile)
output_item.quality = quality
# Record completion on the bill and reset workbench state.
wb.on_craft_complete()
Audit.log(
"job_runner",
"%s crafted %s ×1 quality=%s at %s" % [
pawn.pawn_name,
bill.recipe.output_type,
Item.Quality.keys()[quality],
wb.tile,
]
)
t.done = true
# ── helpers ──────────────────────────────────────────────────────────────────
## Emit job_completed, log, and clear the job reference.

35
scenes/ai/quality.gd Normal file
View file

@ -0,0 +1,35 @@
class_name QualityCalc
## Static helper for rolling an Item.Quality value at craft completion.
##
## Formula (docs/architecture.md "Quality system", Phase 6 spec):
## roll = skill_level × 0.04 + randf() × 0.6
##
## Bucket thresholds:
## roll < 0.10 → SHODDY
## 0.10 ≤ roll < 0.50 → NORMAL
## 0.50 ≤ roll < 0.80 → EXCELLENT
## 0.80 ≤ roll < 0.95 → MASTERWORK
## roll ≥ 0.95 → LEGENDARY
##
## Intuition by skill level (before RNG):
## skill 0: base 0.00; max roll ≈ 0.60 → Excellent ceiling, never Masterwork
## skill 5: base 0.20; roll ≈ 0.200.80 → Excellent comfortably, Masterwork possible
## skill 10: base 0.40; roll ≈ 0.401.00 → Masterwork attainable; Legendary rare (~8%)
##
## Returns an int matching Item.Quality enum values so no Item import is needed
## at call sites that only pass the int through. JobRunner logs via
## Item.Quality.keys()[quality] to get the enum name string.
static func roll(skill_level: int) -> int:
var base: float = float(skill_level) * 0.04
var noise: float = randf() * 0.6
var roll_val: float = base + noise
if roll_val < 0.10:
return Item.Quality.SHODDY
if roll_val < 0.50:
return Item.Quality.NORMAL
if roll_val < 0.80:
return Item.Quality.EXCELLENT
if roll_val < 0.95:
return Item.Quality.MASTERWORK
return Item.Quality.LEGENDARY

1
scenes/ai/quality.gd.uid Normal file
View file

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

64
scenes/ai/recipe.gd Normal file
View file

@ -0,0 +1,64 @@
class_name Recipe extends RefCounted
## A recipe describes one production step: what raw material goes in, what
## product comes out, how long it takes, and what skill is required.
##
## Phase 6 ships single-ingredient / single-output recipes. Multi-input is
## a Phase 7+ expansion — the dict seam in to_dict/from_dict already uses
## the same key names as the full architecture.md spec so no migration is needed.
##
## Save/load contract:
## var r2 := Recipe.from_dict(r.to_dict())
## assert(r2.id == r.id and r2.work_ticks == r.work_ticks)
const SKILL_CRAFTING: StringName = &"crafting"
const SKILL_COOKING: StringName = &"cooking"
## Unique identifier — e.g. &"plank", &"stone_block", &"basic_meal".
var id: StringName = &""
## Item type consumed by this recipe (single-ingredient for Phase 6).
var ingredient_type: StringName = &""
## Item type produced by this recipe.
var output_type: StringName = &""
## Sim ticks needed at 1× skill (no pawn modifier applied here).
var work_ticks: int = 100
## Which skill governs this recipe's quality roll and speed.
var required_skill: StringName = SKILL_CRAFTING
## Pawn's skill level must be >= this to be assigned this bill.
## Per design.md: skills modify duration and quality, never permission — so
## this threshold defaults to 0 (no gate); bill UI lets the player raise it.
var skill_threshold: int = 0
## Human-readable label for Audit logs and (later) bill UI. Not i18n'd here;
## call Strings.t("item." + id) for player-visible text.
var label: String = ""
# ── save / load ───────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
return {
"id": String(id),
"ingredient_type": String(ingredient_type),
"output_type": String(output_type),
"work_ticks": work_ticks,
"required_skill": String(required_skill),
"skill_threshold": skill_threshold,
"label": label,
}
static func from_dict(d: Dictionary) -> Recipe:
var r := Recipe.new()
r.id = StringName(d.get("id", ""))
r.ingredient_type = StringName(d.get("ingredient_type", ""))
r.output_type = StringName(d.get("output_type", ""))
r.work_ticks = int(d.get("work_ticks", 100))
r.required_skill = StringName(d.get("required_skill", str(SKILL_CRAFTING)))
r.skill_threshold = int(d.get("skill_threshold", 0))
r.label = str(d.get("label", ""))
return r

1
scenes/ai/recipe.gd.uid Normal file
View file

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

View file

@ -0,0 +1,34 @@
class_name RecipeCatalog
## Static registry of all Phase-6 recipes. Each method returns a fresh Recipe
## instance configured for that product. Extend here as new workbenches land
## (Phase 7+ cooking hearth, millstone, smithy, etc.).
##
## Phase 6 ships two recipes:
## plank() — wood → plank (Carpenter's bench, Crafting)
## stone_block() — stone → stone_block (Smelter, Crafting)
##
## The full ~22-recipe list per docs/design.md expands in Phase 7+.
static func plank() -> Recipe:
var r := Recipe.new()
r.id = &"plank"
r.label = "Wood plank"
r.ingredient_type = Item.TYPE_WOOD
r.output_type = Item.TYPE_PLANK
r.work_ticks = 60 # ~3 sim seconds at 1× (20 Hz × 3 s = 60 ticks)
r.required_skill = Recipe.SKILL_CRAFTING
r.skill_threshold = 0
return r
static func stone_block() -> Recipe:
var r := Recipe.new()
r.id = &"stone_block"
r.label = "Stone block"
r.ingredient_type = Item.TYPE_STONE
r.output_type = Item.TYPE_STONE_BLOCK
r.work_ticks = 80 # ~4 sim seconds at 1×
r.required_skill = Recipe.SKILL_CRAFTING
r.skill_threshold = 0
return r

View file

@ -0,0 +1 @@
uid://2kcj2y0fn1da

View file

@ -17,6 +17,7 @@ const KIND_INTERACT: StringName = &"interact" # Timed action on a target entity
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
const KIND_BUILD: StringName = &"build" # Timed construction on a Wall / Floor / Door entity
const KIND_CRAFT: StringName = &"craft" # Timed crafting at a Workbench driven by a Bill
var kind: StringName = KIND_IDLE
## Toil-specific params — all values must be int, float, bool, String, Dict, or Array.
@ -104,6 +105,24 @@ static func deposit() -> Toil:
return t
## Timed crafting action at a Workbench.
## `workbench_path` is the NodePath of the Workbench entity (stored as String for JSON safety).
## `bill_index` is the index into workbench.bills that this toil should run.
## JobRunner resolves the workbench and bill on the first tick, validates pawn position and
## carried ingredient, then advances workbench.current_work_progress each tick until
## bill.recipe.work_ticks is reached — at which point the ingredient is consumed, an output
## Item is spawned with a quality roll, and bill.record_completion() is called.
static func craft_at(workbench_path: NodePath, bill_index: int) -> Toil:
var t := Toil.new()
t.kind = KIND_CRAFT
t.data = {
"workbench": String(workbench_path),
"bill_index": bill_index,
"started": false,
}
return t
# ── save / load ──────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:

View file

@ -33,17 +33,27 @@ const TYPE_WEAPON: StringName = &"weapon" # Wp
const TYPE_ARMOR: StringName = &"armor" # Ar
const TYPE_CORPSE: StringName = &"corpse" # Co
# Phase 6 — intermediate crafted goods (carpenter bench + smelter outputs).
const TYPE_PLANK: StringName = &"plank"
const TYPE_STONE_BLOCK: StringName = &"stone_block"
const ALL_TYPES: Array[StringName] = [
TYPE_WOOD, TYPE_STONE, TYPE_IRON_ORE, TYPE_COPPER_ORE,
TYPE_SILVER, TYPE_GOLD, TYPE_CLOTH, TYPE_VEGETABLE,
TYPE_MEAT, TYPE_GRAIN, TYPE_MEAL, TYPE_MEDICINE,
TYPE_TOOL, TYPE_WEAPON, TYPE_ARMOR, TYPE_CORPSE,
TYPE_PLANK, TYPE_STONE_BLOCK,
]
# ── quality system (docs/architecture.md "Quality system") ───────────────────
# Rolled at craft-completion; stored per item; drives border colour in _draw().
enum Quality { SHODDY, NORMAL, EXCELLENT, MASTERWORK, LEGENDARY }
# ── state ────────────────────────────────────────────────────────────────────
@export var item_type: StringName = TYPE_WOOD
@export var stack_size: int = 1
@export var quality: Quality = Quality.NORMAL
var tile: Vector2i = Vector2i.ZERO
@ -92,6 +102,7 @@ func to_dict() -> Dictionary:
"stack_size": stack_size,
"tile_x": tile.x,
"tile_y": tile.y,
"quality": int(quality),
}
@ -104,6 +115,7 @@ static func from_dict(d: Dictionary) -> Dictionary:
"stack_size": int(d.get("stack_size", 1)),
"tile_x": int(d.get("tile_x", 0)),
"tile_y": int(d.get("tile_y", 0)),
"quality": int(d.get("quality", Quality.NORMAL)),
}
@ -119,6 +131,20 @@ func _draw() -> void:
draw_rect(square, fill)
draw_rect(square, Color(0.0, 0.0, 0.0, 0.75), false, 1.0)
# Quality border — drawn over the dark outline, colour per quality tier.
# NORMAL has no extra border (base outline is sufficient).
match quality:
Quality.SHODDY:
draw_rect(square, Color(0.40, 0.40, 0.40), false, 1.0)
Quality.EXCELLENT:
draw_rect(square, Color(0.20, 0.55, 0.95), false, 1.0)
Quality.MASTERWORK:
draw_rect(square, Color(0.85, 0.55, 0.10), false, 1.0)
Quality.LEGENDARY:
draw_rect(square, Color(0.85, 0.10, 0.80), false, 2.0)
_:
pass # NORMAL — no extra border
# Stack count badge — bottom-right corner of the square, font_size 7.
if stack_size > 1:
var label := Strings.t(&"item.stack_count").format({"n": stack_size})

View file

@ -71,6 +71,14 @@ func is_buildable() -> bool:
return not _completed
## Construction-provider hint: walls become impassable when built, so pawns
## must stand on an adjacent tile while building. Phase 6 fix for the
## "pawn-trapped-on-wall" bug. Floors / Doors / Crates / Workbenches don't
## need this since they remain walkable after completion.
func blocks_pathing_when_complete() -> bool:
return true
## Human-readable label for job descriptions and Audit logs.
func label() -> String:
return "%s wall" % wall_material

View file

@ -0,0 +1,302 @@
class_name Workbench extends Node2D
## Workbench entity — buildable structure where pawns craft items per bills.
##
## Rendered as a bottom-anchored sprite (Y-sorted) matching the 3/4-perspective
## convention from Wall/Door. Ghost state (40% alpha) while construction is
## in progress; solid once _completed.
##
## Variant appearance is driven by label_text:
## "Carpenter" → warm-brown wood bench with a vise detail
## "Smelter" → dark grey stone block with an orange ember glow
## Other → generic warm-grey fallback
##
## Bill model (architecture.md "Production: workbenches, recipes, bills"):
## bills[] — ordered queue of Bill objects (untyped; Bill class
## is authored by a sibling agent and may not be
## registered when this file compiles).
## current_bill — the Bill actively being worked; null when idle.
## current_work_progress — tick counter within the current craft cycle.
## JobRunner._tick_craft increments this each sim tick.
## Workbench resets it to 0 on cycle completion or
## when the pawn leaves mid-craft.
##
## Save/load: to_dict / from_dict capture all persistent fields, including
## each bill via bill.to_dict(). Mirrors the Crate save pattern.
##
## World registration: World.register_workbench / World.unregister_workbench
## are called from _ready / _exit_tree.
const TILE_SIZE_PX: int = 16
## Sim ticks to build a workbench (90 ticks ≈ 4.5 sim seconds at 1×).
const BUILD_TICKS: int = 90
# ── exports ───────────────────────────────────────────────────────────────────
## Tile position of this workbench in world-tile coordinates.
@export var tile: Vector2i = Vector2i.ZERO
## Player-visible label. Also drives the _draw() variant.
## Recognised values: "Carpenter", "Smelter". Others render generic.
@export var label_text: String = "Workbench"
## Which skill category this bench accepts.
## CraftingProvider filters by this before assigning a pawn.
@export var accepted_skill: StringName = &"crafting"
# ── state ─────────────────────────────────────────────────────────────────────
## Ticks of construction work applied so far. 0..BUILD_TICKS.
var build_progress: int = 0
## True once build_progress >= BUILD_TICKS.
var _completed: bool = false
## Ordered queue of Bill objects. Untyped so this file compiles before the
## Bill class is registered by the sibling agent. CraftingProvider reads this.
var bills: Array = []
## The Bill being actively worked right now. null when idle.
## Set by JobRunner when it begins a craft toil; cleared on completion or
## when the pawn walks away (job cancelled / interrupted).
var current_bill = null
## Sim-tick progress within the current craft cycle. Incremented by
## JobRunner._tick_craft once per sim tick. Reset to 0:
## - when a craft completes (on_craft_complete)
## - when no pawn is actively crafting (JobRunner cancel / pawn interruption)
## JobRunner reads this to decide whether the recipe's work_ticks are done.
var current_work_progress: int = 0
# ── lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
# Position is bottom-anchored so Y-sort occludes pawns correctly.
position = Vector2(
tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0,
tile.y * TILE_SIZE_PX + TILE_SIZE_PX
)
World.register_workbench(self)
queue_redraw()
func _exit_tree() -> void:
World.unregister_workbench(self)
## One-shot initialiser. Call after add_child() so _ready() has fired.
func setup(p_tile: Vector2i) -> void:
tile = p_tile
position = Vector2(
tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0,
tile.y * TILE_SIZE_PX + TILE_SIZE_PX
)
queue_redraw()
# ── BuildJob interface ────────────────────────────────────────────────────────
## True while the workbench still needs construction work.
## JobRunner's BUILD toil checks this to decide when the toil is done.
func is_buildable() -> bool:
return not _completed
## Human-readable label for job descriptions and Audit logs.
func label() -> String:
return label_text
## Called by the BUILD toil in JobRunner once per sim tick.
## Advances build_progress; completes the workbench at BUILD_TICKS.
func on_build_tick() -> void:
if _completed:
return
build_progress += 1
queue_redraw()
if build_progress >= BUILD_TICKS:
_complete()
## True once the workbench has been fully built.
func is_completed() -> bool:
return _completed
# ── Bills ─────────────────────────────────────────────────────────────────────
## Append a bill to the queue.
func add_bill(b) -> void:
bills.append(b)
Audit.log("workbench", "%s: bill added — recipe '%s'" % [label_text, b.recipe.id])
## Return the first bill that is active and whose required_skill matches
## this bench's accepted_skill. Returns null when none qualify.
## CraftingProvider calls this; JobRunner also calls it when the current_bill
## becomes inactive (UNTIL_N threshold reached, paused, etc.).
func find_active_bill():
for b in bills:
if not b.is_active():
continue
if b.recipe.required_skill != accepted_skill:
continue
return b
return null
# ── Craft-cycle hooks (called by JobRunner) ───────────────────────────────────
## JobRunner calls this when it starts working a bill on this bench.
## Stores the active bill and resets the tick counter.
func begin_craft(b) -> void:
current_bill = b
current_work_progress = 0
## JobRunner calls this once per sim tick while a pawn is actively crafting.
## Returns true when the recipe's work_ticks have been reached (craft done).
func tick_craft() -> bool:
if current_bill == null:
return false
current_work_progress += 1
return current_work_progress >= current_bill.recipe.work_ticks
## JobRunner calls this on craft completion before spawning the output item.
## Records the completion on the bill, resets state.
func on_craft_complete() -> void:
if current_bill != null:
current_bill.record_completion()
current_bill = null
current_work_progress = 0
## JobRunner calls this when the craft is interrupted (pawn leaves, cancel, etc.).
## Resets in-progress state so another pawn can start fresh.
func on_craft_interrupted() -> void:
current_bill = null
current_work_progress = 0
# ── save / load ───────────────────────────────────────────────────────────────
## Serialise workbench state for World save (wired in Phase 16).
func to_dict() -> Dictionary:
var bills_data: Array = []
for b in bills:
bills_data.append(b.to_dict())
return {
"tile_x": tile.x,
"tile_y": tile.y,
"label_text": label_text,
"accepted_skill": String(accepted_skill),
"build_progress": build_progress,
"completed": _completed,
"current_work_progress": current_work_progress,
"bills": bills_data,
}
## Restore from a dict produced by to_dict().
## Bill objects are reconstructed by the caller using Bill.from_dict() once the
## Bill class is registered. current_bill is left null — JobRunner reconnects
## from its own saved state on the next sim tick.
func from_dict(d: Dictionary) -> void:
tile = Vector2i(int(d.get("tile_x", 0)), int(d.get("tile_y", 0)))
label_text = str(d.get("label_text", "Workbench"))
accepted_skill = StringName(d.get("accepted_skill", "crafting"))
build_progress = int(d.get("build_progress", 0))
_completed = bool(d.get("completed", false))
current_work_progress = int(d.get("current_work_progress", 0))
# Bills are re-populated by World.load_workbenches() after Bill class loads.
# Raw dicts are kept in the dict; the caller handles reconstruction.
setup(tile)
# ── render ─────────────────────────────────────────────────────────────────────
func _draw() -> void:
# 3/4-perspective bench rendering — fits within the tile (16×16 local box).
# Origin (0,0) = tile bottom-centre. Tile spans local Y: -16 to 0.
# Two-band look (matches Wall): lit top band + shaded front face.
# Ghost (not yet built) draws at 0.4 alpha.
var alpha: float = 1.0 if _completed else 0.4
match label_text:
"Carpenter":
_draw_carpenter(alpha)
"Smelter":
_draw_smelter(alpha)
_:
_draw_generic(alpha)
func _draw_carpenter(alpha: float) -> void:
# Warm-brown wood bench. Top band lit, front face darker.
# Vise/saw detail: a small darker square at the top-right corner of the
# front face to suggest a mounted tool.
var top_face := Color(0.62, 0.45, 0.25, alpha)
var front_face := Color(0.52, 0.36, 0.18, alpha)
var plank := Color(0.34, 0.22, 0.10, alpha)
var vise := Color(0.28, 0.18, 0.08, alpha)
var outline := Color(0.20, 0.12, 0.04, 0.7 * alpha)
# Top face — lit strip at upper-third of tile.
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 5.0)), top_face)
# Front face — lower body.
draw_rect(Rect2(Vector2(-8.0, -11.0), Vector2(16.0, 11.0)), front_face)
# Horizontal plank seam across the front face.
draw_line(Vector2(-8.0, -6.0), Vector2(8.0, -6.0), plank, 1.0)
# Vise detail: 4×4 px darker square at top-right of front face.
draw_rect(Rect2(Vector2(3.0, -11.0), Vector2(4.0, 4.0)), vise)
# Top/front edge horizon line.
draw_line(Vector2(-8.0, -11.0), Vector2(8.0, -11.0), plank, 1.0)
# Tile outline.
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 16.0)), outline, false, 1.0)
func _draw_smelter(alpha: float) -> void:
# Dark grey stone block. Top band slightly lighter.
# Ember glow: orange rect centred at the bottom of the front face.
var top_face := Color(0.42, 0.42, 0.40, alpha)
var front_face := Color(0.32, 0.32, 0.30, alpha)
var mortar := Color(0.20, 0.20, 0.18, alpha)
var ember := Color(0.95, 0.45, 0.10, alpha)
var outline := Color(0.14, 0.14, 0.12, 0.7 * alpha)
# Top face.
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 5.0)), top_face)
# Front face.
draw_rect(Rect2(Vector2(-8.0, -11.0), Vector2(16.0, 11.0)), front_face)
# Mortar line.
draw_line(Vector2(-8.0, -6.0), Vector2(8.0, -6.0), mortar, 1.0)
# Ember glow: 6×3 px orange rect, horizontally centred, at bottom of front face.
draw_rect(Rect2(Vector2(-3.0, -3.0), Vector2(6.0, 3.0)), ember)
# Top/front edge horizon line.
draw_line(Vector2(-8.0, -11.0), Vector2(8.0, -11.0), mortar, 1.0)
# Tile outline.
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 16.0)), outline, false, 1.0)
func _draw_generic(alpha: float) -> void:
# Warm-grey fallback bench. Simple two-band block with a single seam.
var top_face := Color(0.58, 0.55, 0.50, alpha)
var front_face := Color(0.42, 0.40, 0.36, alpha)
var seam := Color(0.30, 0.28, 0.25, alpha)
var outline := Color(0.20, 0.18, 0.16, 0.7 * alpha)
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 5.0)), top_face)
draw_rect(Rect2(Vector2(-8.0, -11.0), Vector2(16.0, 11.0)), front_face)
draw_line(Vector2(-8.0, -6.0), Vector2(8.0, -6.0), seam, 1.0)
draw_line(Vector2(-8.0, -11.0), Vector2(8.0, -11.0), seam, 1.0)
draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 16.0)), outline, false, 1.0)
# ── internal ──────────────────────────────────────────────────────────────────
func _complete() -> void:
_completed = true
queue_redraw()
Audit.log("workbench", "%s built at %s" % [label_text, tile])

View file

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

View file

@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3 uid="uid://workbench_entity"]
[ext_resource type="Script" path="res://scenes/entities/workbench.gd" id="1_workbench"]
[node name="Workbench" type="Node2D"]
y_sort_enabled = true
z_index = 0
script = ExtResource("1_workbench")

View file

@ -26,6 +26,19 @@ class_name Pawn
const STEP_TICKS: int = 10
const TILE_SIZE_PX: int = 16 # Mirrors World.TILE_SIZE_PX; standalone so Pawn needs no World reference.
# ── skill definitions (docs/design.md "Skills") ──────────────────────────────
# Five skills, levels 010. Level by use; multiplicative speed/quality bonus.
# Skills modify duration and quality, never permission (design.md:35).
const SKILL_MANUAL_LABOR: StringName = &"manual_labor"
const SKILL_CRAFTING: StringName = &"crafting"
const SKILL_COOKING: StringName = &"cooking"
const SKILL_MEDICINE: StringName = &"medicine"
const SKILL_COMBAT: StringName = &"combat"
const ALL_SKILLS: Array[StringName] = [
SKILL_MANUAL_LABOR, SKILL_CRAFTING, SKILL_COOKING, SKILL_MEDICINE, SKILL_COMBAT,
]
signal walk_started
signal walk_completed
signal arrived_at_destination(tile: Vector2i)
@ -47,6 +60,11 @@ var job_runner = null
# one type at a time per design.md.
var carried_item = null
# Phase 6 — skill levels. Initialized to 0 for all five skills in _ready().
# Use get_skill() / set_skill() to access; direct dict mutation is allowed
# for batch operations (e.g. from_dict restoring saved data).
var skills: Dictionary = {}
var _path: Array[Vector2i] = []
var _step_progress: float = 0.0
var _selected: bool = false
@ -58,6 +76,11 @@ var _selected: bool = false
func _ready() -> void:
EventBus.sim_tick.connect(_on_sim_tick)
_state_label.text = Strings.t(&"pawn.state.idle")
# Initialise all five skills to 0 if not already set (from_dict sets them
# before _ready() fires in some load paths — only fill missing keys here).
for skill in ALL_SKILLS:
if not skills.has(skill):
skills[skill] = 0
func setup(p_name: String, start_tile: Vector2i) -> void:
@ -99,12 +122,29 @@ func is_selected() -> bool:
return _selected
## Returns the pawn's current level (010) for the given skill.
## Returns 0 for unknown skills so callers need no nil-guard.
func get_skill(skill: StringName) -> int:
return int(skills.get(skill, 0))
## Sets skill to level, clamped to [0, 10]. Asserts the key is a known skill.
func set_skill(skill: StringName, level: int) -> void:
assert(skill in ALL_SKILLS, "set_skill: unknown skill '%s'" % skill)
skills[skill] = clampi(level, 0, 10)
# ── save / load ─────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
var path_data: Array = []
for v in _path:
path_data.append([v.x, v.y])
# Serialise skills as {"manual_labor": 0, "crafting": 3, ...} — StringName
# keys must be stored as plain Strings for JSON round-trip safety.
var skills_data: Dictionary = {}
for skill in ALL_SKILLS:
skills_data[String(skill)] = get_skill(skill)
return {
"name": pawn_name,
"tile_x": tile.x,
@ -114,6 +154,7 @@ func to_dict() -> Dictionary:
"selected": _selected,
"forced_job": forced_job.to_dict() if forced_job != null else null,
"job_runner": job_runner.to_dict() if job_runner != null else null,
"skills": skills_data,
}
@ -135,6 +176,15 @@ func from_dict(d: Dictionary) -> void:
if jr_dict is Dictionary and job_runner != null:
job_runner.from_dict(jr_dict)
# Restore skills — set directly on the dict to bypass the ALL_SKILLS assert
# (from_dict must be resilient to saves that pre-date a new skill being added).
var saved_skills: Variant = d.get("skills")
if saved_skills is Dictionary:
for raw_key in saved_skills.keys():
var skill := StringName(raw_key)
if skill in ALL_SKILLS:
skills[skill] = clampi(int(saved_skills[raw_key]), 0, 10)
_name_label.text = pawn_name
_state_label.text = Strings.t(&"pawn.state.walking") if is_walking() else Strings.t(&"pawn.state.idle")
position = _tile_to_world(tile)

View file

@ -25,12 +25,16 @@ const WALL_SCENE: PackedScene = preload("res://scenes/entities/wall.tscn")
const FLOOR_SCENE: PackedScene = preload("res://scenes/entities/floor.tscn")
const DOOR_SCENE: PackedScene = preload("res://scenes/entities/door.tscn")
const CRATE_SCENE: PackedScene = preload("res://scenes/world/crate.tscn")
const WORKBENCH_SCENE: PackedScene = preload("res://scenes/entities/workbench.tscn")
# 3 starting pawns — Phase 2 demo. Phase 7+ replaces this with map-gen + name table.
const SAMPLE_PAWNS: Array[Dictionary] = [
{"name": "Bram", "tile": Vector2i(20, 40)},
{"name": "Cora", "tile": Vector2i(25, 40)},
{"name": "Edda", "tile": Vector2i(30, 40)},
# Phase 6 demo — varied Crafting skill so the quality system shows visible
# spread. Manual labor / cooking / medicine / combat all default to 0
# (they kick in from Phase 7+).
{"name": "Bram", "tile": Vector2i(20, 40), "crafting": 8}, # high — makes mostly Excellent / Masterwork / occasional Legendary
{"name": "Cora", "tile": Vector2i(25, 40), "crafting": 4}, # medium — Normal / Excellent mix
{"name": "Edda", "tile": Vector2i(30, 40), "crafting": 0}, # low — Shoddy / Normal only
]
# Phase 4 — sample harvestables. Trees clustered east, rocks south-east.
@ -59,6 +63,7 @@ const HAUL_SWEEP_INTERVAL_TICKS: int = 100
@onready var mine_provider: MineProvider = $MineProvider
@onready var hauling_provider: HaulingProvider = $HaulingProvider
@onready var construction_provider: ConstructionProvider = $ConstructionProvider
@onready var crafting_provider: CraftingProvider = $CraftingProvider
func _ready() -> void:
@ -88,11 +93,14 @@ func _ready() -> void:
# Designation: bind the paint surface + the Selection guard.
designation_ctl.bind(designation_layer, selection)
# Register all 5 providers — Decision iterates by .priority desc.
# construction=6 > chop=5 > mine=4 > haul=3 > rest=0.
# Register all 6 providers — Decision iterates by .priority desc.
# construction=6 > chop=5 > mine=4 > crafting=4 > haul=3 > rest=0.
# (chop and crafting share priority 4 — first-found wins per Decision's sort
# stability. Phase 17 can finalize the priority order via playtest.)
World.register_work_provider(construction_provider)
World.register_work_provider(chop_provider)
World.register_work_provider(mine_provider)
World.register_work_provider(crafting_provider)
World.register_work_provider(hauling_provider)
World.register_work_provider(rest_provider)
@ -194,6 +202,10 @@ func _spawn_sample_pawns() -> void:
jr.setup(p, pathfinder)
p.job_runner = jr
# Phase 6: seed Crafting skill so the quality demo shows variety.
if spawn_data.has("crafting"):
p.set_skill(Pawn.SKILL_CRAFTING, int(spawn_data["crafting"]))
World.register_pawn(p)
@ -275,6 +287,36 @@ func _seed_phase5_demo_buildings() -> void:
wall_count, floor_count, 1 + crate_tiles.size()
])
# Phase 6 demo — two pre-built workbenches inside the cabin with bills.
# Carpenter at (46, 25) makes wood → plank, FOREVER.
# Smelter at (48, 25) makes stone → stone_block, UNTIL 5 in stockpiles.
var carpenter: Workbench = WORKBENCH_SCENE.instantiate()
add_child(carpenter)
carpenter.setup(Vector2i(46, 25))
carpenter.label_text = "Carpenter"
carpenter.accepted_skill = Pawn.SKILL_CRAFTING
while carpenter.is_buildable():
carpenter.on_build_tick()
var plank_bill := Bill.new()
plank_bill.recipe = RecipeCatalog.plank()
plank_bill.mode = Bill.Mode.FOREVER
carpenter.add_bill(plank_bill)
var smelter: Workbench = WORKBENCH_SCENE.instantiate()
add_child(smelter)
smelter.setup(Vector2i(48, 25))
smelter.label_text = "Smelter"
smelter.accepted_skill = Pawn.SKILL_CRAFTING
while smelter.is_buildable():
smelter.on_build_tick()
var block_bill := Bill.new()
block_bill.recipe = RecipeCatalog.stone_block()
block_bill.mode = Bill.Mode.UNTIL_N
block_bill.target_count = 5
smelter.add_bill(block_bill)
Audit.log("world", "phase 6 demo: 2 workbenches built (Carpenter→planks FOREVER, Smelter→blocks UNTIL_N=5)")
func _spawn_sample_stockpiles() -> void:
# Two zones for the Phase 4 acceptance demo:

View file

@ -1,4 +1,4 @@
[gd_scene load_steps=11 format=3 uid="uid://rimlike_world"]
[gd_scene load_steps=12 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"]
@ -10,6 +10,7 @@
[ext_resource type="Script" path="res://scenes/ai/hauling_provider.gd" id="8_hauling_provider"]
[ext_resource type="Script" path="res://scenes/ai/construction_provider.gd" id="9_construction_provider"]
[ext_resource type="Script" path="res://scenes/world/designation.gd" id="10_designation"]
[ext_resource type="Script" path="res://scenes/ai/crafting_provider.gd" id="11_crafting_provider"]
[node name="World" type="Node2D"]
y_sort_enabled = true
@ -62,5 +63,8 @@ script = ExtResource("8_hauling_provider")
[node name="ConstructionProvider" type="Node" parent="."]
script = ExtResource("9_construction_provider")
[node name="CraftingProvider" type="Node" parent="."]
script = ExtResource("11_crafting_provider")
[node name="CameraRig" parent="." instance=ExtResource("2_camera")]
position = Vector2(640, 640)