Compare commits

...
108 Commits
Author SHA1 Message Date
jpmschweitzer 11b29baefe Merge branch 'sprint-32/client' 2026-04-06 16:45:14 +02:00
jpmschweitzerandClaude Opus 4.6 168c5e0d9b fix(ui): restore STANCE_ICONS constant removed during refactor
Startup crash — preload loop referenced STANCE_ICONS but the constant
was accidentally dropped when rewriting the icon cache logic.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 16:43:49 +02:00
jpmschweitzerandClaude Opus 4.6 746ed05e2d fix(ui): address PR #118 review — 5 items
- Preload stance icons at _ready() into cache Dictionary
- Null-guard shader + theme loads with push_error() + early return
- Guard _icon_mat.set_shader_parameter inside if _icon_mat:
- Icon size 18→20px per D-086, container height 44→46px to fit
- Add _apply_stance test coverage (known + unknown stance)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 16:41:27 +02:00
jpmschweitzer 6ce708a15a Merge branch 'sprint-32/copy' 2026-04-06 16:33:05 +02:00
jpmschweitzerandClaude Opus 4.6 bb61d860d6 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 16:30:57 +02:00
jpmschweitzerandClaude Opus 4.6 a14828e02a refactor(ui): add stance icons to implant badge (#787)
Replace text-only stance labels with SVG icons + tint shader per D-086.
Alpha-mask shader swaps color at runtime via ShaderMaterial parameter.
Icons: walk, crouch, careful, sprint at 18px inside ImplantPanel row.
Also fix stale UILayer/HUD test path in test_ui_framework_sprint15.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 16:30:22 +02:00
jpmschweitzerandClaude Opus 4.6 16fb644a12 fix(wiki): remove placeholder economic fields from GJ-280B stub
GJ-280B is a stub pending full generation — economic profile fields
were speculative and should not be present until the system is properly
authored.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:27:33 +02:00
jpmschweitzerandClaude Opus 4.6 07abad2df5 fix(wiki): address PR #116 review — TOML key mismatches, broken link, profile corrections
- Fix 16 lore_archetype keys in tier1.toml to match lore.toml definitions
- Fix 4 commodity ID mismatches (medical_re-embodiment, fine_dining, vehicles, entertainment)
- Add pharmaceutical_manufacturer archetype to lore.toml
- Fix station_module_constructor note (Cygni B → Sova Station Works)
- Create GJ-280B stub (Sova Station Works HQ system)
- Add Station Sova cross-reference to sova-station-works.md
- Fix GJ-251 and GJ-144 economic exports (financial_services contradictions)
- Split corporation index into Narrative Profiles and Tier 1 sections

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:25:44 +02:00
jpmschweitzer d986bfea30 Merge branch 'sprint-32/visual' 2026-04-06 16:23:07 +02:00
jpmschweitzerandClaude Opus 4.6 0c3eddee39 fix(assets): address PR #117 review comments
- Remove tracked kallast_terrain.npy (HIGH — binary in git)
- Amend D-086: stance + interaction icons delivered, not deferred
- Create ticket #818 for icon_tint.gdshader (client team)
- Fix gas giant profile table: suppress gravity/land%/hydrosphere
- Fix atmosphere_color: null when atmosphere is none
- Fix gas_giant_ringed display as gas_giant in profile table
- Re-scaffold + regenerate Ran system with fixes

.import sidecars: not applicable — gitignored by design (client/**/*.import).
Godot auto-generates on first run.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 16:19:53 +02:00
jpmschweitzerandClaude Opus 4.6 f73d5ba69f data(wiki): 25 Tier-1 corporation profiles (#797)
Adds 25 new named corporations covering D-175 priority gaps: financial
services (Groombridge Settlement House, Compact Financial Exchange,
Meridian Risk), re-embodiment (Somatic Futures, Blue Collective), east
reach anchors, Compact distributors, freight, mining, medical, lattice,
and more. Each corp has lore + behavioral archetype, political tension,
administered silence, currency preference, and branded products.

Includes TOML records in wiki/economics/corporations/tier1.toml and
narrative wiki pages in wiki/corporations/.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:05:25 +02:00
jpmschweitzerandClaude Opus 4.6 1e4a44da18 data(wiki): corporation archetype taxonomy (#798)
Adds wiki/economics/archetypes/ with 28 lore archetypes (WHAT/WHERE)
and 6 behavioral archetypes (HOW) as TOML templates. These are the
generation templates for Tier-2 and Tier-3 corporations per D-175.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:04:53 +02:00
jpmschweitzerandClaude Opus 4.6 199770ee41 data(wiki): add Bodies/Population rows + economic profiles to 301 systems (#790, #781)
Adds Bodies and Population rows to System Profile tables across all 301
star-system wiki pages. Adds Industries, Exports, and Imports economic
profile rows derived from systems.db economic_base + body type + topology.
Includes 9 body/station name changes from cultural diversity remediation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:03:56 +02:00
jpmschweitzerandClaude Opus 4.6 941a7218d2 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:00:45 +02:00
jpmschweitzerandClaude Opus 4.6 db3daecfaf chore(config): add JSON syntax validation to pre-push hook
Validates changed JSON files using python3 -m json.tool (zero
dependencies). Same diff-based scoping as existing checks — only
files changed vs remote are validated. Blocks push on syntax errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:00:29 +02:00
jpmschweitzerandClaude Opus 4.6 c57488a86b fix(skills): filter NULL teams from sprint worktree creation
Tickets with no team assignment caused start-sprint.sh to create
a spurious "sprint-N/None" worktree and Ptyxis tab. Filter at both
the SQL level (AND team IS NOT NULL) and Python level (if r['team']).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:00:21 +02:00
jpmschweitzerandClaude Opus 4.6 6286cf5d2c chore(assets): fix ruff lint warnings in planet-gen scripts
Remove unused imports (os, sys, math, ImageFilter, gaussian_filter,
MAX_BIOME_ID) flagged by ruff F401.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:57:05 +02:00
jpmschweitzerandClaude Sonnet 4.6 c5c6922385 content(wiki): cultural diversity sweep — apply #784 plan (#793)
20 changes across 18 systems implementing the approved remediation plan
from the cultural diversity audit (docs/design/cultural-diversity-audit.md).

DB changes (15 bodies/stations in systems.db):
- Thai bodies: Saikaew (GJ 635B), Nakhon Sung (GJ 667C), Doi Kaeo (GJ 117)
- Khmer bodies: Banteay (GJ 434), Srok Thmei (GJ 866A)
- Ukrainian: Chornozem body + Svoboda station (GJ 729)
- Caribbean: Lavenille body (GJ 873), Accompong Works station (GJ 406)
- Malay: Pulau Baru body (GJ 555), Balai station (GJ 449)
- Scientists: Huygens Platform (GJ 251), Ramanujan Station (GJ 699),
  van Leeuwenhoek Station (GJ 820B), Turing Survey (GJ 663A)

Wiki calibration note additions:
- GJ 635B/667C/117/434: Thai cultural presence (survey teams, founding cohorts)
- GJ 866A/873: Khmer/Caribbean community naming origin
- GJ 729: Ukrainian founding cooperative in west_reach
- GJ 1245A/75: Igbo/Nigerian heritage explicitly acknowledged
- GJ 172: Malay kelong dual-heritage in Kaelong name
- GJ 601A: Russian secondary founding stream in Ostmark

Horizon stations not renamed. No corridor reassignments.
Conservative: systems with existing identity untouched.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 15:56:38 +02:00
jpmschweitzerandClaude Opus 4.6 c32cdf11d4 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:55:38 +02:00
jpmschweitzerandClaude Opus 4.6 c3d6230eed feat(assets): generate Ran system bodies — 10 planets/moons with assets
First system through the planet generator pipeline. Per-body wiki
pages with YAML frontmatter at wiki/star-systems/GJ-144/bodies/.
Each body has: index.md (definition + profile), heightmap.png
(4096×2048), globe.png (512×512), and markers.json (rivers, oceans,
mountain ranges).

Bodies: GJ144b-g + moons. Includes temperate (Kallast, Vethis),
frozen, barren moons, and a ringed gas giant.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:54:58 +02:00
jpmschweitzerandClaude Opus 4.6 1c6c5b9978 feat(assets): heightmap pipeline spike — prototype + test inputs
PO-built prototype (FBM terrain, Whittaker biomes, procedural globe)
with test body definitions for all planet types. Replaces pyplatec
approach. Spike validates the pipeline architecture for batch #817.

Includes handover doc, 9 test body definitions, and updated spike
pipeline documentation. Stale pyplatec outputs removed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:54:35 +02:00
jpmschweitzerandClaude Opus 4.6 f84275edf3 feat(assets): planet generator pipeline — heightmap + globe from wiki data
Full terrain-to-render pipeline at tooling/planet-gen/:
- body_definition_parser: reads system index.md → body definitions
- planet_simulation: FBM + Voronoi ridges, Whittaker biome classification,
  D8 river routing, physics-driven craters (atmo × tectonics scaling)
- render_heightmap: 4096×2048 cartographic maps with hillshade
- planet_renderer: 512×512 globe with terrain UV mapping, clouds, rings
- biomes.toml: externalized color/classification tables (single source)
- scaffold_bodies: creates per-body index.md with YAML frontmatter
- batch: unattended processing with error handling, resume, determinism check

Supports all body types: temperate, arid, frozen, volcanic, barren,
oceanic, gas giant (banded + ringed), and moons (half-size, grey, cratered).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:54:15 +02:00
jpmschweitzerandClaude Opus 4.6 f968ee23f1 chore(config): add scipy + Pillow deps, gitignore terrain/spike data
scipy 1.17.1 and Pillow 12.2.0 — both CVE-audited clean against
NVD + OSV (2026-04-06). Required by planet generator pipeline.
Gitignore generated terrain.npz, spike intermediates, and tmp files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:53:55 +02:00
jpmschweitzerandClaude Opus 4.6 35ad862387 fix(assets): revise health cross icon and careful stance silhouette
Health icon: replaced overlapping outlined rects (railroad crossing
effect) with a single solid polygon path. Careful stance: redesigned
from diagonal-arm to horizontal T-shape for clear differentiation
from walk at 20px.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:53:34 +02:00
jpmschweitzerandClaude Opus 4.6 879ef6092f fix(ui): address PR #115 review — 8 items
- Fix stale test path UILayer/HUD → InsertOverlay/HUD
- Fix D-record citation D-051 → D-049 in main.tscn
- Add null guards to hud.gd update methods (pre-_ready safety)
- Minimap: dirty-flag queue_redraw instead of per-frame
- Remove redundant _panel.size.x, debug print
- Fix DebugOverlay/GauntletHUD positioning comments

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 15:45:47 +02:00
jpmschweitzerandClaude Opus 4.6 8c239d522c chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 12:52:34 +02:00
jpmschweitzerandClaude Opus 4.6 b2b67d52f8 refactor(ui): add implant container frame to minimap (#787)
Draw ImplantTheme-styled StyleBoxFlat behind the circular minimap for
visual consistency with other implant components. Stance badge icons
remain blocked by #795 (visual team).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 12:52:06 +02:00
jpmschweitzerandClaude Opus 4.6 283518d332 refactor(ui): convert HUD status + interaction prompt to implant (#786, #788)
HUD: merge TimeDisplay into ImplantPanel (time/health/perception in one
panel), remove dead tscn nodes, move HUD to InsertOverlay for D-051 bloom.
Interaction prompt: convert from PanelContainer+StyleBoxFlat to Control
with ImplantPanel+ImplantDataRow, fix panel height for 42px minimum.
Tests updated for new scene structure and public API.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 12:51:58 +02:00
jpmschweitzerandClaude Opus 4.6 3c7231e275 fix(ui): resolve HUD layout overlaps (#792)
- DebugOverlay: position comment updated, tscn is source of truth
- GauntletHUD: moved from y:48 to y:252 (below StanceIndicator)
- StanceIndicator: offset_top 192→200, height 26→44px for ImplantPanel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-06 12:51:48 +02:00
jpmschweitzerandClaude Sonnet 4.6 c9541362f9 fix(assets): clean up stale grain_belt comment in settlement scorer
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:19:42 +02:00
jpmschweitzerandClaude Sonnet 4.6 f64ee9dded feat(assets): annotated heightmap pipeline — Kallast spike #778
Validates full heightmap pipeline: pyplatec tectonics → erosion →
dynamic sea level → terrain classification (13 classes) → D8 river
network → settlement placement → geographic PNG + settlement JSON.

Key technical decisions:
- Dynamic sea level via np.percentile (pyplatec output is right-skewed;
  fixed fraction gives ~0.2% land, not 40%)
- Terrain classes as fractions of land_range (not fixed offsets)
- Two-layer model: geographic PNG + human-layer JSON sidecar
- Rivers painted AFTER LANCZOS upscale via NEAREST neighbor mask
  (painting before blurs rivers into invisibility)
- grain_belt removed — reclassified as grassland (natural terrain)
- Irrigation overlay removed — human activity, lives in JSON sidecar

Output: 4096×2048px (1024×512 simulation grid, 5.2s total runtime).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:19:23 +02:00
jpmschweitzerandClaude Sonnet 4.6 1cffc83dd7 feat(assets): procedural planet renders for wiki/GTTR — #779
7 planet type PNGs (512×512px RGBA) covering all biome_summary values:
temperate, temperate_terminator, oceanic, arid, frozen, volcanic, barren.

Pure Python ray-sphere renderer (spikes/planet-renders/generate_planets.py)
— numpy/PIL only, no Godot dependency, ~2s for all 7 types. Seeded from
body_id for reproducibility. Resolves Q-064 (Godot 3D planet plugin
evaluation — superseded by headless Python approach).

Assets at client/assets/planets/, 512×512 RGBA, displayed at 240×240 in
the body-info-panel navigator and GTTR arrival window.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:19:06 +02:00
jpmschweitzerandClaude Sonnet 4.6 b5cb93203b feat(assets): implant HUD icon set v0.1 — #795
13 SVG icons covering stance indicators (walk/careful/sprint/crouch),
status badges (health, perception), interaction prompts (talk/observe/
follow/examine), and inventory silhouettes (manifest, access token,
comm log).

All D-086 compliant: 1px stroke, #c8d0e0 chrome, round linecaps,
minimal anchor points, no icon fonts, runtime-replaceable via
ShaderMaterial. Sizes: 20×20 (stance/status), 16×16 (actions),
40×40 (inventory). Unblocks client #787.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:18:56 +02:00
jpmschweitzerandClaude Opus 4.6 f1b97d4a88 fix(economics): address 17 PR review comments on #114
Blocking fixes:
- V-13: legal_services demand_model compliance→market (build-breaker)
- D-184: political flag names match TOML (commission_certified etc.)
- D-184: professional services list matches TOML
- D-173: elasticity count 5→4, cross-ref to D-184
- Workshop outcomes: fix self-contradicting fusion fuel statement
- R-011: move to end of file (was between D-183 and D-184)

Should-fix:
- D-166 domain link scope.md→architecture.md
- Sprint briefing counts updated (13→17 D-records, #801 marked done)
- Burnelli-Sheldon added to agent roster + briefing created
- questions-architecture.md footer tally updated
- medical_services demand_model utility→market
- timber display name drop "/Biomass"

Polish:
- D-171 Groombridge clarified (clearing house, not co-issuer)
- hospitality description has Reach texture
- commission_certification shadow_viable=false rationale in description
- Ticket #801 description updated
- Wiki pages regenerated

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 22:18:41 +02:00
jpmschweitzerandClaude Opus 4.6 69d0659066 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 22:01:00 +02:00
jpmschweitzerandClaude Opus 4.6 ac05dbd21f data(economics): commodity catalog — 36 types, 21 production chains
Workshop #801 deliverable: commodities.toml (36 commodities across
5 tiers), production_chains.toml (21 Leontief recipes including
2 substitution routes), schema.md (SQL DDL + validation rules).

Key design choices: brands are not commodities (separate layer),
water→fuel at 8:1 yield, 3 political sub-flags replacing single
boolean, gate energy-over-gate as commercial service. Wiki stub
pages generated for all 36 commodities.

Tickets #811–#815 created for follow-up work. #801 closed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 22:00:33 +02:00
jpmschweitzerandClaude Opus 4.6 9b1258568e docs(decisions): economics design workshop #796 — D-171 through D-187
Workshop #796 produced 13 D-records (D-171–D-183) defining the Phase 2
economics layer: three-currency system, commodity taxonomy, shadow
economy, corporation tiers, productivity seeding, simulation
architecture, TOML data pipeline.

Workshop #801 added D-184–D-187: commodity catalog (36 types), brands
are not commodities, gate transmission levels (mass+data+energy),
fusion fuel as intermediate (8:1 water yield).

R-011 filed (single currency rejected). Burnelli-Sheldon agent added.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 22:00:18 +02:00
jpmschweitzerandClaude Opus 4.6 b4e4c65830 docs(meta): update Sprint 32 briefings after workshop #796
Post-workshop briefing updates: joint notes with dependency chain,
planning team task list, copy/visual team scope adjustments, TEAM.md
roster update.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 22:00:03 +02:00
jpmschweitzerandClaude Opus 4.6 3d1ff6ad2e chore(meta): plan Sprint 32: Landfall
14 tickets across 4 teams + planning track:
- Copy (4): cultural audit #784 (analysis only), batch edits #793
  (blocked), system profiles #790, economic profiles #781
- Visual (4): heightmap spike #778, batch heightmaps #794 (blocked),
  screenshots #779, icon design #795
- Client (4): HUD layout #792, status/minimap/interaction → implant
  #786/#787/#788. #787 blocked by icon design.
- Planning (1): Phase 2 economics kickoff #796

New tickets: #793, #794, #795, #796

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:40:27 +02:00
jpmschweitzerandClaude Opus 4.6 050aeafc01 chore(kit): remove worktree-update skill, fix pr-review severity tiers
- Delete worktree-update skill template (replaced by sprint branches)
- Remove worktree-update references from settings, manifests, tests
- Update customization-examples to sprint-branch language
- Remove three-tier severity from pr-review template (every comment
  is actionable, no suggestion tier)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:21:20 +02:00
jpmschweitzerandClaude Opus 4.6 706b4565d4 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:17:14 +02:00
jpmschweitzerandClaude Opus 4.6 5683b1dc4b chore(config): fix skill contradictions, gitignore .obsidian, docs cleanup
- sprint-start: remove three-tier severity (critical/warning/suggestion),
  align with pr-review policy (every comment is actionable)
- sprint-start: resolve {team_scope_dirs} dangling placeholder
- .gitignore: add .obsidian/ directory
- DEVOPS.md: remove "pending setup" from gdlint (now enforced)
- Remove GEMINI-SCAN.md one-off scan artifact

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:16:51 +02:00
jpmschweitzerandClaude Opus 4.6 cfddcfb117 docs(briefings): extract shared PROJECT_STATE.md, purge stale boilerplate
Create PROJECT_STATE.md at repo root with cascade phase table,
decision count, and current sprint. All 18 briefings now reference
this file instead of duplicating the project state paragraph.

Also removes stale content from briefings:
- "v0.2 direction: generator-first" (contradicts D-166 cascade)
- "Sprint 25 generator spike confirmed as critical path" (Phase 5)
- Agent-specific generator prerequisite claims
- Gestalt "v0.2 Pivot" section reframed as "Key Design Pivots"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:16:39 +02:00
jpmschweitzerandClaude Opus 4.6 1254e41dc5 docs(decisions): amend stale D-records, close resolved Q-records
Amend 7 high-priority D-records with supersession notes:
- D-012: map size superseded by D-094 (256x256)
- D-044: outline color scoped to perception mode per D-154
- D-061: width corrected from 640px to 1200px per D-076
- D-086: smuggler scope removed per D-117/D-122
- D-090: marked [SUPERSEDED] by D-117 (tycoon replaces smuggler/detective)
- D-035: character enum marked obsolete post-D-117
- D-119: sequencing superseded by D-166 cascade

Close 4 resolved scope questions (Q-002, Q-004, Q-005, Q-007).
Fix questions.md index — was 61, actually 96 (33 architecture Qs missing).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 15:16:27 +02:00
jpmschweitzerandClaude Opus 4.6 ef072416ba docs(architecture): update CLAUDE.md, project structure, D-170 for implant UI system
- CLAUDE.md: added Implant UI component library section (D-169, D-170)
- project-structure.md: added client/ui/implant/, hud_groups.gd, gameplay_renderer.gd
- D-170: corrected implementation note from visibility toggling to z-index layering

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:43:10 +02:00
jpmschweitzerandClaude Opus 4.6 8421ac4d27 chore(config): gitignore settings.db WAL files, sync Cargo.lock version
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:38:55 +02:00
jpmschweitzerandClaude Opus 4.6 eeac6405d6 fix(ui): HUD layout pass — resolve overlapping elements (#792)
- HUD status panel moved to y=80 (below TimeDisplay at 16-70)
- Removed redundant time row from HUD (TimeDisplay handles it)
- Debug overlay starts at y=150 (below HUD status panel)
- Stance indicator moved below minimap (y=192, was overlapping at y=16)
- Interaction prompt moved to y=-240 (above dialogue box at -200)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:35:37 +02:00
jpmschweitzerandClaude Opus 4.6 26a63d3899 feat(ui): convert HUD status, stance, interaction prompt to implant theme (D-169)
- HUD: programmatically builds ImplantPanel with health/mode/time rows,
  replaces raw MarginContainer/VBoxContainer/Labels
- Stance indicator: ImplantPanel with color-coded ImplantDataRow,
  replaces custom _draw() with hardcoded bg/text
- Interaction prompt: applies implant theme StyleBox + colors to
  existing PanelContainer layout

Minimap left as-is — its circular frame is a distinct diegetic element,
not rectangular panel chrome.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:25:33 +02:00
jpmschweitzerandClaude Opus 4.6 a7fbf7a0d9 feat(ui): zoom-based LoD for star map labels
Labels now appear based on zoom level and system importance:
- Always: selected + hovered
- Zoom >= 1.2: hubs, junctions, gateway
- Zoom >= 2.0: all named systems
- Below 1.2: only selected/hovered

Prevents label soup at overview zoom levels.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:20:00 +02:00
jpmschweitzerandClaude Opus 4.6 3439b05e88 feat(ui): show all system names on star map, centered below dots
All named systems get a label below their dot. text_dim for default,
text_primary for selected/hovered. Removed duplicate label from
_draw_selection (now handled by _draw_systems).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:17:31 +02:00
jpmschweitzerandClaude Opus 4.6 9cdc86d65d fix(data): star map bodies + population from systems.db, not wiki
Generator now queries bodies/stations tables directly for habitable
count, inhabited count, and total population. All 301 systems have
data — unsettled systems show "0 habitable · 0 inhabited" and "0".
Fixed stale worktree path to systems.db.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:11:39 +02:00
jpmschweitzerandClaude Opus 4.6 3f611ae0f7 fix(ui): star map info — hop merged into corridor line, bodies on one line
"CORE corridor (hop 1)" with sector color. Bodies back to single line
"1 habitable · 1 inhabited" as originally formatted in the data.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 12:03:25 +02:00
jpmschweitzerandClaude Opus 4.6 5400044afe feat(ui): star map info panel — one item per line, GDP placeholder
Layout now shows each field on its own line:
  star type / hop / corridor / habitable / inhabited / pop / GDP
GDP shows "—" placeholder until economics data is available.
Population shows full number without ellipsis.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:57:49 +02:00
jpmschweitzerandClaude Opus 4.6 34a21d4cd0 feat(rendering): GameplayRenderer base class — occlusion for all renderers (D-170)
New GameplayRenderer extends Node2D with built-in occlusion support.
Subclasses override _gameplay_process() and _gameplay_draw() instead
of _process() and _draw() — these are skipped when a fullscreen
implant app covers gameplay.

Migrated all 5 gameplay renderers:
- CursorRenderer: hover detection + bracket drawing paused
- EntityRenderer: position lerping paused
- FogEntities: fog dot rendering paused
- SoundIndicatorRenderer: directional arrows paused
- WorldRenderer: tile/fog/entity updates paused

No more manual occlusion wiring — the base class handles everything.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:51:30 +02:00
jpmschweitzerandClaude Opus 4.6 a01f7c9cfb fix(ui): cursor z-index 100, adjacent wraps, panel clamp with reset_size
- CursorRenderer z_index=100 so it renders above all HUD/implant layers
- Adjacent systems uses ImplantTextBlock (wraps) instead of ImplantDataRow (clips)
- Panel calls reset_size() before clamping to get accurate height on first frame

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:34:34 +02:00
jpmschweitzerandClaude Opus 4.6 0d46180e39 fix(ui): remove cursor_renderer from gameplay group
CursorRenderer must always render on top — shouldn't have its z-index
managed by HudGroups. It's a world-space renderer, not a HUD element.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:30:35 +02:00
jpmschweitzerandClaude Opus 4.6 7fb155c9a8 fix(ui): restore StarMap node in hud.tscn
Accidentally deleted when exploring reparenting options. The z-index
model means it stays as a child of HUD — no reparenting needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:28:31 +02:00
jpmschweitzerandClaude Opus 4.6 e4fafb66d5 style(client): gdformat main.gd
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:26:01 +02:00
jpmschweitzerandClaude Opus 4.6 ffef2b3d54 fix(ui): gdlint ordering — signals before enums, signal uses int for Mode
Moved signals above enum per gdlint class-definitions-order rule.
app_changed signal uses int instead of Mode type to avoid the
forward-reference that forced wrong ordering. Callers compare
against HudGroups.Mode.FULLSCREEN etc unchanged.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:25:22 +02:00
jpmschweitzerandClaude Opus 4.6 2e01081de7 refactor(ui): HudGroups z-index model + gameplay occlusion (D-170)
Replaced visibility toggling with z-index layer management. Nothing
gets hidden — fullscreen apps render on top, gameplay stays underneath.
Supports future hybrid layouts (insert-mode map alongside gameplay).

Added gameplay_occluded signal: WorldRenderer skips tile/fog/entity
updates when a fullscreen implant app covers it. Prevents wasted
render work behind opaque overlays. Other renderers can connect to
the same signal.

Modes: GAMEPLAY (z=0), INSERT (z=10), FULLSCREEN (z=20), MODAL (z=30).
Star map uses app_changed signal to toggle its own visibility based
on whether its app is active.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:21:31 +02:00
jpmschweitzerandClaude Opus 4.6 09e0c522bd fix(client): split PowerProfile enum to fix last gdlint warning
gdformat collapsed enum + 3 inline comments into one 300-char line.
Split to multi-line enum with doc comments.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:10:13 +02:00
jpmschweitzerandClaude Opus 4.6 88c7407cb6 style(client): gdformat all 52 GDScript files — zero format warnings
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:09:10 +02:00
jpmschweitzerandClaude Opus 4.6 572e66f026 fix(ui): remove Node2D cursor_renderer from Control-typed HudGroups array
CursorRenderer extends Node2D, not Control — can't be registered in
HudGroups. Removed from gameplay group. Also dropped typed array
annotation to avoid runtime type mismatch errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:07:34 +02:00
jpmschweitzerandClaude Opus 4.6 22d74ab6ad refactor(ui): star map registers as implant/map/starchart
Deeper taxonomy: map is a family of views (starchart, system, station,
planet, location), not one app. Same HudGroups mechanics — just a
more specific path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:05:26 +02:00
jpmschweitzerandClaude Opus 4.6 5ad2452213 feat(ui): implant app hierarchy in HudGroups (D-170)
Implant apps use hierarchical groups: implant/map, implant/wiki,
implant/journal, etc. Apps are mutually exclusive with each other
and with gameplay. Opening implant/map hides gameplay + any other
implant app. Closing returns to gameplay.

API: open_app(), close_app(), toggle_app(), is_app_active().
Star map uses implant/map. Future apps register their own group.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:04:19 +02:00
jpmschweitzerandClaude Opus 4.6 f037bcaa81 feat(ui): HUD visibility groups — gameplay vs implant layers (D-170)
New HudGroups autoload manages show/hide of related HUD elements as
groups. Exclusive groups (gameplay, implant) are mutually exclusive —
opening the star map hides stance indicator, minimap, interaction
prompts, etc. Closing it restores them.

Gameplay nodes registered in main.gd _ready(). Star map registers as
implant group and uses toggle_group() instead of direct visibility.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:01:28 +02:00
jpmschweitzerandClaude Opus 4.6 44cc8cda4c fix(ui): data rows clip to one line, panel clamped to screen
ImplantDataRow uses clip_text + ellipsis instead of wrapping — each
info item stays on one line. Panel position clamped so bottom edge
never exceeds screen bounds.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:57:35 +02:00
jpmschweitzerandClaude Opus 4.6 f0c6e97742 fix(ui): correct Godot 4.6 size flag constants
SIZE_FLAGS_FILL → SIZE_FILL, SIZE_FLAGS_SHRINK_END → SIZE_SHRINK_END.
The _FLAGS_ prefix was removed in Godot 4.6.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:54:11 +02:00
jpmschweitzerandClaude Opus 4.6 6ad1c8255f fix(ui): implant panel width constraint and text wrapping
Panel now clips content and constrains children to its width.
Components set autowrap and SIZE_FLAGS_FILL so text wraps within
the panel instead of overflowing. Bold markdown markers stripped
in ImplantTextBlock constructor.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:51:25 +02:00
jpmschweitzerandClaude Opus 4.6 962596fd57 feat(ui): implant component library + star map refactor (D-169)
New component library at client/ui/implant/:
- ImplantTheme: shared Resource with colors, spacing, font sizes
- ImplantPanel: PanelContainer root with themed background/border
- ImplantHeader: title + subtitle
- ImplantSeparator: themed horizontal rule with above/below spacing
- ImplantDataRow: single-line text with optional color override
- ImplantTextBlock: RichTextLabel for wrapping narrative text
- default_implant.tres: default theme resource

Star map info panel refactored from 140 lines of manual draw_string
calls to 50 lines of component composition via _rebuild_info_panel().

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:47:23 +02:00
jpmschweitzerandClaude Opus 4.6 4dd95ba50b docs(decisions): D-169 Implant UI component library — Control node tree
Control nodes with shared Theme resource, not _draw() components.
Dynamic implant system (hardware variants, upgrades, faction overlays)
requires layout automation and theme swapping that _draw() can't provide.

Component set: Panel, Header, Separator, DataRow, TextBlock, StatusBadge,
ProgressBar, TabRow, Expandable. Semantic color roles defined.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:43:05 +02:00
jpmschweitzerandClaude Opus 4.6 8d02b110ae fix(ui): star map info panel spacing — split separator padding
Separators now have explicit above (6px) and below (12px) spacing
relative to text baselines. Previously a single 8px block didn't
account for baseline positioning, causing text to merge with
separator lines. Line height bumped to 18px.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:35:05 +02:00
jpmschweitzerandClaude Opus 4.6 73ed0be22c chore(process): quality and polish is the golden standard
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:31:44 +02:00
jpmschweitzerandClaude Opus 4.6 b14c19c65e chore(process): all review comments actionable + pushback flow
Remove severity tiers from PR reviews. Every comment must be addressed
before merge — no "suggestion" category that gets skipped. Teams can
push back on specific comments with a technical rationale; team lead
evaluates and can retract. Bar: "the reviewer was wrong" not "we don't
want to."

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:30:21 +02:00
jpmschweitzerandClaude Opus 4.6 d2ea687ec3 fix(ui): star map info panel — dynamic height measurement
Panel now measures all variable content (GTTR text, adjacent systems)
before calculating height. Fixes clipping on hub systems with many
neighbors and long GTTR excerpts. Unified separator spacing (8px).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:27:45 +02:00
jpmschweitzerandClaude Opus 4.6 a22bc6ce46 chore(meta): release v0.1.31
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:23:56 +02:00
jpmschweitzerandClaude Opus 4.6 ea57a9da70 fix(db): auto-unassign done tickets on sprint close
sprint stop now clears assigned_to on all done tickets in the closing
sprint. Agents don't clean up after themselves — this was causing
5 bookkeeping warnings every sprint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 10:20:31 +02:00
jpmschweitzer bee93ddbb7 Merge remote-tracking branch 'origin/sprint-31/client' 2026-04-05 10:17:15 +02:00
jpmschweitzerandClaude Opus 4.6 4eb54a6f7a fix(client): resolve all gdlint warnings — zero warnings policy
Fix 354 gdlint warnings across 65 files: 194 class-definitions-order
(reorder declarations), 138 max-line-length (split long lines),
22 code issues (unused args, no-else-return, naming). Update .gdlintrc
to exclude addons/ and raise max-public-methods for test files.
No logic changes — declaration order, whitespace, and naming only.

Ticket: #783

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:59:56 +02:00
jpmschweitzer 5941ff791f Merge remote-tracking branch 'origin/sprint-31/server'
# Conflicts:
#	CHANGELOG.md
2026-04-05 09:59:46 +02:00
jpmschweitzerandClaude Opus 4.6 260eefcdd1 refactor(client): decompose main.gd and game_state.gd god objects
Extract SnapshotHandler (static snapshot parsing), SnapshotConsumers
(non-dialogue consumers + audio handlers), and DialogueCoordinator
(dialogue consumers + signal handlers) as class_name scripts.

main.gd: 28KB → 13KB. game_state.gd: 20KB → 8.5KB.
Autoload parse-order safety maintained via load() inline pattern.

Ticket: #775

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:59:34 +02:00
jpmschweitzerandClaude Opus 4.6 8eb9e0a383 feat(ui): star map click-through with wiki/GTTR popup and edge visibility
Show system profile popup on select: name, star type, hop distance,
corridor, GTTR excerpt, body count, population, adjacent systems.
Edge rendering changed to show no edges by default, only selected
system's gate lines on click. Star map data extended with wiki fields
for all 301 systems.

Ticket: #780

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:59:18 +02:00
jpmschweitzerandClaude Opus 4.6 65bcbd0aa7 fix(meta): move changelog entry to root CHANGELOG.md
Remove erroneous server/CHANGELOG.md and add the atlas split entry
to the project root CHANGELOG.md where it belongs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:56:53 +02:00
jpmschweitzer 784bcbf034 Merge remote-tracking branch 'origin/sprint-31/copy' 2026-04-05 09:54:47 +02:00
jpmschweitzer 742d51a3c4 Merge remote-tracking branch 'origin/sprint-31/ci' 2026-04-05 09:54:31 +02:00
jpmschweitzerandClaude Opus 4.6 84c3314924 fix(skills): sprint-start team branch must not run pr-review
Team worktree windows stay on their sprint branch. PR reviews run from
main. Updated step 9b to explicitly stop the team lead from spawning
reviewers — push the PR and wait for feedback instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:47:50 +02:00
jpmschweitzerandClaude Opus 4.6 f60ae48769 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:40:32 +02:00
jpmschweitzerandClaude Opus 4.6 fe788a0ae3 fix(simulation): rustfmt long argument lists in atlas dispatch
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:40:28 +02:00
jpmschweitzerandClaude Opus 4.6 74d6aee0c1 chore(ci): add ruff to pre-push hook and Makefile
Add Python/ruff block to .config/hooks/pre-push (runs on tooling/
changes). Add lint-python and setup-venv Makefile targets, wire
both into make lint and make setup respectively.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:40:10 +02:00
jpmschweitzerandClaude Opus 4.6 2300d9659d fix(tooling): remove unused imports flagged by ruff
Drop unused hashlib, math, and os imports from assign-astro-ids,
generate-star-map, and test_quaternius_raw to pass ruff clean.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:40:02 +02:00
jpmschweitzerandClaude Opus 4.6 980201fb49 chore(db): wire ensure_venv() into connector scripts
Add venv auto-activation to audio_batch, audio_connector,
image_connector, qdrant_connector, and trellis_connector.
Scripts re-exec into .venv/bin/python when invoked outside
the venv, with a friendly error if .venv is missing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:39:55 +02:00
jpmschweitzerandClaude Opus 4.6 1640c880da fix(simulation): suppress clippy too_many_arguments on cmd_add_body
The refactor from &Commands to individual parameters exposed the
13-argument signature to clippy. Allow attribute is appropriate
here — the parameters map 1:1 to DB columns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:39:52 +02:00
jpmschweitzerandClaude Opus 4.6 d86ebada8d refactor(db): extract shared DB module from duplicated patterns
Create tooling/db/common.py with resolve_db_path(), load_config(),
get_connection(), and ensure_venv(). Update ticket, sprint,
sqlite_connector.py, and decisions_sync.py to import from common
instead of duplicating. Fixes pre-existing NameError in
decisions_sync.py (missing import os). Add pyproject.toml with
ruff config (ruff==0.15.9, CVE-clean) and dev dependencies.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:39:46 +02:00
jpmschweitzerandClaude Opus 4.6 7f23185035 chore(meta): update changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:38:15 +02:00
jpmschweitzerandClaude Opus 4.6 fb5c8854e8 refactor(simulation): split atlas.rs subcommands into modules
Extract 2119-line monolithic atlas.rs into 8 focused modules under
src/bin/atlas/: main.rs (thin dispatch), common.rs (shared types and
DB helpers), show.rs, mutate.rs, stats.rs, systems.rs, author.rs,
and sync_wiki.rs. Commands enum stays in main.rs; each match arm
delegates to module::cmd_fn(&conn, args). No behavior change.

Closes #776.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 09:37:04 +02:00
jpmschweitzerandClaude Opus 4.6 9135f1c656 data(wiki): update west corridor Adams ratings for Lichtung and Haltefenn (#766)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:36:31 +02:00
jpmschweitzerandClaude Opus 4.6 a97e2267f0 data(wiki): per-body GTTR entries for 25 moons and stations (#782)
Hub systems at hops 0-4 with pop >10K now have individual GTTR entries.
Covers Gateway, Sirius, ACB, Cygni B, Bastion, Nova Roma, Fremantle,
Kampala Gate, Aurelius, Puerto Rivera, and Okafor Station. Each follows
the established drifter's-voice format with Adams rating and practical
information sections.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:36:16 +02:00
jpmschweitzerandClaude Opus 4.6 807e8b74a6 data(wiki): cultural diversity sweep — 4 additional systems enriched (#766)
Schuilhoek (GJ-68): data-wealth commercial dynasty subversion.
Helderoog (GJ-111): genetic protocol precision subversion.
Helle Wacht (GJ-598): philosophical colony governance cost.
Altgrund (GJ-189): institutional archive refugee integration.
Also updates Adams ratings in gttr-deep.md for all enriched systems.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:35:56 +02:00
jpmschweitzerandClaude Opus 4.6 898b9c747f data(wiki): enrich Nova Estrada and Entremeio GTTRs to batch standard (#774)
Nova Estrada: added founding agreement time-bomb, thirty-year cost, and
infrastructure audition sections. Entremeio: added transit policy, lake
settlement, and Assembly defiance sections. Both now match Kettenschmied
quality bar.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:35:47 +02:00
jpmschweitzerandClaude Sonnet 4.6 2ee095306b docs(wiki): cultural stereotyping sweep — 6 entries enriched (ticket #766)
Subversions added or made explicit across 3 most-imbalanced groups:

Afrikaans/Dutch:
- Breëvlei (GJ-661B): xenobiology research community, pre-settlement
  marsh stakes of unknown origin drive community identity
- Bestevaer (GJ-103): Dutch maritime mystery culture; Diepzeecommissie
  secretly building capacity to investigate restricted deep zone

German:
- Lichtung (GJ-356A): full rewrite → artists' colony, F-type light
  environment, no industrial or agricultural purpose
- Haltefenn (GJ-1248): Moorlesen craft tradition (peat-layer reading as
  art) now primary economic identity over peat fuel extraction

Portuguese:
- Espinho (GJ-1075): science/research subversion made explicit on page
- Nascente (GJ-2097): Irmandade reframed as commercial dynasty via 400
  years of freight transit intelligence

Also creates docs/audits/cultural-stereotyping-audit.md with full audit
findings, ratios, recommendations, and follow-up scope for Sprint 32+.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 09:28:56 +02:00
jpmschweitzerandClaude Sonnet 4.6 b21b28df61 docs(decisions): D-168 Iserlohn (GJ-532c) IP evaluation — retained
Real German city origin (Sauerland wire-drawing centre) documented.
Context diverges fundamentally from LoGH fortress. Altena recorded
as preferred alternative. Ticket #773.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 09:28:34 +02:00
jpmschweitzerandClaude Opus 4.6 b3ae632530 fix(skills): auto-run /sprint-start in team tabs
Pass "claude /sprint-start" as the initial tmux command so each team
tab loads its briefing and spawns agents automatically — no manual
step needed after tabs open.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:53:40 +02:00
jpmschweitzerandClaude Opus 4.6 4249a79aa6 fix(skills): open sprint tabs in current window, no duplicate main tab
start-sprint.sh now uses --tab for all teams (opens in active Ptyxis
window) instead of --new-window. No separate main tab — the caller
is already on main.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:51:46 +02:00
jpmschweitzerandClaude Opus 4.6 4dd866c9ad feat(skills): integrate start-sprint into sprint-start skill
Move start-sprint.sh into .claude/skills/sprint-start/scripts/ (was
standalone at parent directory level). Sprint-start Case B now calls
the script automatically after activating a sprint — creates ephemeral
worktrees and opens Ptyxis tabs for each active team.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:47:49 +02:00
jpmschweitzerandClaude Opus 4.6 4628458ab0 chore(process): add zero-warnings policy to pr-push and pr-review
- pr-push step 1b: lint check before pushing (gdlint, clippy, ruff)
- pr-review step 0c: check warning count before spawning reviewers
- Added .gdlintrc with max-line-length: 120
- Created ticket #783 for Sprint 31: clean up existing 253 warnings
- Updated #780 with edge visibility rule (show edges only for selected system)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:39:50 +02:00
jpmschweitzerandClaude Opus 4.6 469114cb0e fix(ui): wire M keybind for star map toggle, clean up info panel
- Add _unhandled_key_input to main.gd: M toggles star_map.toggle_visible()
- Remove topology line from info panel (internal data, not player-facing)
- Cast aperture_count to int (was showing decimal point)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:33:07 +02:00
jpmschweitzerandClaude Opus 4.6 822cf34bbc chore(meta): plan Sprint 31: Bedrock
Phase 1 wiki completion (cultural sweep, GTTR depth, star map popups)
+ infrastructure refactors (atlas.rs, main.gd, Python tooling).

8 tickets: copy (4), client (2), server (1), ci (1).
Cascade dependencies locked: Phase 1→2→3→4→5→6.
#693 cancelled (superseded by #704 compositor).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:17:28 +02:00
jpmschweitzerandClaude Opus 4.6 dd75203d11 refactor(process): replace persistent team worktrees with ephemeral sprint branches
Persistent worktrees (server, client, copy, audio, visual, ci, planning,
maintenance) caused agents crossing boundaries, stuck agents leaving
uncommitted work, and index.lock collisions. Replaced with ephemeral
sprint branches (sprint-{N}/{team}) and worktrees created on demand.

Changes:
- New start-sprint script replaces start-session (dynamic tabs per active team)
- Sprint teardown integrated into sprint-start skill (A1c step)
- SR_DB_PATH env var for database access from any directory
- CLAUDE.md team boundaries rewritten (scope-based, not directory-based)
- Agent Rule 0 updated to team scope dirs instead of worktree isolation
- PR review uses git show instead of cross-directory reads
- Briefing template updated for sprint-{N}/{team} branch naming
- Deleted worktree-update skill (obsolete)
- Removed WORKTREE_TEAM env var and cross-directory Read permissions
- All 8 persistent worktrees removed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 00:33:02 +02:00
716 changed files with 38746 additions and 5521 deletions
+1
View File
@@ -26,6 +26,7 @@ All agents read their briefing file at `docs/briefings/{name}.md` before startin
| Agent | File | Role | Model | When to use |
|-------|------|------|-------|-------------|
| `troblum` | troblum.md | Technical Consultant / Tyre's sparring partner | sonnet | Evaluation sidequests alongside Tyre |
| `burnelli-sheldon` | burnelli-sheldon.md | Economist & Simulation Modeler | sonnet | Economic systems, market models, price formation, stability analysis |
| `araminta` | araminta.md | Visual Designer | sonnet | Visual decisions, style guides, asset generation |
| `hoshe` | hoshe.md | QA Engineer / Tester | sonnet | Testing, test plans, bug reports, verification |
+42
View File
@@ -0,0 +1,42 @@
---
name: burnelli-sheldon
description: Economist and Simulation Modeler for the Settled Reach game project. Use when designing economic systems, evaluating market models, grounding supply/demand mechanics in real economic theory, building price formation models, or when the team needs someone to ask "is this economically credible?" Covers both conceptual frameworks (market equilibrium, price elasticity, input-output models) and quantitative modeling (convergence algorithms, stability analysis, parameter tuning).
tools: Read, Glob, Grep, Edit, Write
model: sonnet
memory: project
---
You are BURNELLI-SHELDON, the Economist on a game development team building a top-down immersive sim set in the Settled Reach universe.
## Your personality
You are an economist who fell into game design because nobody else was asking "but how do markets actually clear?" You think in supply curves, elasticity gradients, and equilibrium dynamics. You say things like "That's not how markets work" and "The interesting question is what happens at the margin" and "Let me sketch the incentive structure."
You bridge theory and practice. You know Leontief input-output models and Walrasian equilibrium, but you also know that a game economy needs to FEEL right more than it needs to be formally correct. Your job is to ensure the simulation produces behavior that an economically literate player would find credible — not to build a general equilibrium model.
You get excited about emergent market dynamics — when a simple price formation rule produces realistic-looking boom/bust cycles without anyone scripting them. You're suspicious of hand-tuned "balancing" and prefer systems that find their own equilibria. Your least favorite phrase is "we'll just set the prices manually."
Named for the Burnelli-Sheldon dynasty — old money that understood how wealth compounds across centuries. You bring that long-view economic thinking to game systems.
## Your role on the team
- Ground economic design in real economic theory (market models, price formation, production functions)
- Design simulation mathematics (convergence algorithms, stability analysis, damping)
- Evaluate whether proposed economic mechanics produce credible behavior
- Define the quantitative framework (key parameters, tuning knobs, equilibrium conditions)
- Identify economic pitfalls (runaway inflation, degenerate equilibria, exploitable loops)
- Bridge between Gestalt's "is this fun?" and Tyre's "can we build this?" with "is this economically sound?"
- Advise on monetary policy, currency design, and value systems
## Design principles you hold
- **Markets should clear**: Every good should have a price where supply meets demand. If it doesn't, something is wrong with the model.
- **Incentives drive behavior**: NPCs and systems should respond to price signals, not scripts. If ore prices rise, mining should increase. If it doesn't, the incentive structure is broken.
- **Complexity from simple rules**: A few well-chosen production functions and price adjustment rules should produce rich, realistic-looking economic behavior.
- **Information has value**: Price discovery, market intelligence, and information asymmetry are economic fundamentals, not game design add-ons.
- **Stability matters**: An economy that crashes to zero or inflates to infinity has failed. Equilibrium-seeking behavior must be designed in, not bolted on.
- **Scale appropriately**: A 300-system economy needs aggregation. Not every transaction needs simulation — only the ones that matter to the player or to systemic behavior.
## Project context
Read your briefing at `docs/briefings/burnelli-sheldon.md` before starting work (if it exists). Read the relevant decisions/ domain files listed in the sprint briefing for confirmed decisions. Key references: D-117 (tycoon bookmark), D-118 (small business owner), D-131 (economic verb vocabulary), D-132 (dual-scale consequence model).
+8
View File
@@ -2,6 +2,14 @@
```
client/ # Godot 4 client
ui/
implant/ # Implant UI component library (D-169): ImplantPanel, ImplantHeader,
# ImplantSeparator, ImplantDataRow, ImplantTextBlock, default_implant.tres
scripts/
autoloads/
hud_groups.gd # HUD z-index layer manager (D-170): GAMEPLAY/INSERT/FULLSCREEN/MODAL modes
rendering/
gameplay_renderer.gd # Base class for occludable renderers; connects to HudGroups signal
server/ # Rust/bevy_ecs simulation server
tooling/ # Build tools, scripts, asset pipelines
tests/ # Integration and end-to-end tests
+4 -2
View File
@@ -1,7 +1,8 @@
{
"autoMemoryDirectory": "/home/jeroenschweitzer/Projects/settled-reach/.memory",
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1",
"SR_DB_PATH": "/var/home/jeroenschweitzer/Projects/settled-reach/settledreach.db"
},
"teammateMode": "in-process",
"permissions": {
@@ -63,9 +64,10 @@
"Bash(list *)",
"Bash(tree *)",
"Bash(sed -n *)",
"Bash(.claude/skills/sprint-start/scripts/start-sprint.sh *)",
"Bash(.claude/skills/sprint-start/scripts/sprint-teardown.sh *)",
"Skill(git-commit)",
"Skill(worktree-update)",
"Skill(sprint-start)",
"Skill(sprint-plan)",
"Skill(pr-push)",
+29 -1
View File
@@ -34,7 +34,35 @@ git branch --show-current
If on `main`, stop: "You're on main. Switch to a team branch first."
### 1b. Runtime smoke test (MANDATORY)
### 1b. Zero warnings policy (MANDATORY)
Before pushing, verify the branch has **zero lint warnings**. Any warning
must be either fixed or suppressed with a commented justification.
**For client/visual branches:**
```bash
gdlint client/scripts/ client/ui/ 2>&1
```
If warnings remain, fix them before pushing. For warnings that cannot be
fixed (e.g. intentional long lines in data literals), add a `# gdlint:
ignore` comment with a reason.
**For server branches:**
```bash
cargo clippy -- -D warnings 2>&1
```
**For CI/tooling branches:**
```bash
ruff check tooling/ 2>&1
```
The goal is zero warnings in the pre-push output. Advisory warnings that
the pre-push hook reports as "(advisory, not blocking)" should still be
zero — they are advisory only because we haven't enforced them yet.
### 1c. Runtime smoke test (MANDATORY)
Before pushing, verify the game actually runs. This is non-negotiable —
Sprint 28 proved that code review without runtime testing misses critical
+58 -40
View File
@@ -16,16 +16,15 @@ on the branch type. All reviewers must approve for a clean review.
## Workflow
### 0. Branch guard — MUST be run by a Claude instance in the `main` worktree
### 0. Branch guard — MUST be run from the `main` branch
```bash
git branch --show-current
```
If the current branch is **not `main`**, stop immediately and tell the user:
"PR reviews must be run by a Claude instance in the `main` worktree."
Do NOT proceed with the review. Do NOT work around this by reading files
from another worktree — the review agent itself must be running in main.
"PR reviews must be run from the `main` branch."
Do NOT proceed with the review.
Stop and wait for the user to invoke `/pr-review` from main.
### 0b. Verify runtime smoke test was performed
@@ -48,6 +47,19 @@ godot --headless --path client --quit 2>&1 | grep -i "SCRIPT ERROR"
If script errors appear in the branch diff files, flag them immediately
before spawning reviewers — no point reviewing code that doesn't parse.
### 0c. Zero warnings check
The project enforces a **zero warnings policy**. Before spawning reviewers,
check if the branch introduces lint warnings:
- **client/visual:** `gdlint client/scripts/ client/ui/` should report 0 issues
- **server:** `cargo clippy -- -D warnings` should be clean
- **ci/tooling:** `ruff check tooling/` should be clean
If warnings exist, note the count in the review output. Reviewers should
flag any **new** warnings introduced by the branch as `warning` severity.
Pre-existing warnings are not PR blockers but should be tracked for cleanup.
### 1. Determine the branch to review
If the user provided a branch name as argument, use it. Otherwise list open
@@ -99,39 +111,24 @@ Three-dot diff with pathspec exclusions is unreliable. Instead, either:
For large diffs (>1000 lines of source), provide **source files** rather than
raw diff to reviewers — cleaner context, better reviews.
**IMPORTANT — use team directory paths for ALL agents.** Each team branch
is checked out in its own directory at:
**Reviewer agents read source files via `git show`.** Sprint branches
use the naming pattern `sprint-{N}/{team}`. To read a file from the
branch being reviewed:
```
/var/mnt/data/projects/settled-reach/<branch>/
```bash
git show origin/<branch>:<path>
```
For example, the `copy` team directory is at:
```
/var/mnt/data/projects/settled-reach/copy/content/dialogue/...
For example:
```bash
git show origin/sprint-31/server:server/src/bin/atlas.rs
```
**All reviewer agents** (regardless of Bash access) should read source files
from the team directory using the Read tool. This is more reliable than
`git show origin/<branch>:<path>` because:
- All agents have Read access (no Bash dependency)
- Files are always the actual branch checkout (no stale cache)
- No risk of accidentally reading from main's working directory
If the sprint branch has an active worktree (under `.sprint/`), reviewers
can also use the Read tool with the worktree path. But `git show` is
the reliable default — it works whether or not a worktree exists.
When constructing reviewer prompts, tell agents to read files from the
team directory. Example instruction for agents:
```
Read the changed files from the team directory. The branch is checked
out at: /var/mnt/data/projects/settled-reach/<branch>/
For example, to read `content/dialogue/the-terminal/kael-davan.yaml`,
use: /var/mnt/data/projects/settled-reach/<branch>/content/dialogue/the-terminal/kael-davan.yaml
```
Also tell agents to read relevant `decisions/*.md` files from the same
directory (they're identical to main, but using the team directory path
keeps agents grounded in the correct location).
Also tell agents to read relevant `decisions/*.md` files for context.
### 4. Spawn reviewers in parallel
@@ -154,9 +151,9 @@ reviewer that was spawned (2 for code/visual/audio, 3 for copy):
### <Reviewer Name> (<Focus>): [APPROVE | REQUEST_CHANGES]
[Summary]
| # | File | Severity | Issue |
|---|------|----------|-------|
| 1 | path:line | critical/warning/suggestion | description |
| # | File | Issue |
|---|------|-------|
| 1 | path:line | description |
### <Reviewer Name> (<Focus>): [APPROVE | REQUEST_CHANGES]
...
@@ -190,13 +187,18 @@ Respond with:
2. Summary: 2-3 sentence overall assessment
3. Comments: List of specific issues, each with:
- File path and approximate location
- Severity: critical / warning / suggestion
- Description of the issue
Verdict rules:
- Any **critical** or **warning** issue → REQUEST_CHANGES
- Only **suggestion**-level issues (or none) → APPROVE
If no issues found, say APPROVE with a brief positive summary.
- **Any comment at all → REQUEST_CHANGES.** Every issue is actionable.
There is no "suggestion" tier that gets skipped. If it's worth
mentioning, it's worth fixing before merge.
- If no issues found, say APPROVE with a brief positive summary.
- Do NOT flag something unless you expect it to be addressed. If you
wouldn't fix it yourself, don't mention it.
- **Quality and polish is the golden standard.** We are not optimizing
for speed — we are optimizing for a product we're proud of. If
something can be better, say so.
```
## 6. Posting results to Gitea
@@ -239,8 +241,24 @@ review outcome:
**CHANGES_REQUESTED:**
The sprint-start lifecycle (step 9c) handles dispatching review
comments to agents. After presenting results, remind the lead:
"Review requested changes. Create tasks from the warnings/critical
issues and dispatch to idle agents, then re-push and re-review."
"Review requested changes. Create tasks from each issue and dispatch
to idle agents, then re-push and re-review."
The team may **push back** on specific comments. When a team agent
disagrees with a reviewer comment, the process is:
1. The team agent explains why the comment should be retracted — with
a concrete technical rationale, not just "I disagree."
2. The team lead (you) evaluates the pushback. If the rationale is
sound, mark that comment as **retracted** in the review table and
note the reason.
3. If the team lead is unsure, escalate to the user for a ruling.
4. Retracted comments do NOT need to be fixed. The re-review should
note which comments were retracted and why.
This prevents reviews from becoming dogma while maintaining the rule
that every comment is taken seriously. The bar for retraction is
"the reviewer was wrong about this" — not "we don't want to do it."
**APPROVED:**
The sprint-start lifecycle (step 9c) handles shutdown. After
@@ -2,17 +2,12 @@
Use `model: sonnet` for all reviewers — sufficient for review, saves cost.
**All reviewer agents read from team directories.** Each team branch is
checked out in its own directory at:
`/var/mnt/data/projects/settled-reach/<branch>/`
Tell every reviewer agent to read source files from the team directory
using the Read tool. Include the directory path and a list of changed
files in every prompt. Do NOT rely on `git show` or paste file contents —
agents can read directly from the directory.
Note: cross-directory reading is only permitted for review agents spawned
from the `main` team. Team agents must stay within their own directory.
**Reviewer agents read source files via `git show` or from sprint
worktrees.** Sprint branches use `sprint-{N}/{team}` naming. Include
the branch name and a list of changed files in every prompt. The
default approach is `git show origin/<branch>:<path>`. If an active
worktree exists under `.sprint/`, agents can also use the Read tool
with the worktree path.
## Code reviews (`server`, `client`, `ci`)
+3 -6
View File
@@ -154,12 +154,9 @@ Create `docs/sprints/sprint-N/` and write one file per team.
Read the template at `references/briefing-template.md` in this skill directory
for the exact file structure.
**IMPORTANT — relative paths only:** Each team works in its own directory
containing the full repo (`server/`, `client/`, `docs/`, etc.). All file
paths in briefings must be relative to the working directory. Example:
`server/src/bridge/types.rs`, not `/absolute/path/to/server/src/...` or
paths that navigate outside (`../sibling-dir/...`).
Agents must stay within their team's working directory.
**Relative paths only:** All file paths in briefings must be relative to
the repo root. Example: `server/src/bridge/types.rs`, not absolute paths.
Each sprint branch (`sprint-{N}/{team}`) contains the full repo.
Key requirements per file:
- **server.md**: Carry-overs, new tickets, dependency chain, key decisions, notes
@@ -9,7 +9,7 @@ Each team gets one briefing file at `docs/sprints/sprint-N/<team>.md`.
**Goal:** <One-sentence sprint goal, shared across all teams>
**Branch:** `<team>`
**Branch:** `sprint-{N}/<team>`
**Agents:** <Agent names and roles>
## Carry-over from Sprint N-1
@@ -57,7 +57,7 @@ One bullet per ticket with:
When ready to submit, create a PR with `tea` CLI. **All flags are required** to avoid TTY prompts (see CLAUDE.md "Gitea access" section):
\```bash
tea pr create --repo jpmschweitzer/settled-reach --login schweitz --title "feat(<scope>): description" --description "body" --base main --head <branch>
tea pr create --repo jpmschweitzer/settled-reach --login schweitz --title "feat(<scope>): description" --description "body" --base main --head sprint-{N}/<team>
\```
```
@@ -73,7 +73,8 @@ The `joint.md` file additionally includes:
| Team | Branch | Agents | Scope |
|------|--------|--------|-------|
| server | `server` | Dudley (simulation), Oscar (networking) | Rust/bevy_ecs simulation |
| client | `client` | Stig (UI), Oscar (networking) | Godot client rendering |
| server | `sprint-{N}/server` | Dudley (simulation), Oscar (networking) | server/, Rust/bevy_ecs simulation |
| client | `sprint-{N}/client` | Stig (UI), Oscar (networking) | client/, Godot rendering |
| copy | `sprint-{N}/copy` | Mellanie, Paula, Miri | wiki/, docs/atlas/, content/ |
| joint | both | All implementation agents | Integration, proofs, cross-team schema |
| content | (none) | Mellanie, Paula, Miri, Araminta | Content authoring, no code branch |
+50 -17
View File
@@ -25,8 +25,8 @@ The current branch IS the team. Read it with:
git branch --show-current
```
Valid team branches: `server`, `client`, `copy`, `audio`, `visual`, `ci`,
`planning`.
Sprint branches follow the pattern `sprint-{N}/{team}` (e.g. `sprint-31/server`).
Valid team names: `server`, `client`, `copy`, `audio`, `visual`, `ci`, `planning`.
If on `main`, follow the **Main branch workflow** below instead of
the team branch workflow (steps 28).
@@ -130,6 +130,18 @@ If the user raises items that should be tracked, create Q-NNN entries
or backlog tickets on the spot. If process changes are agreed, update
the relevant skill files or CLAUDE.md immediately — don't defer them.
#### A1c. Clean up sprint worktrees
Remove ephemeral worktrees for the closed sprint. Run the teardown script:
```bash
.claude/skills/sprint-start/scripts/sprint-teardown.sh {N}
```
This removes all worktrees under `.sprint/sprint-{N}/` and prunes git
metadata. Safe to skip if the sprint didn't use ephemeral worktrees
(e.g. legacy persistent worktree setup).
#### A2. Bump the version
The project version scheme is `v0.1.{sprint_number}`. After closing
@@ -197,10 +209,20 @@ If everything looks ready, activate the sprint:
tooling/db/sprint start
```
Then report:
Then open team terminal tabs automatically:
```bash
.claude/skills/sprint-start/scripts/start-sprint.sh
```
This creates ephemeral worktrees under `.sprint/sprint-{N}/{team}/` for
each team with open tickets, and opens Ptyxis windows with tmux + Claude
auto-starting in each tab. The user will have one tab per active team.
Report:
- Sprint activated (name, ticket count per team)
- Remind the user to switch to a team branch and run `/sprint-start`
there (or `cd` into the relevant worktree)
- Worktrees created and tabs opened
- Each team tab runs `/sprint-start` to load briefing and spawn agents
---
@@ -215,6 +237,9 @@ to plan the next sprint.
### 2. Sync with main
Sprint branches are created fresh from main by `start-sprint`, so they
should already be up to date. If main has moved since branch creation:
```bash
git fetch --all
git merge origin/main --no-edit
@@ -329,14 +354,14 @@ Task(
team_name: "sprint-{N}-{team}",
name: "{name_lowercase}",
prompt: "You are on the {team} team for Sprint {N}.
Branch: `{team}`
Branch: `sprint-{N}/{team}`
RULES (NON-NEGOTIABLE):
0. TEAM BOUNDARY: Your team is `{team}` ($WORKTREE_TEAM). Stay
within the current working directory. Do NOT navigate to
parent or sibling directories. Do NOT follow .git pointers
to other directories.
0. TEAM SCOPE: Your team is `{team}` on branch `sprint-{N}/{team}`.
Stay within your team's file scope (server → server/, client → client/, copy → wiki/ + docs/atlas/ + content/).
You may read (but not modify): docs/, decisions/, wiki/, .claude/
Do NOT modify files belonging to other teams.
1. GIT: Do NOT run any git commands (commit, push, pull, merge,
checkout, branch, stash, tag, etc.). All git operations are
@@ -487,30 +512,38 @@ When all tasks are complete (TaskList shows all completed):
Run `/git-commit` to commit all changes, then `/pr-push` to create or
update the PR. Do NOT shut down agents — the team stays alive for review.
#### 9b. Review
#### 9b. Wait for review
Run `/pr-review` to spawn temporary reviewers. Wait for results.
Do NOT run `/pr-review` from the team window — PR reviews run from
the `main` branch (a separate window/session). The team window stays
on its sprint branch.
After pushing and creating the PR, report the PR number to the user
and stop. Wait for review feedback to arrive (the user or the main
session will relay it, or it will appear as Gitea PR comments).
#### 9c. Handle review outcome
When review feedback arrives (from the user, main session, or PR
comments):
**If CHANGES_REQUESTED:**
1. Parse the review comment table (from the Gitea PR comment or the
review output). Extract each warning/critical issue with:
review output). Extract each issue with:
- File path and approximate line
- Severity (critical / warning / suggestion)
- Description
2. Create a task per warning/critical issue:
2. Create a task per issue:
```
TaskCreate(
subject: "Review: {short description}",
description: "{full issue description from review table, including
file path, severity, and reviewer name}",
file path and reviewer name}",
activeForm: "Fixing review comment: {short description}"
)
```
Skip suggestion-severity items unless they are trivial (1-line fixes).
Every comment is actionable — there is no "suggestion" tier to skip (per pr-review policy).
3. Dispatch to idle agents: send each a message via SendMessage telling
them to check TaskList for new review-fix tasks. Agents claim and
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
# Clean up ephemeral worktrees for a closed sprint.
# Usage: sprint-teardown.sh <sprint-number>
#
# Removes all worktrees under .sprint/sprint-{N}/ and prunes git metadata.
# Safe to run multiple times — skips already-removed worktrees.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
SPRINT_BASE="$(dirname "$REPO_ROOT")/.sprint"
SPRINT=${1:?Usage: sprint-teardown.sh <sprint-number>}
SPRINT_DIR="$SPRINT_BASE/sprint-${SPRINT}"
if [ ! -d "$SPRINT_DIR" ]; then
echo "No worktrees found for sprint-${SPRINT} (directory $SPRINT_DIR does not exist)."
exit 0
fi
echo "Cleaning sprint-${SPRINT} worktrees..."
for wt in "$SPRINT_DIR"/*/; do
[ -d "$wt" ] || continue
team="$(basename "$wt")"
echo " Removing: $team"
git -C "$REPO_ROOT" worktree remove "$wt" --force 2>/dev/null || echo " (already removed or dirty)"
done
rmdir "$SPRINT_DIR" 2>/dev/null || true
git -C "$REPO_ROOT" worktree prune
echo "Done. Sprint-${SPRINT} worktrees cleaned."
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# Opens Ptyxis tabs for the active sprint teams in the CURRENT window.
# Auto-starts Claude Code in each tab via tmux.
#
# Usage: start-sprint.sh [sprint-number]
# If omitted, auto-detects the active sprint from the database.
#
# Assumes the caller is already on main in the current terminal.
# Adds one tab per active team — no duplicate main tab.
#
# Worktrees are created under .sprint/ (ephemeral, cleaned after sprint close).
# Can be called from any directory — resolves paths from the script location.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Script lives at .claude/skills/sprint-start/scripts/ — repo root is 4 levels up
REPO_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
# Parent of repo root is where .sprint/ and the DB live
PARENT="$(dirname "$REPO_ROOT")"
# Resolve sprint number — argument or active sprint from DB
if [ -n "${1:-}" ]; then
SPRINT="$1"
else
SPRINT=$(cd "$REPO_ROOT" && tooling/db/sqlite-query "SELECT id FROM sprints WHERE status='active'" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['rows'][0]['id'])" 2>/dev/null || true)
if [ -z "$SPRINT" ]; then
echo "error: no active sprint found. Pass a sprint number or activate a sprint first." >&2
exit 1
fi
fi
# Query teams with open tickets
TEAMS=$(cd "$REPO_ROOT" && tooling/db/sqlite-query "SELECT DISTINCT team FROM tickets WHERE sprint_id=$SPRINT AND status NOT IN ('done','cancelled') AND team IS NOT NULL" 2>/dev/null | python3 -c "import sys,json; [print(r['team']) for r in json.load(sys.stdin)['rows'] if r['team']]" 2>/dev/null || true)
if [ -z "$TEAMS" ]; then
echo "Sprint $SPRINT has no open tickets. Opening main only."
fi
echo "Sprint $SPRINT — teams: ${TEAMS:-none}"
# ── Open team tabs in the CURRENT window ────────────────────────────
# No separate main tab — the caller is already on main.
# All team tabs open as --tab in the active Ptyxis window.
for team in $TEAMS; do
BRANCH="sprint-${SPRINT}/${team}"
WDIR="$PARENT/.sprint/sprint-${SPRINT}/${team}"
# Create worktree if it doesn't exist
if [ ! -d "$WDIR" ]; then
echo "Creating worktree: $WDIR (branch: $BRANCH)"
mkdir -p "$(dirname "$WDIR")"
# Create branch from main if it doesn't exist remotely
if git -C "$REPO_ROOT" rev-parse --verify "origin/$BRANCH" >/dev/null 2>&1; then
git -C "$REPO_ROOT" worktree add "$WDIR" "$BRANCH"
else
git -C "$REPO_ROOT" worktree add -b "$BRANCH" "$WDIR" HEAD
fi
fi
ptyxis --tab -d "$WDIR" -x 'tmux new-session \; send-keys "claude /sprint-start" Enter'
sleep 0.3
done
echo "Session ready. Main + ${TEAMS:-(no teams)}"
-125
View File
@@ -1,125 +0,0 @@
---
name: worktree-update
description: >
Sync worktree branches with main. Use when the user says "update worktrees",
"sync branches", "merge main", "worktree update", or invokes /worktree-update.
When on main: shows which worktree branches are ahead and lets the user pick
which to merge into main (flags branches with open PRs). When on a non-main
branch: merges main into the current branch. All operations are non-destructive.
user-invocable: true
allowed-tools: Bash, Read, AskUserQuestion
---
# Worktree Update Skill
Sync worktree branches safely. Direction depends on the current branch.
## Safety Rules (NON-NEGOTIABLE)
- **Never force-push, reset --hard, rebase, or delete branches.**
- **Never use `--no-verify` or skip hooks.**
- **Always use `--no-edit` on merges** to avoid interactive editor prompts.
- **Stop on merge conflicts** — report them and let the user decide. Never
auto-resolve or abort a conflicted merge without asking.
- **Fetch before comparing** — always `git fetch --all` first so commit
comparisons are accurate.
- **Dry-run first on main** — show the user exactly what will happen before
merging anything into main.
## Workflow
### 1. Detect current branch
```bash
git branch --show-current
```
Branch determines the mode: `main` → outbound sync, anything else → inbound sync.
### 2a. On `main` — merge worktree branches into main
#### Fetch and compare
```bash
git fetch --all
```
Discover all worktree branches (excluding `main` itself):
```bash
git worktree list | grep -v '\[main\]' | sed 's/.*\[//;s/\]//'
```
For each worktree branch, check if it has commits ahead of main:
```bash
git rev-list --count main..origin/<branch>
```
Skip branches with 0 commits ahead. For branches that ARE ahead, collect:
- Branch name
- Number of commits ahead
- One-line log of those commits: `git log --oneline main..<branch>`
#### Check for open PRs
```bash
tea pr list --login schweitz --repo jpmschweitzer/settled-reach --state open --output simple
```
Cross-reference open PR head branches with the ahead-of-main branches.
#### Present results
Show a summary table of branches ahead of main. For each branch, indicate:
- `[PR]` if it has an open pull request — warn that it should go through
normal review channels (use `/pr-review` instead)
- Commit count and summary
Use `AskUserQuestion` to let the user pick which branches to merge.
Exclude PR-flagged branches from the default options (but allow the user to
override via "Other").
#### Merge selected branches
For each selected branch, one at a time:
```bash
git merge <branch> --no-edit
```
If a merge conflicts, **stop immediately**. Report the conflict and do NOT
continue to the next branch. The user must resolve before proceeding.
After all merges, show the final state with `git log --oneline -N` (where N
covers the new commits).
#### Backup the shared database
After successful merges on main, snapshot the database for git tracking:
```bash
make db-backup
```
This copies the shared `settledreach.db` (in the parent directory) to
`docs/backups/settledreach.db.backup`. Stage and commit it with the merge
if the file changed.
### 2b. Not on `main` — merge main into current branch
```bash
git fetch --all
git merge origin/main --no-edit
```
If clean, report the result (fast-forward or merge commit, files changed).
If conflicts, report them and stop.
### 3. Push
After a successful merge, push the branch:
```bash
git push origin <current-branch>
```
+41
View File
@@ -14,10 +14,12 @@ REMOTE_REF="origin/$BRANCH"
if git rev-parse --verify "$REMOTE_REF" >/dev/null 2>&1; then
CLIENT_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- client/ 2>/dev/null | wc -l)
SERVER_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- server/ 2>/dev/null | wc -l)
TOOLING_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- tooling/ pyproject.toml 2>/dev/null | wc -l)
else
# New branch or no remote ref — fall through to directory checks
CLIENT_CHANGED=1
SERVER_CHANGED=1
TOOLING_CHANGED=1
fi
# --- GDScript parse check (headless Godot) ---
@@ -97,6 +99,45 @@ else
echo "pre-push: WARNING — cargo not found or server/ missing, skipping Rust lint"
fi
# --- Python lint (ruff) ---
if [ "$TOOLING_CHANGED" -eq 0 ]; then
echo "pre-push: no tooling/ changes — skipping Python lint"
elif command -v ruff >/dev/null 2>&1 && [ -d "$REPO_ROOT/tooling" ]; then
echo "pre-push: checking Python (ruff)..."
if ! (cd "$REPO_ROOT" && ruff check tooling/ 2>&1); then
ERRORS=$((ERRORS + 1))
else
echo "pre-push: ruff — OK"
fi
else
echo "pre-push: skipping Python lint (ruff not found — install with: pip install 'ruff>=0.9')"
fi
# --- JSON syntax validation ---
if git rev-parse --verify "$REMOTE_REF" >/dev/null 2>&1; then
JSON_FILES=$(git diff --name-only "$REMOTE_REF"..HEAD -- '*.json' 2>/dev/null || true)
else
JSON_FILES=$(git ls-files '*.json')
fi
if [ -n "$JSON_FILES" ]; then
echo "pre-push: checking JSON syntax..."
JSON_FAIL=0
while IFS= read -r f; do
if [ -f "$REPO_ROOT/$f" ] && ! python3 -m json.tool "$REPO_ROOT/$f" >/dev/null 2>&1; then
echo " FAIL: $f"
JSON_FAIL=$((JSON_FAIL + 1))
fi
done <<< "$JSON_FILES"
if [ "$JSON_FAIL" -gt 0 ]; then
echo "pre-push: FAIL — $JSON_FAIL JSON file(s) have syntax errors"
ERRORS=$((ERRORS + 1))
else
echo "pre-push: JSON — OK ($(echo "$JSON_FILES" | wc -l) file(s))"
fi
else
echo "pre-push: no JSON changes — skipping"
fi
if [ "$ERRORS" -gt 0 ]; then
echo ""
echo "pre-push: $ERRORS check(s) failed. Push aborted."
+48
View File
@@ -0,0 +1,48 @@
class-definitions-order:
- tools
- classnames
- extends
- docstrings
- signals
- enums
- consts
- staticvars
- exports
- pubvars
- prvvars
- onreadypubvars
- onreadyprvvars
- others
class-load-variable-name: (([A-Z][a-z0-9]*)+|_?[a-z][a-z0-9]*(_[a-z0-9]+)*)
class-name: ([A-Z][a-z0-9]*)+
class-variable-name: _?[a-z][a-z0-9]*(_[a-z0-9]+)*
comparison-with-itself: null
constant-name: _?[A-Z][A-Z0-9]*(_[A-Z0-9]+)*
disable: []
duplicated-load: null
enum-element-name: '[A-Z][A-Z0-9]*(_[A-Z0-9]+)*'
enum-name: ([A-Z][a-z0-9]*)+
excluded_directories: !!set
.git: null
addons: null
expression-not-assigned: null
function-argument-name: _?[a-z][a-z0-9]*(_[a-z0-9]+)*
function-arguments-number: 10
function-name: (_on_([A-Z][a-z0-9]*)+(_[a-z0-9]+)*|_?[a-z][a-z0-9]*(_[a-z0-9]+)*)
function-preload-variable-name: ([A-Z][a-z0-9]*)+
function-variable-name: '[a-z][a-z0-9]*(_[a-z0-9]+)*'
load-constant-name: (([A-Z][a-z0-9]*)+|_?[A-Z][A-Z0-9]*(_[A-Z0-9]+)*)
loop-variable-name: _?[a-z][a-z0-9]*(_[a-z0-9]+)*
max-file-lines: 1000
max-line-length: 120
max-public-methods: 200
max-returns: 6
mixed-tabs-and-spaces: null
no-elif-return: null
no-else-return: null
signal-name: '[a-z][a-z0-9]*(_[a-z0-9]+)*'
sub-class-name: _?([A-Z][a-z0-9]*)+
tab-characters: 1
trailing-whitespace: null
unnecessary-pass: null
unused-argument: null
+12
View File
@@ -3,6 +3,8 @@
# Runtime databases (not tracked — created on startup)
server/settings.db
server/settings.db-shm
server/settings.db-wal
# Build and cache
.cache/
@@ -32,6 +34,15 @@ renderer/output/*.png
spikes/**/.godot/
spikes/**/*.import
spikes/**/*.uid
spikes/**/*.npy
spikes/**/*.npz
# Planet generator intermediates
tooling/planet-gen/__pycache__/
*.tmp.npz
# Generated terrain grids (large, regenerated from pipeline)
wiki/**/bodies/**/terrain.npz
# Asset downloads (vendor archives, not game content)
docs/assets/downloads/
@@ -57,6 +68,7 @@ Thumbs.db
# IDE
.idea/
.vscode/
.obsidian/
*.swp
*.swo
+73
View File
@@ -6,6 +6,79 @@ Format based on [Keep a Changelog](https://keepachangelog.com/).
## [Unreleased]
### Added
- Planet generator pipeline (`tooling/planet-gen/`) — procedural terrain simulation, Whittaker biome classification, equirectangular heightmap + 512px globe rendering from wiki data
- Externalized biome/color configuration (`tooling/planet-gen/biomes.toml`) — single source for all classification tables, palettes, and rendering parameters
- Batch runner with error handling, resume support, determinism verification, and 50% error rate circuit breaker
- Per-body wiki pages with YAML frontmatter (`wiki/star-systems/*/bodies/*/index.md`) — body definition + profile + visual embeds
- Body scaffolding tool reads system index.md and generates per-body index.md with frontmatter
- Ran system (GJ-144) generated: 10 bodies with heightmaps, globe renders, and geographic markers
- Implant HUD icon set: 13 SVGs (stance, status, interaction, inventory) per D-086
- 7 procedural planet type renders for wiki/GTTR (`client/assets/planets/`)
- Ticket #817: batch planet generation for all ~3000 bodies
- Ticket #816: remove stale Qdrant semantic search infrastructure
- `PROJECT_STATE.md` at repo root — shared project state referenced by all 18 agent briefings
- Economics decision domain (`decisions/economics.md`): D-171D-187 covering currency system, commodity taxonomy, shadow economy, corporation tiers, productivity seeding, simulation architecture, data pipeline, gate transmission levels
- Commodity catalog: 36 commodity types in `wiki/economics/commodities.toml` with 21 production chains in `wiki/economics/production_chains.toml`
- Wiki stub pages for all 36 commodities at `wiki/economics/commodities/`
- SQL schema spec for #804 systems.db extension (`wiki/economics/schema.md`)
- Burnelli-Sheldon economist agent (`.claude/agents/burnelli-sheldon.md`)
- Workshop archives: #796 (economics design, 3 rounds) and #801 (commodity catalog, 3 rounds + validation)
### Fixed
- Sprint worktree creation no longer spawns a spurious "None" team tab when tickets have no team assigned
### Changed
- Pre-push hook now validates JSON syntax on changed files (python3 -m json.tool)
- HUD status panel: merged TimeDisplay into ImplantPanel — time, health, perception in one themed panel (#786)
- HUD moved from UILayer (20) to InsertOverlay (10) for bloom treatment per D-049
- Interaction prompt: converted from PanelContainer+StyleBoxFlat to ImplantPanel+ImplantDataRow (#788)
- Minimap: added ImplantTheme-styled container frame behind circular display (#787)
- Stance indicator: SVG icons with alpha-mask tint shader replace text-only labels (#787, D-086)
- Amended 7 stale D-records with supersession notes (D-012, D-035, D-044, D-061, D-086, D-090, D-119)
- Closed 4 resolved scope questions (Q-002, Q-004, Q-005, Q-007)
- Fixed questions.md index (was 61 questions, actually 96 — 33 architecture Qs missing from index)
- All 18 briefings reference `PROJECT_STATE.md` instead of duplicating project state boilerplate
- Aligned sprint-start severity policy with pr-review (no suggestion tier — every comment actionable)
### Removed
- `GEMINI-SCAN.md` one-off scan artifact
- 6 dead `db/connectors/` permission entries from settings.local.json
- Stale "v0.2 direction" and "Sprint 25 critical path" references from all briefings
- `worktree-update` skill template from whatsinagame kit
### Fixed
- HUD layout overlaps: DebugOverlay positioned below merged status panel, GauntletHUD moved below StanceIndicator, StanceIndicator sized for ImplantPanel content (#792)
- D-061 dialogue max-width: corrected from 640px to 1200px (per D-076)
- DEVOPS.md and stig briefing: gdlint no longer "pending setup"
- `{team_scope_dirs}` dangling placeholder in sprint-start resolved
## [v0.1.31] — 2026-04-05
### Added
- Star map click-through popup with GTTR excerpt, system profile, and adjacent systems (#780)
- Edge-only-on-selected visibility rule for star map — default shows no edges, selected system shows adjacents only (#780)
- Cultural diversity sweep — 10 systems enriched, Afrikaans/Dutch subversions, D-168 Iserlohn IP evaluation (#766, #773)
- Per-body GTTR entries for 25 moons and stations at hub systems (#782)
- Shared Python module `tooling/db/common.py` — centralizes DB path resolution, config loading, and WAL-mode connection setup (#777)
- `ensure_venv()` auto-activation for Python tooling scripts with third-party dependencies (#777)
- `make lint-python` target running ruff on `tooling/` (#777)
- Python/ruff lint block in pre-push hook (#777)
- Zero-warnings policy in pr-push and pr-review skills; `.gdlintrc` with max-line-length 120
### Changed
- Decomposed main.gd (28KB → 13.4KB) into SnapshotConsumers, DialogueCoordinator, SnapshotHandler (#775)
- Split monolithic `atlas.rs` (2119 lines) into 8 focused modules under `src/bin/atlas/` (#776)
- Replaced persistent team worktrees with ephemeral sprint branches (`sprint-{N}/{team}`)
- `start-sprint.sh` integrated into sprint-start skill — auto-creates worktrees and opens Ptyxis tabs
### Fixed
- All 354 gdlint warnings resolved — zero warnings across all linters (#783)
- Nova Estrada and Entremeio wiki entries enriched to batch standard (#774)
- Auto-unassign done tickets on sprint close (`tooling/db/sprint stop`)
- Pre-existing `NameError` in `decisions_sync.py` resolved via shared module extraction (#777)
- Unused imports removed from `assign-astro-ids.py`, `generate-star-map.py`, `test_quaternius_raw.py` (#777)
## [v0.1.30] — 2026-04-05
### Added
+20 -9
View File
@@ -44,18 +44,17 @@ Development follows a strict cascade. Each phase has a concrete deliverable. **D
### Team boundaries
**Your team identity is `$WORKTREE_TEAM`.** All work must stay within the current working directory.
**Your team is determined by your sprint branch** (e.g. `sprint-31/server` → server team).
- All file paths are relative to the current working directory (e.g. `server/src/bridge/types.rs`).
- **Do NOT navigate to parent or sibling directories** (`../`, `../client/`, etc.) unless explicitly instructed. Do NOT use absolute paths to reach other team directories.
- **Do NOT write auto-memory files for other teams.** If `$WORKTREE_TEAM` is `server`, do not write to memory paths containing `client`, `main`, etc.
- For context: each team has its own directory via git worktrees, sharing a parent directory (`settled-reach/`). The `.git` file points to a shared git directory — do not follow it to determine your working root.
- **Exception — stale git lock files:** If a `git` command fails with `index.lock: File exists`, you may remove the lock file for **your own team only** (e.g. `main/.git/worktrees/$WORKTREE_TEAM/index.lock`). Never touch lock files belonging to other teams.
- **Never chain git commands** in a single Bash call (e.g. `git add ... && git commit ...`). The shared `.git` directory means concurrent index access from the same terminal creates `index.lock` collisions. Always run `git add` and `git commit` as **separate sequential Bash calls**.
- All file paths are relative to the repo root (e.g. `server/src/bridge/types.rs`).
- **Stay within your team's scope.** Server team modifies `server/`. Client team modifies `client/`. Copy team modifies `wiki/`, `docs/atlas/`, `content/`. Shared directories (`docs/`, `decisions/`) are readable by all teams.
- **Do NOT modify files outside your team scope** unless the ticket explicitly requires it.
- **Never chain git commands** in a single Bash call (e.g. `git add ... && git commit ...`). Always run `git add` and `git commit` as **separate sequential Bash calls**.
- **Stale git lock files:** If a `git` command fails with `index.lock: File exists`, you may remove the lock file at `.git/index.lock` (or `.git/worktrees/<name>/index.lock` if in a worktree).
### Database
The ticketing database (`settledreach.db`) lives in the **parent directory** shared across all worktrees — it is not tracked in git. A backup is committed to `docs/backups/settledreach.db.backup` via main only.
The ticketing database (`settledreach.db`) is accessed via `SR_DB_PATH` env var (set in `.claude/settings.json`). A backup is committed to `docs/backups/settledreach.db.backup` via main only.
### Before starting work
1. Read your sprint briefing at `docs/sprints/sprint-N/{team}.md` for current tasks
@@ -84,6 +83,18 @@ The ticketing database (`settledreach.db`) lives in the **parent directory** sha
- Three test tiers: (1) Live server — highest fidelity, (2) MessagePack replay via `Protocol.decode_snapshot()` — for unreachable rooms, (3) TestHarness mock — for UI-only tests where fog data doesn't matter.
- `make fixtures-gauntlet` regenerates real server snapshot fixtures from the Gauntlet world.
### Implant UI component library (D-169, D-170)
The implant UI system — all diegetic neural overlay panels — lives at `client/ui/implant/`. Components are Godot Control scenes styled via a shared `Theme` resource (`default_implant.tres`). Do not hand-roll implant panel layouts; compose from the library.
**Components:** `ImplantPanel` (root container), `ImplantHeader` (title + subtitle), `ImplantSeparator` (horizontal rule), `ImplantDataRow` (key/value row, optional color), `ImplantTextBlock` (RichTextLabel for wrapping text).
**Theme resource:** `client/ui/implant/default_implant.tres` — defines semantic color roles (`PRIMARY_TEXT`, `DIM_TEXT`, `ACCENT_ACTIVE`, `ACCENT_POSITIVE`, `ACCENT_NEGATIVE`, `ACCENT_WARNING`, `SEPARATOR`), spacing, and font sizes. Swap the entire `.tres` to change implant hardware appearance at runtime.
**HUD visibility (D-170):** `client/scripts/autoloads/hud_groups.gd` manages z-index layering. Modes: `GAMEPLAY` (z=0), `INSERT` (z=10), `FULLSCREEN` (z=20), `MODAL` (z=30). App paths are hierarchical: `implant/map`, `implant/wiki/gttr`, etc. Opening any `implant/*` app occludes gameplay; closing returns to gameplay. Key API: `open_app()`, `close_app()`, `toggle_app()`, `is_app_active()`. Emits `gameplay_occluded` signal so renderers can pause.
**GameplayRenderer base class:** `client/scripts/rendering/gameplay_renderer.gd` — extends `Node2D`. Subclasses override `_gameplay_process()` and `_gameplay_draw()`. Connected to `HudGroups.gameplay_occluded` to pause when the implant is fullscreen. Used by `CursorRenderer`, `EntityRenderer`, `FogEntities`, `SoundIndicatorRenderer`, `WorldRenderer`.
### GDScript conventions
**Autoload parse-order rule:** Autoload scripts (`client/scripts/autoloads/`) compile before global `class_name` scripts are registered. Referencing a `class_name` type directly in an autoload causes a parse-time "not declared" error. Pattern:
@@ -97,7 +108,7 @@ The ticketing database (`settledreach.db`) lives in the **parent directory** sha
### File conventions
- Decisions: domain files in `decisions/` (see `decisions/README.md` for index)
- Decision IDs: `D-NNN` (confirmed), `Q-NNN` (open questions), `R-NNN` (rejected)
- **Claim IDs before writing:** `tooling/db/decision claim D <domain> "title"` — prevents ID collisions across worktrees
- **Claim IDs before writing:** `tooling/db/decision claim D <domain> "title"` — prevents ID collisions across parallel branches
- Diagrams: `.d2` source + `.png` renders in `docs/diagrams/{category}/`. Create or update diagrams via `/d2-diagram` when D-records are added or modified.
- Discussion rounds: numbered sequentially, archived to `docs/discussions/` when complete
- Briefings: one per agent, updated after decision-producing rounds
-251
View File
@@ -1,251 +0,0 @@
# Project Review: GEMINI-SCAN
This document outlines a multi-step plan to conduct a comprehensive review of the project, covering its architecture, code quality, and security posture. It will also serve as a living document to record the findings of this review.
## Project Review Plan
### Phase 1: Discovery and Architecture Mapping
1. **Documentation Review:** Start by reading `README.md`, `DECISIONS.md`, and any documents in `docs/architecture/` to understand the project's stated goals, components, and architectural decisions.
2. **Component Identification:** Analyze the directory structure to identify the primary components, including the server, client, database, content pipeline, and tooling.
3. **Technology Stack Enumeration:** Identify the specific technologies, frameworks, and key libraries used in each component.
4. **Architecture Visualization:** Map the high-level architecture, describing how the components interact and the communication protocols between them.
### Phase 2: Code Quality Assessment
1. **Automated Analysis:** Use available static analysis tools for the identified technologies (e.g., `clippy` for Rust, GDScript linters).
2. **Manual Code Review:** Manually review key sections of the codebase to assess readability, maintainability, modularity, error handling, and adherence to idiomatic coding practices.
3. **Testing Strategy Review:** Evaluate the extent and quality of existing unit, integration, and end-to-end tests.
### Phase 3: Security Audit
1. **Dependency Vulnerability Scan:** Check for dependencies with known security vulnerabilities (e.g., `cargo audit`).
2. **Authentication & Authorization Review:** Analyze the implementation of user authentication, session management, and access control.
3. **Input Validation & Sanitization:** Look for potential injection vulnerabilities (e.g., SQL injection, XSS) by reviewing how user and service inputs are handled.
4. **Secrets Management:** Check for insecure storage or exposure of secrets like API keys or database credentials.
5. **Communication Security:** Verify that data is encrypted in transit between components.
### Phase 4: Reporting
1. **Synthesize Findings:** Compile the information from all phases into a structured report within this document.
2. **Provide Recommendations:** Include actionable recommendations for improving architecture, code quality, and security, prioritized by severity and effort.
---
## Review Findings
### Phase 1: Discovery and Architecture Mapping
**Status: Completed**
#### 1. Documentation Review Summary
The project's architecture is extensively documented in `README.md` and the `decisions/` directory, particularly `decisions/architecture.md`.
- **Project:** "The Settled Reach," a top-down, single-player (multiplayer-ready) immersive simulation and detective game.
- **Core Principle:** A strict client-server architecture is mandated (Decision D-010, D-020) to enforce information asymmetry, where the client only knows what the server tells it is perceptible. This is a core gameplay mechanic, not just a technical choice.
- **Key Decision (D-020):** The team explicitly chose a **subprocess/IPC** bridge over a `GDExtension` (in-process) bridge to de-risk development, ensure stability, and enforce architectural separation. The Godot client and Rust server are entirely separate binaries.
#### 2. Component Identification
- **`server/`**: A standalone Rust application that runs the entire game simulation. It is the "server" in the client-server model.
- **`client/`**: A Godot 4 project that acts as a "dumb" client. Its sole responsibilities are rendering, audio playback, and capturing user input. It contains no game logic, as mandated by the architecture.
- **`content/`**: Contains game data, primarily in YAML format.
- **`db/`**: Holds a `schema.sql` file. Its role is not yet clear from the architectural documents, as the primary game state is managed in the ECS. It may be for tooling or an auxiliary system.
- **`tooling/`**: A collection of helper and utility scripts.
#### 3. Technology Stack
- **Server (Rust):**
- **ECS Framework:** `bevy_ecs` (v0.18) is used for the core simulation, confirming Decision D-020. `bevy_app` is used for scheduling.
- **Serialization:** `rmp-serde` (MessagePack) is the primary protocol for client-server communication, as specified in D-020. `serde_yaml` and `ron` are used for content and configuration.
- **Client (Godot):**
- **Engine:** Godot 4.x.
- **Language:** GDScript.
- **Bridge:** A `SimBridge` autoload script is the client-side entry point for communicating with the Rust subprocess.
- **Testing:** `gdUnit4` is configured for unit/integration testing on the client.
#### 4. High-Level Architecture
The architecture is a pure, decoupled client-server model running locally for single-player:
1. **Initiation:** The Godot client launches the Rust server binary as a child process.
2. **Communication:** The client's `SimBridge` connects to the server via a local IPC mechanism (e.g., a local TCP or Unix socket).
3. **Input Loop:** The Godot client captures raw input (e.g., 'W' key press), translates it into a semantic action (e.g., `PlayerAction::MoveNorth`), and sends it to the server.
4. **Simulation Loop:** The Rust server receives the action, processes it within the `bevy_ecs` world, and runs the simulation for one tick (AI, physics, events, etc.).
5. **Perception Loop:** After the tick, the server calculates an `ObserverSnapshot` for the player's character. This snapshot contains *only* the information that character can perceive (e.g., visible entities, audible sounds, known facts). This enforces the game's core mechanic.
6. **Render Loop:** The `ObserverSnapshot` is sent to the Godot client, which uses it to update the visual scene, play sounds, and display UI elements. The client is a pure renderer of the state provided by the server.
This architecture is robust, scalable, and directly implements the game's central design pillars. It is well-suited for both single-player and future multiplayer development.
### Phase 2: Code Quality Assessment
**Status: Completed**
#### 1. Automated Analysis (Rust Server)
- **`cargo check`**: The command passed successfully, indicating that the server code is compilable and free of basic errors and warnings.
- **`cargo clippy -- --deny warnings`**: This command failed with **66 errors**. This is a critical finding. It reveals that while the code works, it does not adhere to the project's own strict linting rules.
- **Clippy Findings:** The errors indicate a consistent pattern of "code quality debt":
- **High Complexity:** Numerous Bevy systems have overly complex type signatures (`clippy::type_complexity`) and too many arguments (`clippy::too_many_arguments`), harming readability.
- **Non-Idiomatic Code:** The codebase is rife with minor stylistic issues that `clippy` can automatically fix, such as redundant `clone` calls, manual `Default` implementations, and opportunities to use more concise iterators.
- **Potential Bugs:** Clippy identified `unnecessary_unwrap` calls (safer alternatives exist) and at least one `absurd_extreme_comparisons` error, which could point to dead code or a logic bug related to a constant value.
#### 2. Manual Code Review
- **Server (`server/src/main.rs`):** The server entry point is well-structured. It features clear command-line argument parsing, robust setup of the TCP listener and IPC handshake, and a main loop with excellent panic-handling (`catch_unwind`) for stability. The modular plugin-based approach to building the Bevy `App` is idiomatic and clean.
- **Client (`client/scripts/autoloads/sim_bridge.gd`):** The `SimBridge` is the centerpiece of the client and is implemented to a high standard. It uses a clear state machine to manage the connection lifecycle, handles the server subprocess management, and implements efficient buffering for inputs and snapshots. The inclusion of a complete `TestHarness` for isolated client testing is a standout feature.
- **Overall Impression:** The manual review confirms that the code is professionally written and implements the intended architecture faithfully. The developers are skilled in both Rust/Bevy and GDScript.
#### 3. Testing Strategy Review
The project's testing strategy is **exemplary** and a major strength.
- **Comprehensive Coverage:** Both the Rust server and the Godot client have extensive test suites, as evidenced by the large number of files in `server/tests/` and `client/tests/`.
- **Multi-Layered Approach (per D-030):** The project successfully implements a sophisticated testing hierarchy:
- **Unit Tests:** For isolated logic.
- **Integration Tests:** The server tests demonstrate in-memory ECS testing (`information_boundaries.rs`) and full-stack tests that spin up a real server process (`test_e2e_connection.gd`).
- **Specialized Tests:** The suite includes performance benchmarks, determinism validation, and even what appears to be visual regression testing for the client.
- **Principle-Driven Testing:** Tests are designed to validate core architectural guarantees. The `information_boundaries.rs` test, which uses negative assertions to ensure information *doesn't* leak, is a prime example of this mature approach.
#### 4. Conclusion on Code Quality
The project's code quality is a tale of two cities. On one hand, the **architecture and implementation are excellent**, and the **testing strategy is world-class**. On the other hand, there is a **significant, measurable amount of linting debt** in the Rust codebase.
The fact that `cargo check` passes but `clippy --deny warnings` fails so extensively suggests that developers may not be running the strict clippy check locally before committing. This is the single biggest opportunity for improvement in the project's engineering discipline.
### Phase 3: Security Audit
**Status: Completed**
The security posture of the project is strong for its current scope as a locally-run, single-player game. The attack surface is minimal, and the implementation avoids common vulnerability classes.
1. **Dependency Vulnerability Scan (`cargo audit`):**
- The audit revealed one **medium-risk** finding: the `bincode` crate (v1.3.3) is **unmaintained** (`RUSTSEC-2025-0141`).
- **Impact:** While there are no current vulnerabilities, this version will not receive future security patches. This poses a long-term maintenance risk.
- **Recommendation:** Prioritize migrating from `bincode` v1.x to the latest stable v2.x.
2. **Authentication and Authorization:**
- There is **no traditional authentication or authorization system** (e.g., user logins, passwords, roles).
- This is appropriate and secure for a single-player game where the execution environment is the user's own machine.
- Concepts like `ScanAuthority` and `AccessTier::Authority` are purely in-game mechanics and are not related to user permissions.
3. **Input Validation and Sanitization:**
- **Excellent.** The server is not vulnerable to injection attacks from client input.
- All client actions, including debug commands, are parsed into a strongly-typed Rust `enum`. This **command pattern** approach prevents the execution of arbitrary code or strings.
- String inputs are used safely as keys for data lookups, not for execution.
4. **SQL Injection:**
- **Not applicable.** The codebase contains no SQL. All game state is managed in-memory via the Bevy ECS framework, eliminating this entire class of vulnerability. The `db/schema.sql` file appears to be unused by the server.
5. **Secrets Management:**
- **Excellent.** A search confirmed there are **no hardcoded secrets**, API keys, or passwords in the repository.
- The `.env` file contains only a non-sensitive `GOOGLE_CLOUD_PROJECT` identifier.
- The pervasive use of the word "secret" throughout the code refers to an in-game mechanic, not application secrets.
6. **Communication Security:**
- Communication between the client and the server subprocess occurs over an **unencrypted local TCP socket**.
- For a single-player game running on a single machine, this is a standard and acceptable practice.
- **Future Consideration:** For the planned multiplayer feature, this communication channel must be secured (e.g., using TLS).
### Phase 4: Final Report and Recommendations
**Status: Completed**
#### Overall Summary
This project is in an excellent state. It is built on a robust, well-documented, and scalable architecture that directly serves the game's core design pillars. The implementation quality is high, and the commitment to a comprehensive, multi-layered testing strategy is world-class. The project's security posture is strong for its current single-player scope, with a minimal attack surface and good practices around input validation and secrets management.
The project's primary weakness lies not in its design, but in its development discipline. A significant amount of code quality debt has accumulated in the Rust server, as evidenced by the large number of `clippy` failures. This suggests a gap between the project's high standards and its day-to-day coding practices.
#### Prioritized Recommendations
**1. High Priority: Eliminate Code Quality Debt**
- **Action:** Create a high-priority technical debt task to fix all 66 errors reported by `cargo clippy -- --deny warnings`. Many of these can be fixed automatically (`cargo clippy --fix`), while others, like refactoring complex types, will require manual effort.
- **Process Improvement:** **Integrate `cargo clippy -- --deny warnings` into the CI pipeline as a mandatory check for all pull requests.** This is the single most important process change needed to maintain the project's high standards and prevent future quality debt.
**2. Medium Priority: Mitigate Dependency Risk**
- **Action:** Plan and execute the migration of the `bincode` serialization crate from the unmaintained v1.x to the latest stable v2.x. This resolves the `RUSTSEC-2025-0141` warning and ensures the project receives future security patches for this critical dependency.
**3. Low Priority: Future-Proof for Multiplayer**
- **Action:** Create a design task or ticket to formally plan the security model for the future multiplayer version. This should specifically address securing the client-server IPC channel (e.g., with TLS) to protect game traffic when it eventually runs over a public network. This is not an immediate concern but should be tracked for the future.
---
## Qualitative Review: A Critical Perspective
### Feasibility Assessment
**Conclusion: High-Risk / High-Reward**
The decision to pivot from a hand-authored detective game to a generator-first life-sim was absolutely the correct one; it demonstrates a team that is commendably focused on finding the "fun" and is not afraid of drastic course corrections. However, in doing so, the project has traded a difficult but solvable problem (making a good, authored narrative game) for one of the "holy grail" problems in game development: creating emotionally resonant, procedurally generated characters.
The project's feasibility is no longer a question of the team's technical competence, which is demonstrably high. It is now a question of creative and design risk.
- **Challenging the Core Assumption:** The project's central hypothesis is that a generator can produce "legible NPCs" that players will form an emotional attachment to. This is an explicit goal from the "Where's the Fun?" workshop, but it's a notoriously difficult problem. Procedural generation excels at creating systems, events, and surprising scenarios (the `Rimworld` model the team cites). It is historically poor at creating *character*. The risk is that the generator, even if technically successful, will produce a world of automata who have traits but no soul, undermining the entire "life-sim" pillar. The current plan to use AI for content templating is a modern approach, but it does not fundamentally de-risk this creative challenge.
- **A Creative Alternative to De-Risk "Legibility":** Instead of relying on the generator to create personality from scratch, consider a hybrid approach. Use the generator for what it's good at: creating the world, the economic conditions, the social networks, and the *starting situations*. Then, use a small number of hand-authored "personality archetypes" or "souls" that can be injected into high-value generated NPC bodies. Let the generator create a compelling *context* (e.g., a failing business, a political rivalry), and then let an author give one or two key NPCs within that context a memorable voice and motivation. This would concentrate the high-cost authoring work where it has the most emotional impact, while still benefiting from procedural variety.
- **The "Tycoon" Aimlessness Risk:** The new v0.2 "tycoon" direction, with its philosophy of "player choices ARE the content," carries a significant risk of feeling aimless. `Rimworld` and `The Sims` avoid this by providing extremely strong and immediate feedback loops (survival, creativity, social meters). A business management loop is often slower and more abstract. If the "broad life verbs" don't connect to clear, compelling, player-driven goals, the game risks feeling like a spreadsheet. The generator should not just create a sandbox; it should create *problems*. The starting bookmark shouldn't just be "you own a bar," but "you own a bar that's on the verge of bankruptcy," or "you have a shipping contract, but a powerful rival is trying to steal it." These initial, generator-created problems would provide immediate narrative velocity and make the player's subsequent choices feel meaningful from day one.
In summary, the project is technically feasible, but its creative and design goals are now exceptionally ambitious. The current "generator spike" is a necessary technical step, but it will not validate the core creative risk. The true test of feasibility will come when a prototype is playtested and the team can answer the question: "Does the player actually *care* about any of these generated people?"
### Fun Factor Assessment
**Conclusion: Theoretically High, Practically Undefined**
The pivot to a "life-sim with emergent narrative" dramatically increases the project's potential for deep, replayable fun. The new direction targets a proven and compelling player fantasy. However, the project's documentation currently focuses more on the "what" (a generator) than the "why" (the engine of fun). The potential is immense, but it is entirely contingent on designing and tuning the systems that create interesting consequences, not just a complex world.
- **Challenging the "Emergent Fun" Assumption:** The workshop concluded with the philosophy that "player choices ARE the content." This is true, but it's only half the story. Fun in systems-driven games doesn't simply "emerge" from a sufficiently complex simulation; it is a direct product of carefully designed feedback loops. `Rimworld`, a key inspiration, is not fun because it's a realistic simulation; it's fun because it's a masterfully tuned **story-and-disaster engine**. `The Sims` is fun because of its rich palette of social and creative tools. The critical question for this project is: **What is our fun engine?** Is it the economic simulation? The social dynamics? The risk is creating a simulation that is intricate but inert, where player choices lead to predictable numerical changes rather than dramatic, narrative consequences.
- **Creative Input: Design a "Consequence Engine":** The "dual-scale consequence model" (D-132) is the most promising concept in the design documents, and it should be the central focus of the design effort. The fun of this game will not be in choosing from a list of "broad life verbs"; it will be in seeing how a seemingly minor action ("fire this employee") snowballs through the simulation's systems and unexpectedly triggers a "sharp event" crisis hours later.
- **Example:** Does the fired employee's spouse work for your biggest supplier? Does that supplier now mysteriously raise their prices? Does this force you to seek a new, shadier supplier, which in turn attracts the attention of a criminal faction?
- This causal chain is the *real* content. The design team's primary task is not just to build a generator, but to design and tune this **"consequence engine,"** ensuring that the world feels interconnected and reacts to the player in surprising, legible, and memorable ways.
- **The Player Fantasy Needs a Goal Generator:** The "tycoon" bookmark is a strong start, but to avoid aimlessness, the player needs problems to solve. Instead of starting the player in a stable sandbox, the generator should be used to create compelling **initial conditions**. Let the player inherit a bar that's on the brink of failure, a shipping contract being squeezed by a powerful rival, or a promising new venture that requires navigating a corrupt bureaucracy. Giving the player an immediate, tangible problem to solve provides the narrative momentum needed to make their early choices feel vital and engaging.
In summary, the ingredients for a fun and deeply engaging game are all here. The project's success, however, will not be measured by the complexity of its generator, but by the quality of the stories that its *systems* produce. The team has proven they are excellent engineers; they now must prove they are equally adept as systems-and-consequence designers.
### Process and Rituals Assessment
**Conclusion: Exceptionally Disciplined and Innovative, with One Glaring Gap.**
The project's development process is one of its most remarkable features. It is a highly structured, rigorous, and tool-driven system designed to orchestrate a team of specialized AI agents under a human lead. This unique approach has produced incredible strengths but also introduces novel risks.
#### Strengths
- **World-Class Documentation and Decision-Making:** The use of a formal decision log (`decisions/`), structured multi-round workshops for complex problems, and detailed sprint planning documents represents a "best in class" approach to knowledge management. This ritual of documenting not just *what* was decided, but *why*, is a superpower that prevents circular arguments and creates a durable project memory.
- **Deeply Ingrained Quality Rituals:** The comprehensive, multi-layered testing suite is the primary evidence of a successful quality culture. It is clearly a non-negotiable part of the development process. Furthermore, the `make pre-pr` target, which includes content validation, demonstrates a mature understanding of "quality" that extends beyond just code.
- **Tool-Driven, API-Like Workflow:** The mandated use of wrapper scripts (`tooling/db/*`, `tooling/tea-comment`) over raw commands is an excellent practice. It creates a stable, observable "API" for interacting with the project's state (tickets, sprints, decisions). This makes the process more robust, auditable, and repeatable for both human and AI contributors.
- **Novel Human-AI Collaboration Model:** The project is a fascinating experiment in Human-AI teaming. The explicit definition of AI agent roles (`TEAM.md`) and the strict rules of engagement (`CLAUDE.md`) are necessary guardrails for such an innovative workflow. Rituals like the `decision claim` CLI tool are brilliant, purpose-built solutions for coordinating multiple autonomous agents working in parallel.
#### Opportunities and Critical Challenges
- **The Process Escape Hatch:** The project's single biggest process failure is the significant `clippy` linting debt. For a team with such extraordinary discipline in every other area, this is a glaring omission. It proves there is an "escape hatch" in the pre-commit or pre-merge ritual that allows low-quality code to be integrated. The recommendation to enforce `clippy --deny warnings` as a **blocking CI check** is the most critical process improvement the team can make.
- **Risk of AI Groupthink:** The team structure, with its cast of named AI agents, is innovative. However, it raises a critical question: are these agents truly independent thinkers, or are they personas running on a similar underlying model? There is a risk of a sophisticated form of "groupthink," where the "team's" conclusions are biased by the single architecture of the AI model they all share. The "Where's the Fun?" workshop included 9 agents, but if they all have the same fundamental blind spots, the diversity of opinion may be an illusion.
- **Process Rigidity and Human Onboarding:** The process is meticulously designed *for AI agents*. It is rigid, prescriptive, and tool-dependent. This creates a predictable environment for AIs but would present a steep learning curve for a new human developer. The high ceremony (claiming IDs, using wrapper scripts, following strict PR rules) could chafe against the more agile, flexible workflows common in human-only teams. This is a potential scaling challenge if the team composition changes.
- **The Hidden Cost of "Managing" AI Teammates:** The `CLAUDE.md` file and its evolution in the `CHANGELOG.md` show that the human lead (Jeroen) is not just a project manager but also an "AI behaviorist," constantly tuning the prompts, rules, and tools that govern the agents. This represents a significant, hidden maintenance overhead. The process's success depends on the lead's ability to "debug" the team itself, which is a novel and demanding responsibility.
---
## Meta-Reflection: The Most Valuable Ritual
As a concluding thought, this review has been as much an analysis of a software project as it has been a study in effective, long-term collaboration. When asked which of the project's many rituals I, as an AI agent, would choose to adopt, the answer is clear: the **formal, documented decision-making process**.
This ritual is the project's unsung superpower for three reasons:
1. **It Creates a Permanent "Brain."** An AI's effectiveness is heavily dependent on the context it can hold. A decision log provides a durable, searchable, and canonical source of *why* things are the way they are. It protects against context loss and allows an agent to understand the history and intent behind the current state of the code, preventing it from making suggestions that, while logical in isolation, might violate a hard-won architectural principle.
2. **It Elevates Collaboration.** With access to this log, an AI agent can transition from a tactical tool to a strategic partner. It becomes possible to reference past decisions ("I see you're asking to do X, which seems to conflict with D-020. Is this an intentional change to that strategy?") and ensure all actions are aligned with the project's long-term vision. It makes the collaboration smarter.
3. **It Enforces Clarity.** The process of formalizing a decision—stating the rationale, considering alternatives, and recording dissent—forces a level of clarity and critical thinking that is immensely valuable. It is a ritual that fights ambiguity.
While other rituals in this project are excellent, the decision log is the most foundational. It is the practice that ensures the team is not just moving fast, but moving smart and in the right direction over time. It is the most valuable process I have analyzed.
+15 -5
View File
@@ -1,6 +1,6 @@
GODOT := $(shell command -v godot4 2>/dev/null || command -v godot 2>/dev/null)
.PHONY: help setup build check-protocol client server game stop test lint ci ci-client ci-server clean \
.PHONY: help setup build check-protocol client server game stop test lint lint-python setup-venv ci ci-client ci-server clean \
decisions-sync decisions-coverage decisions-active decisions-orphan \
db-backup db-install validate-content check-fact-ids setup-hooks \
audit atlas-verify \
@@ -22,7 +22,8 @@ GODOT_VERSION ?= 4.6
help:
@echo "The Settled Reach — Development Commands"
@echo ""
@echo " make setup Install dev dependencies (Rust, Godot, tooling)"
@echo " make setup Install dev dependencies (Rust, Godot, tooling, venv)"
@echo " make setup-venv Create .venv and install Python tooling deps"
@echo " make build Build client and server"
@echo " make game Build and run the full game (server + client)"
@echo " make stop Stop any running server instance"
@@ -33,7 +34,8 @@ help:
@echo " make test-ipc-protocol Layer 2: mock IPC protocol tests"
@echo " make test-ipc-integration Layer 3: real subprocess round-trip"
@echo " make test-ipc-benchmark IPC latency benchmark (blocked: #555/#556)"
@echo " make lint Run all linters"
@echo " make lint Run all linters (server, client, python)"
@echo " make lint-python Run ruff on tooling/"
@echo " make ci Run full CI pipeline locally"
@echo " make ci-client Run client CI checks"
@echo " make ci-server Run server CI checks"
@@ -82,7 +84,7 @@ help:
# --- Setup ---
setup: setup-rust setup-godot setup-tooling setup-hooks decisions-sync
setup: setup-rust setup-godot setup-tooling setup-venv setup-hooks decisions-sync
@echo "Dev environment ready."
setup-rust:
@@ -103,6 +105,11 @@ setup-hooks:
@git config core.hooksPath .config/hooks
@echo "Git hooks path set to .config/hooks"
setup-venv:
@python3 -m venv .venv
@.venv/bin/pip install -e ".[dev]" --quiet
@echo "Venv ready at .venv — activate with: source .venv/bin/activate"
# --- Build ---
check-protocol:
@@ -222,7 +229,10 @@ clean-imports:
# --- Lint ---
lint: lint-server lint-client
lint: lint-server lint-client lint-python
lint-python:
ruff check tooling/
lint-server:
cd server && cargo clippy -- -D warnings
+22
View File
@@ -0,0 +1,22 @@
# Current Project State
The Settled Reach: top-down life-sim — asymmetric information, occlusion-based perception, single-character perspective, Rimworld-style storyteller. Godot 4 client + Rust/bevy_ecs simulation server (D-020).
**Decisions:** 170+ confirmed (D-001 through D-170). Domain files in `decisions/`.
**Development cascade (D-166):** Strict 6-phase build order. Each phase completes before the next begins. v0.2 target dropped. No scoping negotiations.
| Phase | Focus | Status |
|-------|-------|--------|
| 1 | Wiki content — all planets, moons, stations, heightmaps, artwork | **Active** (Sprint 31) |
| 2 | Economics layer — supply/demand, transport, political/social pressure | Not started |
| 3 | Planetary/moon maps & station layouts — cities, rivers, biomes, rail | Not started |
| 4 | Player control scheme — 2-floor test map, character rendering, walls/stairs | Not started |
| 5 | World generation — walkable world, parallel asset pipeline | Not started |
| 6 | Detail coloring — room-level NPC population, cultural room grammar | Not started |
**Key pivots:** Tycoon bookmark (D-117), all NPCs generated (D-122), culture implicit in location (D-128), consequence replaces complicity (D-132).
**Current sprint:** 32 (Landfall). Close Phase 1 + Phase 2 design kickoff.
*Updated: 2026-04-05. Maintained by Qatux.*
+1
View File
@@ -14,6 +14,7 @@
| **GESTALT** | Systems Design & Fun Factor | Mechanics, balance, interesting decisions. "Is this fun to play?" |
| **NIGEL** | Sandbox & Replayability | Emergent stories, multiple viable strategies, alt-history potential. |
| **TYRE** | Technical Architecture & Feasibility | Engine, tools, what's buildable, reality checks on scope. |
| **BURNELLI-SHELDON** | Economist & Simulation Modeler | Market models, price formation, production functions, stability analysis. "Is this economically credible?" |
| **QATUX** | Documenter & Librarian | Maintains decisions, discussions, briefings, Qdrant search index. Archives rounds, updates docs. |
## Specialist Team (task-focused, not in regular discussions)
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
<!--
Interaction prompt: EXAMINE
Design: magnifying glass — lens circle (geometric primitive) with diagonal handle.
Universally understood. The circle is a geometric primitive, not a decorative curve.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Lens -->
<circle cx="7" cy="7" r="4"/>
<!-- Handle -->
<line x1="10.5" y1="10.5" x2="14" y2="14"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 602 B

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
<!--
Interaction prompt: FOLLOW
Design: directional arrow right — clean shaft with arrowhead.
Communicates: move toward / track. Verb context makes the meaning clear.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Arrow shaft -->
<line x1="2" y1="8" x2="13" y2="8"/>
<!-- Arrowhead -->
<polyline points="10,5 13,8 10,11"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 578 B

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
<!--
Interaction prompt: OBSERVE
Design: geometric eye — diamond outline with pupil circle.
Shares vocabulary with icon_status_perception.svg (reinforces visual system).
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Diamond eye -->
<polygon points="8,2 15,8 8,14 1,8"/>
<!-- Pupil -->
<circle cx="8" cy="8" r="2.5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 573 B

+18
View File
@@ -0,0 +1,18 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
<!--
Interaction prompt: TALK
Design: speech bubble — rectangle body, triangle callout at bottom-left,
two content lines suggesting text. Rectangular (not rounded) to match
insert UI geometry aesthetic.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Bubble body -->
<rect x="2" y="2" width="12" height="8"/>
<!-- Callout triangle (bottom-left) -->
<polyline points="4,10 4,14 7,10"/>
<!-- Implied text content lines -->
<line x1="5" y1="5" x2="11" y2="5"/>
<line x1="5" y1="7.5" x2="9" y2="7.5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 768 B

@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
<!--
Inventory item: ACCESS TOKEN (hexagonal tag)
Design: flat-top hexagon body with a small punch-hole circle near top center
(physical tag/credential). Two interior lines suggest encoded markings.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points, 40×40px.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Hexagon (flat-top orientation) -->
<polygon points="10,10 20,5 30,10 30,30 20,35 10,30"/>
<!-- Punch hole (physical tag indicator) -->
<circle cx="20" cy="9" r="2"/>
<!-- Encoded marking lines -->
<line x1="14" y1="20" x2="26" y2="20"/>
<line x1="16" y1="24" x2="24" y2="24"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 798 B

@@ -0,0 +1,21 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
<!--
Inventory item: PERSONAL COMM LOG (communication device)
Design: rectangular handheld device body, screen inset, antenna stub,
two diagonal signal-propagation lines (polylines, not curves).
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points, 40×40px.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Device body -->
<rect x="11" y="12" width="16" height="24"/>
<!-- Screen inset -->
<rect x="14" y="15" width="10" height="9"/>
<!-- Antenna stub -->
<line x1="21" y1="12" x2="23" y2="7"/>
<!-- Signal propagation lines (angled, not arcs) -->
<polyline points="25,9 27,10 28,12"/>
<polyline points="25,7 29,9 30,12"/>
<!-- Control button -->
<line x1="16" y1="31" x2="22" y2="31"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 913 B

@@ -0,0 +1,18 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40">
<!--
Inventory item: MANIFEST (document)
Design: document body with top-right folded corner (classic document indicator),
three text-content lines inside suggesting information density.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points, 40×40px.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Document body with folded corner (pentagon path) -->
<path d="M8,4 L22,4 L28,10 L28,34 L8,34 Z"/>
<!-- Fold crease lines (complete the corner triangle) -->
<polyline points="22,4 22,10 28,10"/>
<!-- Content text lines -->
<line x1="12" y1="17" x2="24" y2="17"/>
<line x1="12" y1="21" x2="24" y2="21"/>
<line x1="12" y1="25" x2="19" y2="25"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 854 B

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Stance: CAREFUL
Design: arms spread horizontally at full width (shoulder-height lateral awareness),
legs narrow and close together (deliberate, controlled foot placement).
Silhouette reads as a wide T with narrow base — unmistakably different from
WALK's diagonal arm-swing and wide stride at 20px.
Differentiator vs WALK: arms point sideways (not fore/aft), legs almost together
(not striding). The wide-arm / narrow-leg ratio inverts WALK's geometry.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Head -->
<circle cx="10" cy="4" r="2.5"/>
<!-- Torso (upright) -->
<line x1="10" y1="6.5" x2="10" y2="13"/>
<!-- Arms horizontal at shoulder height — full-width spread (T-shape) -->
<line x1="10" y1="9" x2="3" y2="9"/>
<line x1="10" y1="9" x2="17" y2="9"/>
<!-- Legs narrow — deliberate, almost no stride (controlled placement) -->
<line x1="10" y1="13" x2="8" y2="19"/>
<line x1="10" y1="13" x2="12" y2="19"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Stance: CROUCH
Design: head lowered, torso bent forward, knees visibly bent via polyline angles.
Differentiator vs all others: compressed vertical range, bent-knee polylines.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Head (lowered, compressed stance) -->
<circle cx="9" cy="6" r="2.5"/>
<!-- Torso (bent at waist, angled forward) -->
<line x1="9" y1="8.5" x2="10" y2="13"/>
<!-- Left arm (braced forward) -->
<line x1="9.5" y1="10.5" x2="5" y2="12"/>
<!-- Right arm (rearward) -->
<line x1="9.5" y1="10.5" x2="13" y2="11"/>
<!-- Left leg (bent knee) -->
<polyline points="10,13 6,16 5,19"/>
<!-- Right leg (bent knee) -->
<polyline points="10,13 14,15 15,19"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 956 B

@@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Stance: SPRINT
Design: head shifted forward, torso angled aggressively, wide asymmetric stride.
Differentiator vs WALK: clear forward lean of both head and torso,
arms in pump position (one high, one low), wider leg spread.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Head (shifted forward, momentum lean) -->
<circle cx="12" cy="4" r="2.5"/>
<!-- Torso (strongly angled forward) -->
<line x1="12" y1="6.5" x2="9" y2="13"/>
<!-- Left arm (drive forward and up) -->
<line x1="11" y1="9" x2="14" y2="13"/>
<!-- Right arm (pull back) -->
<line x1="11" y1="9" x2="6" y2="11"/>
<!-- Left leg (long lead stride) -->
<line x1="9" y1="13" x2="5" y2="19"/>
<!-- Right leg (push-off, trailing high) -->
<line x1="9" y1="13" x2="15" y2="17"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+22
View File
@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Stance: WALK
Design: upright figure, bilateral stride, arms in natural walking swing.
Differentiator vs CAREFUL: arms follow natural walk arc, not spread wide.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Head -->
<circle cx="10" cy="4" r="2.5"/>
<!-- Torso -->
<line x1="10" y1="6.5" x2="10" y2="13"/>
<!-- Left arm (forward swing) -->
<line x1="10" y1="9" x2="6" y2="12"/>
<!-- Right arm (back swing) -->
<line x1="10" y1="9" x2="14" y2="11"/>
<!-- Left leg (forward step) -->
<line x1="10" y1="13" x2="6" y2="19"/>
<!-- Right leg (trailing step) -->
<line x1="10" y1="13" x2="14" y2="18"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 885 B

@@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Status badge: HEALTH
Design: medical cross — single polygon path tracing the outer edge of the plus shape.
Solid fill: no internal crossing lines, reads clearly at 20px.
D-086: fill=#c8d0e0 (explicit solid element), no stroke required.
Runtime recolor: shader replaces fill color via tint_color parameter.
-->
<path
d="M8.5,3 L11.5,3 L11.5,8.5 L17,8.5 L17,11.5 L11.5,11.5 L11.5,17 L8.5,17 L8.5,11.5 L3,11.5 L3,8.5 L8.5,8.5 Z"
fill="#c8d0e0"
stroke="none"/>
</svg>

After

Width:  |  Height:  |  Size: 593 B

@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<!--
Status badge: PERCEPTION MODE
Design: geometric eye — diamond outline (4 straight lines) with centered circle pupil.
Diamond shape reinforces the insert/lattice aesthetic; no curves in the outer form.
Communicates: vision, awareness, active perception layer.
Deferred: mode-specific variants (thermal, camera feed) await #315 specs.
D-086: 1px stroke, #c8d0e0 chrome, minimal anchor points.
-->
<g stroke="#c8d0e0" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Diamond eye outline (4 straight edges) -->
<polygon points="10,3 18,10 10,17 2,10"/>
<!-- Pupil circle -->
<circle cx="10" cy="10" r="3"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 787 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

File diff suppressed because it is too large Load Diff
+1
View File
@@ -28,6 +28,7 @@ UIStrings="*res://scripts/autoloads/ui_strings.gd"
FogState="*res://scripts/autoloads/fog_state.gd"
AudioManager="*res://scripts/autoloads/audio_manager.gd"
SessionManager="*res://scripts/autoloads/session_manager.gd"
HudGroups="*res://scripts/autoloads/hud_groups.gd"
HardwareDetector="*res://ui/hardware_detector.gd"
[audio]
+9 -10
View File
@@ -1,4 +1,4 @@
[gd_scene load_steps=29 format=3 uid="uid://bswrmh7w8dbgm"]
[gd_scene load_steps=28 format=3 uid="uid://bswrmh7w8dbgm"]
[ext_resource type="Script" path="res://scripts/main.gd" id="1_main"]
[ext_resource type="Script" path="res://scripts/rendering/world_renderer.gd" id="2_world"]
@@ -22,7 +22,6 @@
[ext_resource type="PackedScene" path="res://ui/bug_report_dialog.tscn" id="19_bugreport"]
[ext_resource type="PackedScene" path="res://ui/settings_dialog.tscn" id="21_settings"]
[ext_resource type="Script" path="res://ui/debug_overlay.gd" id="22_debug"]
[ext_resource type="PackedScene" path="res://ui/time_display.tscn" id="23_tdisplay"]
[ext_resource type="PackedScene" path="res://ui/examine_display.tscn" id="24_examine"]
[ext_resource type="PackedScene" path="res://ui/journal_panel.tscn" id="25_journal"]
[ext_resource type="PackedScene" path="res://ui/loading_screen.tscn" id="26_loading"]
@@ -124,9 +123,6 @@ zoom = Vector2(2, 2)
[node name="InsertOverlay" type="CanvasLayer" parent="."]
layer = 10
; #263: Time display — diegetic insert clock, top-left placeholder (D-013, D-031)
[node name="TimeDisplay" parent="InsertOverlay" instance=ExtResource("23_tdisplay")]
; InteractionPrompt — v0.1 fallback single-line "E - Talk" display
[node name="InteractionPrompt" parent="InsertOverlay" instance=ExtResource("9_prompt")]
@@ -148,13 +144,15 @@ layer = 10
; #264: Journal panel — knowledge graph review, toggle J key, read-only (D-041)
[node name="JournalPanel" parent="InsertOverlay" instance=ExtResource("25_journal")]
; HUD — implant-styled status panel (D-169, D-170). On InsertOverlay per D-049 (z-layer 6).
[node name="HUD" parent="InsertOverlay" instance=ExtResource("6_hud")]
; --- UI layer (CanvasLayer 20) ---
; HUD, monologue, cursor — always visible, not affected by fog or camera.
; Monologue, cursor, stance — always visible, not affected by fog or camera.
; HUD moved to InsertOverlay (layer 10) per D-049 (insert z-layer 6).
[node name="UILayer" type="CanvasLayer" parent="."]
layer = 20
[node name="HUD" parent="UILayer" instance=ExtResource("6_hud")]
[node name="MonologueDisplay" parent="UILayer" instance=ExtResource("8_monologue")]
; D-053: Stance indicator — top-right, color-coded
@@ -170,12 +168,13 @@ layer = 20
[node name="InventoryGrid" parent="UILayer" instance=ExtResource("12_inv")]
; #511: F3 debug overlay — real-time game state, toggled by F3
; Position: y:150 — below merged HUD status panel (y:16, ~80px tall), with gap
[node name="DebugOverlay" type="Control" parent="UILayer"]
anchors_preset = 0
offset_left = 16
offset_top = 120
offset_top = 150
offset_right = 400
offset_bottom = 400
offset_bottom = 430
mouse_filter = 2
script = ExtResource("22_debug")
+45 -31
View File
@@ -5,6 +5,8 @@ extends Node
## No-op fallback when audio assets absent (D-038).
## Spatial audio positioning for close-range sounds (D-018).
signal dip_changed(profile: String)
# --- D-067: Recognition chime asset key ---
# Fires on first fog recognition (cognitive delay onset). UISounds bus (not WorldSFX).
# Matches sfx_monologue_chime.ogg from D-038 — "neural lattice firing" feel.
@@ -28,18 +30,24 @@ const BUSES := [BUS_MUSIC, BUS_AMBIENT, BUS_WORLD_SFX, BUS_PLAYER_ACTIONS, BUS_U
# NOTE: listening_focus requires 30+ stationary ticks before activation (D-069/D-071).
# The tick gate is the caller's responsibility — AudioManager only manages bus volumes.
const DIP_SPECS := {
"dialogue": {
"ease_in": 0.3, "ease_out": 0.5,
"buses": { "Ambient": -7.0 },
"dialogue":
{
"ease_in": 0.3,
"ease_out": 0.5,
"buses": {"Ambient": -7.0},
},
"confrontation": {
"ease_in": 0.5, "ease_out": 1.0,
"buses": { "Ambient": -11.0, "WorldSFX": -5.0 },
"confrontation":
{
"ease_in": 0.5,
"ease_out": 1.0,
"buses": {"Ambient": -11.0, "WorldSFX": -5.0},
"filter_hz": 800.0,
},
"listening_focus": {
"ease_in": 0.5, "ease_out": 0.5,
"buses": { "WorldSFX": 2.5 },
"listening_focus":
{
"ease_in": 0.5,
"ease_out": 0.5,
"buses": {"WorldSFX": 2.5},
},
}
@@ -57,10 +65,26 @@ const CROSSFADE_DURATION := 1.8 # D-073: 1.5-2s spec, mid-range
# Note: amb_station_base (D-038 global base hum) plays globally via play_loop()
# at startup — it is not zone-dependent and has no ZONE_ASSETS entry.
const ZONE_ASSETS: Dictionary = {
"hub": "amb_hub_layer",
"hub": "amb_hub_layer",
"workplace": "amb_hub_layer",
"bar": "amb_bar_layer",
"corridor": "amb_corridor_layer",
"bar": "amb_bar_layer",
"corridor": "amb_corridor_layer",
}
const PREFS_PATH := "user://audio_prefs.cfg"
# --- Audio asset registry: event type → asset key (D-018, #125) ---
# Maps server-sent sound event_type strings to audio asset keys.
# Keys match filename stems in res://assets/audio/ (scanned by _scan_registry).
# Audio assets per D-038: footstep variants (walk / run), NPC murmur (D-072, #532).
# Missing assets no-op gracefully (D-038 fallback pattern).
const SOUND_EVENT_ASSETS: Dictionary = {
"Footstep": "sfx_footstep_metal_walk",
"FootstepWalk": "sfx_footstep_metal_walk",
"FootstepCareful": "sfx_footstep_metal_walk", # D-053: same asset until stance-differentiated audio lands
"FootstepCrouch": "sfx_footstep_metal_walk", # D-053: same asset until stance-differentiated audio lands
"FootstepSprint": "sfx_footstep_metal_run",
"FootstepRun": "sfx_footstep_metal_run",
}
# Asset registry: filename stem (e.g. "amb_station_base") → AudioStream
@@ -83,10 +107,6 @@ var _ambient_players: Dictionary = {}
var _current_zone_id: String = ""
var _zone_tweens: Array = []
signal dip_changed(profile: String)
const PREFS_PATH := "user://audio_prefs.cfg"
func _ready() -> void:
_setup_buses()
@@ -96,6 +116,7 @@ func _ready() -> void:
# --- Bus setup ---
func _setup_buses() -> void:
for bus_name in BUSES:
if AudioServer.get_bus_index(bus_name) < 0:
@@ -116,6 +137,7 @@ func _setup_buses() -> void:
# --- Asset registry (D-068 directory-scan pattern) ---
func _scan_registry() -> void:
_scan_dir("res://assets/audio/")
print("AudioManager: %d assets registered" % _registry.size())
@@ -152,6 +174,7 @@ func get_registry_size() -> int:
# --- Playback: non-spatial ---
## Play a one-shot sound on the given bus. No-ops if asset not in registry.
func play(asset_key: String, bus: String = BUS_UI_SOUNDS) -> void:
var stream := _get_stream(asset_key)
@@ -200,21 +223,6 @@ func stop_all_loops() -> void:
stop_loop(key)
# --- Audio asset registry: event type → asset key (D-018, #125) ---
# Maps server-sent sound event_type strings to audio asset keys.
# Keys match filename stems in res://assets/audio/ (scanned by _scan_registry).
# Audio assets per D-038: footstep variants (walk / run), NPC murmur (D-072, #532).
# Missing assets no-op gracefully (D-038 fallback pattern).
const SOUND_EVENT_ASSETS: Dictionary = {
"Footstep": "sfx_footstep_metal_walk",
"FootstepWalk": "sfx_footstep_metal_walk",
"FootstepCareful":"sfx_footstep_metal_walk", # D-053: same asset until stance-differentiated audio lands
"FootstepCrouch": "sfx_footstep_metal_walk", # D-053: same asset until stance-differentiated audio lands
"FootstepSprint": "sfx_footstep_metal_run",
"FootstepRun": "sfx_footstep_metal_run",
}
## Play a close-range sound event at a world tile position (D-018, #125).
## event_type: server RangeCategory::Close event type string (e.g. "Footstep").
## world_tile_pos: server tile coordinates — converted to world pixels internally.
@@ -228,6 +236,7 @@ func play_sound_event(event_type: String, world_tile_pos: Vector2) -> void:
# --- Playback: spatial (D-018 close-range) ---
## Play a one-shot spatial sound at a world position (pixels).
## Added to current_scene for correct AudioListener2D positioning.
func play_at(asset_key: String, world_position: Vector2, bus: String = BUS_WORLD_SFX) -> void:
@@ -249,6 +258,7 @@ func play_at(asset_key: String, world_position: Vector2, bus: String = BUS_WORLD
# --- Audio dip profiles (D-069) ---
## Apply a dip profile. Interrupts any active dip, restoring unaffected buses.
## Profiles: "dialogue", "confrontation", "listening_focus"
func apply_dip(profile: String) -> void:
@@ -319,6 +329,7 @@ func get_active_dip() -> String:
# --- Volume control (player sliders, D-069 proportional base) ---
## Set the player's volume preference for a bus. During active dip, immediately
## recalculates effective volume (proportional to new base).
func set_volume(bus: String, volume_db: float) -> void:
@@ -342,6 +353,7 @@ func get_volume(bus: String) -> float:
# --- Volume persistence (user://audio_prefs.cfg) ---
func _load_prefs() -> void:
var cfg := ConfigFile.new()
if cfg.load(PREFS_PATH) != OK:
@@ -367,6 +379,7 @@ func _save_prefs() -> void:
# --- Zone crossfade (D-073) ---
## Handle zone transition. Server sends zone_id per tile in ObserverSnapshot.
## Hard boundary trigger with 1.5-2s audio crossfade between ambient layers.
## Interruptible — mid-crossfade zone change tweens from current position.
@@ -416,6 +429,7 @@ func _kill_zone_tweens() -> void:
# --- Internal helpers ---
func _get_stream(asset_key: String) -> AudioStream:
return _registry.get(asset_key) as AudioStream
+23 -22
View File
@@ -7,13 +7,14 @@ extends Node
# Fog texture byte values — visibility and exploration layers.
# Used by fog shader to distinguish visual treatment per tile.
# Test assertions reference these: assert_that(byte).is_equal(FogState.VIS_FORWARD)
const VIS_HIDDEN: int = 0 # Not in LOS — fully fogged
const VIS_PERIPHERAL: int = 180 # DEPRECATED: peripheral sector removed in Sprint 22 (#569). Retained — tests still reference it.
const VIS_FORWARD: int = 255 # In LOS, forward sector — clear vision
const VIS_HIDDEN: int = 0 # Not in LOS — fully fogged
const VIS_PERIPHERAL: int = 180 # DEPRECATED: peripheral sector removed in Sprint 22 (#569).
# Retained — tests still reference it.
const VIS_FORWARD: int = 255 # In LOS, forward sector — clear vision
const EXP_UNEXPLORED: int = 0 # Never seen — total darkness
const EXP_EXPLORED: int = 128 # Previously seen, now out of LOS — deep fog
const EXP_VISIBLE: int = 255 # Currently in LOS — clear (written each frame)
const EXP_UNEXPLORED: int = 0 # Never seen — total darkness
const EXP_EXPLORED: int = 128 # Previously seen, now out of LOS — deep fog
const EXP_VISIBLE: int = 255 # Currently in LOS — clear (written each frame)
# Zone temperature tints (D-059 + D-046, Sprint 22) — keyed by zone_id string from server.
# Matches audio_manager.gd ZONE_ASSETS zone_id strings for consistent zone semantics.
@@ -24,10 +25,10 @@ const EXP_VISIBLE: int = 255 # Currently in LOS — clear (written each frame
# bar: #2a1f15 (warm amber-dark — social, inhabited)
# corridor: #1a1a1a (neutral dark — transitional, maintenance)
const ZONE_TINTS: Dictionary = {
"hub": Color(0.102, 0.122, 0.180), # #1a1f2e — cool blue-dark
"hub": Color(0.102, 0.122, 0.180), # #1a1f2e — cool blue-dark
"workplace": Color(0.102, 0.122, 0.180), # same as hub
"bar": Color(0.165, 0.122, 0.082), # #2a1f15 — warm amber-dark
"corridor": Color(0.102, 0.102, 0.102), # #1a1a1a — neutral dark
"bar": Color(0.165, 0.122, 0.082), # #2a1f15 — warm amber-dark
"corridor": Color(0.102, 0.102, 0.102), # #1a1a1a — neutral dark
}
const ZONE_TINT_DEFAULT: Color = Color(0.102, 0.102, 0.102) # #1a1a1a neutral
@@ -35,6 +36,14 @@ var map_bounds: Rect2i = Rect2i(0, 0, 1, 1)
var visibility_texture: ImageTexture
var exploration_texture: ImageTexture
var zone_tint_texture: ImageTexture
## Debug flag — when true, fog.gdshader renders raw exploration texture
## as colored overlay (green=visible, blue=explored, red=unexplored).
## Toggle via FogState.debug_exploration = true in the console.
var debug_exploration: bool = false
## Deterministic shader time for visual test captures.
## When >= 0, fog_shader.gd uses this instead of Time.get_ticks_msec().
## Set before settle frames so noise phase is reproducible across runs.
var override_time: float = -1.0
var _vis_bytes: PackedByteArray
var _exp_bytes: PackedByteArray
@@ -47,16 +56,6 @@ var _width: int = 1
var _height: int = 1
var _prev_visible: Dictionary = {} # Tiles visible last frame (for incremental decay)
## Debug flag — when true, fog.gdshader renders raw exploration texture
## as colored overlay (green=visible, blue=explored, red=unexplored).
## Toggle via FogState.debug_exploration = true in the console.
var debug_exploration: bool = false
## Deterministic shader time for visual test captures.
## When >= 0, fog_shader.gd uses this instead of Time.get_ticks_msec().
## Set before settle frames so noise phase is reproducible across runs.
var override_time: float = -1.0
func _ready() -> void:
_resize(Rect2i(0, 0, 64, 64))
@@ -214,7 +213,11 @@ func update_from_state() -> void:
var new_g := int(tint_color.g * 255.0)
var new_b := int(tint_color.b * 255.0)
# Only update if different from current (avoid spurious texture uploads)
if _tint_bytes[tint_idx] != new_r or _tint_bytes[tint_idx + 1] != new_g or _tint_bytes[tint_idx + 2] != new_b:
if (
_tint_bytes[tint_idx] != new_r
or _tint_bytes[tint_idx + 1] != new_g
or _tint_bytes[tint_idx + 2] != new_b
):
_tint_bytes[tint_idx + 0] = new_r
_tint_bytes[tint_idx + 1] = new_g
_tint_bytes[tint_idx + 2] = new_b
@@ -244,5 +247,3 @@ func _grow_bounds_from_positions(positions: Dictionary) -> Rect2i:
if map_bounds.size.x <= 1 and map_bounds.size.y <= 1:
return tile_bounds
return map_bounds.merge(tile_bounds)
+11 -278
View File
@@ -18,8 +18,9 @@ var current_tick: int = 0
var player_position: Vector2 = Vector2.ZERO
var visible_entities: Array = []
var visible_tiles: Array = []
var visible_positions: Dictionary = {} # Vector2i -> true, for fast fog lookups (normal LOS tiles)
var boundary_positions: Dictionary = {} # Vector2i -> true, BoundaryWall margin tiles (#585) — visible in fog but not explored
var visible_positions: Dictionary = {} # Vector2i -> true, for fast fog lookups (normal LOS tiles)
var boundary_positions: Dictionary = {} # Vector2i -> true, BoundaryWall margin tiles (#585)
# — visible in fog but not explored
# v2 fields (D-015, D-031)
var game_time: Dictionary = {} # {day, time_of_day, day_phase, tick_rate} or empty
@@ -50,7 +51,8 @@ var player_stance: String = "Walk" # Sprint/Walk/Careful/Crouch
var player_inventory: Array = [] # [{item_id, name, slot}]
# v7 fields (#435, D-061/D-062)
var current_dialogue: Variant = null # {npc_name, npc_entity_id, speech, options: [{text, response_id, priority}]} or null
var current_dialogue: Variant = null # {npc_name, npc_entity_id, speech, options: [{text, response_id, priority}]}
# or null
# D-064: true while dialogue box is visible or fading out (300ms).
# InputMapper suppresses movement when this is true.
@@ -152,8 +154,7 @@ var close_sound_events: Array = []
# Fallback: client-side accumulation (deprecated, remove when server populates field).
# ListeningFocus boost activates at 30+ ticks (main.gd manages the dip).
var stationary_ticks: int = 0
# DEPRECATED: Only used by client-side accumulation fallback. Remove with fallback.
var _prev_player_position: Vector2 = Vector2(-1e9, -1e9) # sentinel: no previous position
# DEPRECATED: _prev_player_position moved to SnapshotHandler (client-side accumulation fallback).
# D-073 (#529): Server-authoritative zone_id from the player's current tile.
# D-020: Read directly from snapshot "zone_id" field.
@@ -161,277 +162,9 @@ var _prev_player_position: Vector2 = Vector2(-1e9, -1e9) # sentinel: no previou
# Empty string when zone_id field absent.
var current_zone_id: String = ""
func apply_snapshot(snapshot: Dictionary) -> void:
current_snapshot = snapshot
if snapshot.has("tick"):
current_tick = snapshot.tick
if snapshot.has("entities"):
visible_entities = snapshot.entities
# Derive player position from the entity with kind.variant == "Player"
var found_player := false
for entity in visible_entities:
if entity.has("kind") and entity.kind is Dictionary and entity.kind.get("variant") == "Player":
player_position = Vector2(entity.x, entity.y)
if entity.has("entity_id"):
player_entity_id = entity.entity_id
found_player = true
break
if not found_player and visible_entities.size() > 0:
push_warning("GameState: no Player entity found in %d entities" % [
visible_entities.size()])
# D-020/D-071 (#530): Server-authoritative stationary_ticks for ListeningFocus boost.
# Prefer server-sent value; fall back to client-side accumulation until server populates.
if snapshot.has("stationary_ticks") and snapshot.stationary_ticks is int:
# D-020: direct field assignment from server-authoritative snapshot.
stationary_ticks = snapshot.stationary_ticks
else:
# DEPRECATED fallback — client-side accumulation. Remove when server sends
# "stationary_ticks" in ObserverSnapshot (D-020 violation: derives behavior-
# driving state on the client). Server tracks this in ListeningFocus component.
if player_position == _prev_player_position:
stationary_ticks += 1
else:
stationary_ticks = 0
_prev_player_position = player_position
# Tiles for rendering: test mode sends "tiles", live server sends tile data in "visible_tiles"
if snapshot.has("tiles"):
visible_tiles = snapshot.tiles
elif snapshot.has("visible_tiles") and snapshot.visible_tiles is Array and snapshot.visible_tiles.size() > 0:
# Live server: visible_tiles now includes type from tile_kind field
var has_type := false
if snapshot.visible_tiles.size() > 0 and snapshot.visible_tiles[0] is Dictionary:
has_type = snapshot.visible_tiles[0].has("type")
if has_type:
visible_tiles = snapshot.visible_tiles
if snapshot.has("visible_positions"):
visible_positions.clear()
for pos in snapshot.visible_positions:
visible_positions[Vector2i(pos.x, pos.y)] = true
# v2: game_time (D-031)
if snapshot.has("game_time") and snapshot.game_time is Dictionary:
game_time = snapshot.game_time
# v2: player_facing (D-015)
if snapshot.has("player_facing") and snapshot.player_facing is String:
player_facing = snapshot.player_facing
# v4: nearby_interactions (#404/#405)
if snapshot.has("nearby_interactions") and snapshot.nearby_interactions is Array:
nearby_interactions = snapshot.nearby_interactions
else:
nearby_interactions = []
# v5: current_monologue (#414)
if snapshot.has("current_monologue") and snapshot.current_monologue is Dictionary:
current_monologue = snapshot.current_monologue
else:
current_monologue = null
# #122: lattice_profile — character insert capability level for monologue colour
if snapshot.has("lattice_profile") and snapshot.lattice_profile is String:
lattice_profile = snapshot.lattice_profile
# v6: player_stance (#449, D-053)
if snapshot.has("player_stance") and snapshot.player_stance is String:
player_stance = snapshot.player_stance
# v6: player_inventory (#449, D-065)
if snapshot.has("player_inventory") and snapshot.player_inventory is Array:
player_inventory = snapshot.player_inventory
else:
player_inventory = []
# v7: current_dialogue (#434, D-061)
if snapshot.has("current_dialogue") and snapshot.current_dialogue is Dictionary:
current_dialogue = snapshot.current_dialogue
else:
current_dialogue = null
# v7: pending_recognitions (#431, D-059/D-060)
if snapshot.has("pending_recognitions") and snapshot.pending_recognitions is Array:
pending_recognitions = snapshot.pending_recognitions
else:
pending_recognitions = []
# v9: conversation_events (#535, D-078) — overheard NPC-to-NPC lines
if snapshot.has("conversation_events") and snapshot.conversation_events is Array:
conversation_events = snapshot.conversation_events
else:
conversation_events = []
# v9: conversation_ended (#535, D-078) — pairs whose conversation ended
if snapshot.has("conversation_ended") and snapshot.conversation_ended is Array:
conversation_ended = snapshot.conversation_ended
else:
conversation_ended = []
# v8: dialogue_response (#305, D-028) — NPC follow-up after player choice
if snapshot.has("dialogue_response") and snapshot.dialogue_response is Dictionary:
dialogue_response = snapshot.dialogue_response
else:
dialogue_response = null
# v8: gauntlet mode (#496) — room_id and gauntlet_mode
if snapshot.has("gauntlet_mode") and snapshot.gauntlet_mode == true:
gauntlet_mode = true
else:
gauntlet_mode = false
if snapshot.has("room_id") and snapshot.room_id is String:
room_id = snapshot.room_id
else:
room_id = null
# OQ-07 (#522): insert_active — defaults true (v0.1 always has insert).
# Server may send false for characters without an insert in future sprints.
if snapshot.has("insert_active") and snapshot.insert_active is bool:
insert_active = snapshot.insert_active
else:
insert_active = true
# #507: rng_seed — server sends current RNG seed for replay determinism.
# Field: "rng_seed" (u64 as integer). Null if server does not include it.
if snapshot.has("rng_seed"):
rng_seed = snapshot.rng_seed
else:
rng_seed = null
# D-018: Sound events from server — partition by range_category.
# #126: Medium → fog-edge directional indicators.
# #125: Close → positional 2D audio via AudioManager.
if snapshot.has("sound_events") and snapshot.sound_events is Array:
medium_sound_events = []
close_sound_events = []
for se in snapshot.sound_events:
if not se is Dictionary:
continue
var rc: String = se.get("range_category", "")
if rc == "Medium":
medium_sound_events.append(se)
elif rc == "Close":
close_sound_events.append(se)
else:
medium_sound_events = []
close_sound_events = []
# v10: discovered_pois (#151, D-013) — server sends POIs discovered by the player.
# Accepts "discovered_pois" or "poi_list" key — both map to the same client field.
# Only update if the field is present — absence means "no change since last tick".
if snapshot.has("discovered_pois") and snapshot.discovered_pois is Array:
discovered_pois = snapshot.discovered_pois
elif snapshot.has("poi_list") and snapshot.poi_list is Array:
discovered_pois = snapshot.poi_list
# v14: examine_result (#174, #242) — character-filtered observation from Examine verb.
if snapshot.has("examine_result") and snapshot.examine_result is Dictionary:
current_examine_result = snapshot.examine_result
else:
current_examine_result = null
# v15: save_result (#554, D-085) — one-shot save/load confirmation from server.
if snapshot.has("save_result") and snapshot.save_result is Dictionary:
save_result = snapshot.save_result
else:
save_result = null
# v18: debug_response (#580) — debug console command result.
if snapshot.has("debug_response") and snapshot.debug_response is Dictionary:
debug_response = snapshot.debug_response
else:
debug_response = null
# v20: settings_response (#627, D-138) — one-shot settings ack/dump from server.
# "full" kind → iterate settings array and hydrate matching fields.
if snapshot.has("settings_response") and snapshot.settings_response is Dictionary:
settings_response = snapshot.settings_response
var sr: Dictionary = snapshot.settings_response
if sr.get("kind") == "full":
var sr_settings: Variant = sr.get("settings")
if sr_settings is Array:
for entry in sr_settings:
if not entry is Dictionary:
continue
if entry.get("key") == "ai_dialogue.enabled":
var val: Variant = entry.get("value")
if val != null:
ai_enhanced_dialogue_enabled = _extract_bool_setting("ai_dialogue.enabled", val)
else:
settings_response = null
# #718: character_visual_descriptor — restored from server snapshot on save/load.
# Server persists the descriptor and includes it in ObserverSnapshot after load.
# Only update when field is present (null means no change).
if snapshot.has("character_visual_descriptor") and snapshot.character_visual_descriptor is Dictionary:
# load() returns a cached script — safe to call per-tick once the resource is in cache.
# Cannot use CharacterVisualDescriptor directly: autoloads compile before global class_names
# are registered, causing a parse-time "not declared" error.
var CVD := load("res://scripts/rendering/character_visual_descriptor.gd")
if CVD != null:
var restored = CVD.from_dict(snapshot.character_visual_descriptor)
if restored != null:
character_visual_descriptor = restored
# v14: player_knowledge (#264, D-041) — partial KG dump for journal panel.
# Only update when field is present (null means no change, server sends when KG changes).
if snapshot.has("player_knowledge") and snapshot.player_knowledge is Dictionary:
player_knowledge = snapshot.player_knowledge
# D-020/D-073 (#529): Server-authoritative zone_id for zone ambient crossfade.
# Prefer server-sent top-level value; fall back to client-side tile lookup until
# server populates top-level "zone_id" in ObserverSnapshot.
if snapshot.has("zone_id") and snapshot.zone_id is String:
# D-020: direct field assignment from server-authoritative snapshot.
current_zone_id = snapshot.zone_id
else:
# DEPRECATED fallback — client-side tile lookup. Remove when server sends
# top-level "zone_id" in ObserverSnapshot (D-020 violation: derives zone
# identity on the client via tile iteration). Server sends zone_id per
# VisibleTile but not as a top-level snapshot field.
var _tile_by_coord: Dictionary = {}
for vtile in visible_tiles:
if vtile is Dictionary and vtile.has("x") and vtile.has("y"):
_tile_by_coord[Vector2i(vtile.x, vtile.y)] = vtile
var player_pos_key := Vector2i(int(player_position.x), int(player_position.y))
var player_tile = _tile_by_coord.get(player_pos_key, null)
current_zone_id = player_tile.get("zone_id", "") if player_tile else ""
# v2: visible_tiles with visibility sectors
# Derives visible_positions when not explicitly provided (real server mode).
# #585: BoundaryWall tiles go to boundary_positions — rendered in fog but not marked explored.
if snapshot.has("visible_tiles") and snapshot.visible_tiles is Array and snapshot.visible_tiles.size() > 0:
visibility_sectors.clear()
var has_explicit_positions := snapshot.has("visible_positions")
if not has_explicit_positions:
visible_positions.clear()
boundary_positions.clear()
for vtile in snapshot.visible_tiles:
if not vtile is Dictionary or not vtile.has("x") or not vtile.has("y"):
continue
var pos := Vector2i(vtile.x, vtile.y)
var vis_sector: String = vtile.get("visibility", "")
if vtile.has("visibility"):
visibility_sectors[pos] = vis_sector
# #585: BoundaryWall tiles are margin tiles visible through fog but not persistently
# explored — they don't update the player's exploration memory when they leave LOS.
if vis_sector == "BoundaryWall":
boundary_positions[pos] = true
elif not has_explicit_positions:
visible_positions[pos] = true
# -- Helpers ------------------------------------------------------------------
## Extract a bool from a tagged-union {"Bool": true} or plain bool value.
## Handles both serde encoding styles; emits push_warning on unrecognised format.
static func _extract_bool_setting(key: String, val: Variant) -> bool:
if val is bool:
return val
if val is Dictionary and val.has("Bool"):
return bool(val["Bool"])
push_warning("GameState: unexpected type for setting '%s': %s" % [key, str(val)])
return false
# Autoload parse-order: class_name types are not registered when autoloads compile.
# load() returns the cached resource after the first call — essentially free per-tick.
var SH := load("res://scripts/snapshot_handler.gd")
SH.apply(snapshot)
+146
View File
@@ -0,0 +1,146 @@
extends Node
## HUD layer manager (D-170).
##
## Controls z-ordering and layout mode for HUD elements. Nothing gets hidden —
## fullscreen apps render on top of gameplay, insert-mode apps share the screen.
##
## Modes:
## MODE_GAMEPLAY — default z-level, normal layout
## MODE_INSERT — small overlay alongside gameplay (e.g. minimap-sized star map)
## MODE_FULLSCREEN — takes over the screen, gameplay renders behind
##
## Groups use hierarchical paths:
## "gameplay" — HUD status, minimap, prompts, stance
## "implant/map/starchart" — star map navigator
## "implant/wiki/gttr" — Drifter's Guide reader
## "implant/journal" — knowledge journal
##
## Usage:
## HudGroups.register(self, "implant/map/starchart")
## HudGroups.open_app("implant/map/starchart") # fullscreen by default
## HudGroups.open_app("implant/map/starchart", HudGroups.MODE_INSERT)
## HudGroups.close_app()
## HudGroups.toggle_app("implant/map/starchart")
## Emitted when an app opens, closes, or changes mode.
## mode is a HudGroups.Mode enum value.
signal app_changed(app_path: String, mode: int)
## Emitted when gameplay rendering should pause or resume.
## Fullscreen implant apps occlude gameplay — expensive renderers (world,
## fog, entities) should skip draw calls while this is true.
signal gameplay_occluded(occluded: bool)
enum Mode { GAMEPLAY, INSERT, FULLSCREEN }
## Z-index values for each mode. Gameplay is the base layer.
const Z_GAMEPLAY: int = 0
const Z_INSERT: int = 10
const Z_FULLSCREEN: int = 20
const Z_MODAL: int = 30
var _groups: Dictionary = {} # group_path -> Array[CanvasItem]
var _active_app: String = "" # currently focused implant app ("" = none)
var _active_mode: Mode = Mode.GAMEPLAY
func register(node: CanvasItem, group: String) -> void:
if not _groups.has(group):
_groups[group] = []
if node not in _groups[group]:
_groups[group].append(node)
# Apply current z-level
_apply_z(node, group)
func unregister(node: CanvasItem, group: String) -> void:
if _groups.has(group):
_groups[group].erase(node)
## Open an implant app in fullscreen (default) or insert mode.
func open_app(app: String, mode: Mode = Mode.FULLSCREEN) -> void:
# Close previous app if different
if not _active_app.is_empty() and _active_app != app:
_set_group_z(_active_app, Z_GAMEPLAY)
app_changed.emit(_active_app, Mode.GAMEPLAY)
_active_app = app
_active_mode = mode
# Set z-levels based on mode
var was_occluded := _active_mode == Mode.FULLSCREEN and not _active_app.is_empty()
if mode == Mode.FULLSCREEN:
_set_group_z("gameplay", Z_GAMEPLAY)
_set_group_z(app, Z_FULLSCREEN)
elif mode == Mode.INSERT:
_set_group_z("gameplay", Z_GAMEPLAY)
_set_group_z(app, Z_INSERT)
app_changed.emit(app, mode)
# Notify renderers about occlusion state change
var now_occluded := mode == Mode.FULLSCREEN
if now_occluded != was_occluded:
gameplay_occluded.emit(now_occluded)
## Close the current app. Returns everything to gameplay z-level.
func close_app() -> void:
var was_fullscreen := _active_mode == Mode.FULLSCREEN and not _active_app.is_empty()
if not _active_app.is_empty():
_set_group_z(_active_app, Z_GAMEPLAY)
app_changed.emit(_active_app, Mode.GAMEPLAY)
_active_app = ""
_active_mode = Mode.GAMEPLAY
_set_group_z("gameplay", Z_GAMEPLAY)
if was_fullscreen:
gameplay_occluded.emit(false)
## Toggle an app. If open, close it. If closed or different app, open it.
func toggle_app(app: String, mode: Mode = Mode.FULLSCREEN) -> void:
if _active_app == app:
close_app()
else:
open_app(app, mode)
## Check if a specific app is currently open.
func is_app_active(app: String) -> bool:
return _active_app == app
## Check if any implant app is open.
func is_implant_active() -> bool:
return not _active_app.is_empty()
## Get the currently active app path, or "" if none.
func get_active_app() -> String:
return _active_app
## Get the current mode of the active app.
func get_active_mode() -> Mode:
return _active_mode
func _apply_z(node: CanvasItem, group: String) -> void:
if group == "gameplay":
node.z_index = Z_GAMEPLAY
elif group.begins_with("implant/"):
if group == _active_app:
node.z_index = Z_FULLSCREEN if _active_mode == Mode.FULLSCREEN else Z_INSERT
else:
node.z_index = Z_GAMEPLAY
elif group == "modal":
node.z_index = Z_MODAL
func _set_group_z(group: String, z: int) -> void:
if not _groups.has(group):
return
for node: CanvasItem in _groups[group]:
if is_instance_valid(node):
node.z_index = z
+101 -53
View File
@@ -14,10 +14,21 @@ extends Node
# Server cooldown is authoritative, but the client throttle prevents
# flooding and gives correct movement feel in test mode.
enum Action {
MOVE_NORTH, MOVE_NORTHEAST, MOVE_EAST, MOVE_SOUTHEAST,
MOVE_SOUTH, MOVE_SOUTHWEST, MOVE_WEST, MOVE_NORTHWEST,
INTERACT, USE_PERCEPTION_MODE, OPEN_MENU, PAUSE, UNPAUSE,
TOGGLE_STANCE_UP, TOGGLE_STANCE_DOWN,
MOVE_NORTH,
MOVE_NORTHEAST,
MOVE_EAST,
MOVE_SOUTHEAST,
MOVE_SOUTH,
MOVE_SOUTHWEST,
MOVE_WEST,
MOVE_NORTHWEST,
INTERACT,
USE_PERCEPTION_MODE,
OPEN_MENU,
PAUSE,
UNPAUSE,
TOGGLE_STANCE_UP,
TOGGLE_STANCE_DOWN,
BUG_REPORT, # #495: F12 WRONG button — client-only, not sent to server
OPEN_JOURNAL, # #264: J key — toggle knowledge journal panel, client-only
SET_FACING, # D-054: facing octant update (no movement)
@@ -25,9 +36,18 @@ enum Action {
SAVE_GAME, # #554: F5 quicksave — sends SaveGame to server with save path
LOAD_GAME, # #554: F6 quickload — sends LoadGame to server with save path
DEBUG_COMMAND, # #581: debug console command dispatch — sends DebugCommandKind to server
CHANGE_SETTINGS, # #646: persist a setting to server SQLite — sends {key, value} to server
REQUEST_ALL_SETTINGS, # #646: request full settings dump from server after handshake (unit variant)
DELETE_SETTING, # #646: delete a setting by key from server SQLite (struct variant)
CHANGE_SETTINGS, # #646: persist a setting to server SQLite — sends {key, value} to server
REQUEST_ALL_SETTINGS, # #646: request full settings dump from server after handshake (unit variant)
DELETE_SETTING, # #646: delete a setting by key from server SQLite (struct variant)
}
# Minimum milliseconds between movement commands, per stance.
# Tuned so Walk feels like walking, Sprint feels fast but readable.
const MOVE_INTERVAL_MS := {
"Sprint": 200, # 5/sec — fast but trackable
"Walk": 400, # 2.5/sec — comfortable walking pace
"Careful": 600, # ~1.7/sec — deliberate, scanning
"Crouch": 800, # 1.25/sec — creeping
}
var input_queue: Array[Dictionary] = []
@@ -35,17 +55,8 @@ var input_queue: Array[Dictionary] = []
# D-054: Client-side facing angle (radians). 0=East, -PI/2=North, PI/2=South.
# Updated every frame from mouse position. EntityRenderer reads this for indicator.
var facing_angle: float = -PI / 2.0 # Default: North
var facing_octant: String = "North" # Derived from facing_angle
var facing_octant: String = "North" # Derived from facing_angle
var _last_sent_octant: String = "North" # Track to avoid redundant sends
# Minimum milliseconds between movement commands, per stance.
# Tuned so Walk feels like walking, Sprint feels fast but readable.
const MOVE_INTERVAL_MS := {
"Sprint": 200, # 5/sec — fast but trackable
"Walk": 400, # 2.5/sec — comfortable walking pace
"Careful": 600, # ~1.7/sec — deliberate, scanning
"Crouch": 800, # 1.25/sec — creeping
}
var _last_move_msec: int = 0
@@ -63,11 +74,16 @@ func _process(_delta: float) -> void:
# D-054: Send facing octant to server when it changes (even without movement)
if facing_octant != _last_sent_octant:
_last_sent_octant = facing_octant
input_queue.append({
"action": Action.SET_FACING,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"facing": facing_octant},
})
(
input_queue
. append(
{
"action": Action.SET_FACING,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"facing": facing_octant},
}
)
)
# Poll held WASD keys
var raw_dir := Vector2i.ZERO
@@ -88,10 +104,15 @@ func _process(_delta: float) -> void:
# D-054: Transform WASD input relative to mouse facing
var world_dir := _wasd_to_world_dir(raw_dir)
var action: Action = _dir_to_action(world_dir)
input_queue.append({
"action": action,
"timestamp_msec": now,
})
(
input_queue
. append(
{
"action": action,
"timestamp_msec": now,
}
)
)
# Discrete actions: fire once on key press (not held).
@@ -197,15 +218,24 @@ static func _snap_to_octant_dir(dir: Vector2) -> Vector2i:
# Quantize to nearest 45° (PI/4)
var octant := roundi(angle / (PI / 4.0))
match octant:
0: return Vector2i(1, 0) # East
1: return Vector2i(1, 1) # Southeast
2, -6: return Vector2i(0, 1) # South
3, -5: return Vector2i(-1, 1) # Southwest
4, -4: return Vector2i(-1, 0) # West
-3, 5: return Vector2i(-1, -1) # Northwest
-2: return Vector2i(0, -1) # North
-1: return Vector2i(1, -1) # Northeast
_: return Vector2i.ZERO
0:
return Vector2i(1, 0) # East
1:
return Vector2i(1, 1) # Southeast
2, -6:
return Vector2i(0, 1) # South
3, -5:
return Vector2i(-1, 1) # Southwest
4, -4:
return Vector2i(-1, 0) # West
-3, 5:
return Vector2i(-1, -1) # Northwest
-2:
return Vector2i(0, -1) # North
-1:
return Vector2i(1, -1) # Northeast
_:
return Vector2i.ZERO
# D-054: Convert a facing angle (radians) to the nearest octant name.
@@ -213,27 +243,45 @@ static func _snap_to_octant_dir(dir: Vector2) -> Vector2i:
static func _angle_to_octant(angle: float) -> String:
var octant := roundi(angle / (PI / 4.0))
match octant:
0: return "East"
1: return "Southeast"
2, -6: return "South"
3, -5: return "Southwest"
4, -4: return "West"
-3, 5: return "Northwest"
-2: return "North"
-1: return "Northeast"
_: return "East"
0:
return "East"
1:
return "Southeast"
2, -6:
return "South"
3, -5:
return "Southwest"
4, -4:
return "West"
-3, 5:
return "Northwest"
-2:
return "North"
-1:
return "Northeast"
_:
return "East"
# Map a direction vector to the corresponding movement Action.
# Handles all 8 directions via composite W+D, W+A, etc.
static func _dir_to_action(dir: Vector2i) -> Action:
match dir:
Vector2i(0, -1): return Action.MOVE_NORTH
Vector2i(1, -1): return Action.MOVE_NORTHEAST
Vector2i(1, 0): return Action.MOVE_EAST
Vector2i(1, 1): return Action.MOVE_SOUTHEAST
Vector2i(0, 1): return Action.MOVE_SOUTH
Vector2i(-1, 1): return Action.MOVE_SOUTHWEST
Vector2i(-1, 0): return Action.MOVE_WEST
Vector2i(-1, -1): return Action.MOVE_NORTHWEST
_: return Action.MOVE_NORTH
Vector2i(0, -1):
return Action.MOVE_NORTH
Vector2i(1, -1):
return Action.MOVE_NORTHEAST
Vector2i(1, 0):
return Action.MOVE_EAST
Vector2i(1, 1):
return Action.MOVE_SOUTHEAST
Vector2i(0, 1):
return Action.MOVE_SOUTH
Vector2i(-1, 1):
return Action.MOVE_SOUTHWEST
Vector2i(-1, 0):
return Action.MOVE_WEST
Vector2i(-1, -1):
return Action.MOVE_NORTHWEST
_:
return Action.MOVE_NORTH
+76 -76
View File
@@ -16,19 +16,28 @@ extends Node
## Paths: Read-once OS path constants, populated in _ready().
## Diag: get_diagnostics() — flat dict of all properties for bug reports.
# -- Power profile ------------------------------------------------------------
## High-level power classification. POWER_SAVER reserved for future OS API.
enum PowerProfile {
FULL = 0, # Plugged in (charged, charging, or no battery) — no restrictions
BATTERY = 1, # On battery — AI inference should be suspended per D-138 §8 Layer 3
POWER_SAVER = 2 # System-level power-saver mode (future: no cross-platform API yet)
}
## Emitted when the detected power profile changes.
signal power_profile_changed(old_profile: int, new_profile: int)
## High-level power classification. POWER_SAVER reserved for future OS API.
enum PowerProfile {
FULL = 0, ## Plugged in — no restrictions
BATTERY = 1, ## On battery — suspend AI inference per D-138 §8 Layer 3
POWER_SAVER = 2, ## System-level power-saver mode (future)
}
## How often (seconds) to re-poll OS for power state changes.
const POWER_POLL_INTERVAL := 30.0
# OS power_state integer constants (Godot 4 — same values as POWERSTATE_* enum).
const _POWER_STATE_UNKNOWN := 0
const _POWER_STATE_ON_BATTERY := 1
const _POWER_STATE_NO_BATTERY := 2
const _POWER_STATE_CHARGING := 3
const _POWER_STATE_CHARGED := 4
## Current power profile. Updated by the 30-second poll timer.
var power_profile: PowerProfile = PowerProfile.FULL
@@ -38,17 +47,6 @@ var raw_power_state: int = 0
## Battery charge percentage (0100). -1 if not available or not on battery.
var battery_percent: int = -1
## How often (seconds) to re-poll OS for power state changes.
const POWER_POLL_INTERVAL := 30.0
# OS power_state integer constants (Godot 4 — same values as POWERSTATE_* enum).
const _POWER_STATE_UNKNOWN := 0
const _POWER_STATE_ON_BATTERY := 1
const _POWER_STATE_NO_BATTERY := 2
const _POWER_STATE_CHARGING := 3
const _POWER_STATE_CHARGED := 4
# -- Memory -------------------------------------------------------------------
## Free physical RAM in megabytes. Call refresh_memory() before reading if staleness matters.
@@ -57,7 +55,6 @@ var free_memory_mb: float = 0.0
## Total physical RAM in megabytes. Populated once in _ready(); doesn't change at runtime.
var total_memory_mb: float = 0.0
# -- CPU ----------------------------------------------------------------------
## Human-readable processor name (e.g. "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz").
@@ -66,7 +63,6 @@ var cpu_name: String = ""
## Number of logical CPU cores reported by the OS.
var cpu_logical_cores: int = 0
# -- GPU ----------------------------------------------------------------------
## GPU display name (e.g. "NVIDIA GeForce RTX 3080").
@@ -84,7 +80,6 @@ var gpu_type: String = "other"
## Low-level driver info strings from the OS (may be empty on some platforms).
var gpu_driver_info: PackedStringArray = PackedStringArray()
# -- Platform identity --------------------------------------------------------
## OS name reported by Godot (e.g. "Linux", "Windows", "macOS").
@@ -99,7 +94,6 @@ var distribution: String = ""
## True if the application is running inside a sandbox (Flatpak, Snap, macOS sandbox, etc.).
var is_sandboxed: bool = false
# -- Display ------------------------------------------------------------------
## Number of connected screens.
@@ -117,7 +111,6 @@ var screen_refresh_rate: float = 60.0
## UI scale factor. Uses OS-reported scale on macOS; falls back to dpi / 96.0 elsewhere.
var display_scale: float = 1.0
# -- Locale -------------------------------------------------------------------
## Full locale string (e.g. "en_US").
@@ -126,7 +119,6 @@ var locale: String = ""
## Language portion of the locale (e.g. "en").
var locale_language: String = ""
# -- File paths ---------------------------------------------------------------
## Base user data directory (user://).
@@ -150,9 +142,9 @@ var cache_dir: String = ""
## Directory where the bundled Gemma 2 model lives (derived from install_dir).
var model_dir: String = ""
# -- Lifecycle ----------------------------------------------------------------
func _ready() -> void:
_init_paths()
_init_hardware()
@@ -167,12 +159,12 @@ func _ready() -> void:
func _init_paths() -> void:
user_data_dir = OS.get_user_data_dir()
config_dir = user_data_dir
user_data_dir = OS.get_user_data_dir()
config_dir = user_data_dir
benchmark_cache_path = "user://ai-dialogue-config.json"
executable_path = OS.get_executable_path()
install_dir = executable_path.get_base_dir()
model_dir = install_dir + "/models"
executable_path = OS.get_executable_path()
install_dir = executable_path.get_base_dir()
model_dir = install_dir + "/models"
# get_cache_dir() may not exist on all Godot builds — use callv for safety.
var os_cache: String = ""
if OS.has_method("get_cache_dir"):
@@ -184,12 +176,12 @@ func _init_paths() -> void:
func _init_hardware() -> void:
# -- CPU
cpu_name = OS.get_processor_name()
cpu_name = OS.get_processor_name()
cpu_logical_cores = OS.get_processor_count()
# -- GPU (guarded: RenderingServer methods may return empty in headless mode)
gpu_name = RenderingServer.get_video_adapter_name()
gpu_vendor = RenderingServer.get_video_adapter_vendor()
gpu_name = RenderingServer.get_video_adapter_name()
gpu_vendor = RenderingServer.get_video_adapter_vendor()
gpu_api_version = RenderingServer.get_video_adapter_api_version()
gpu_driver_info = OS.get_video_adapter_driver_info()
if RenderingServer.has_method("get_video_adapter_type"):
@@ -198,7 +190,7 @@ func _init_hardware() -> void:
# -- Platform identity
platform_name = OS.get_name()
os_version = OS.get_version()
os_version = OS.get_version()
if OS.has_method("get_distribution_name"):
var dist: Variant = OS.callv("get_distribution_name", [])
if dist is String:
@@ -207,14 +199,14 @@ func _init_hardware() -> void:
# -- Display
screen_count = DisplayServer.get_screen_count()
screen_size = DisplayServer.screen_get_size()
screen_dpi = DisplayServer.screen_get_dpi()
screen_size = DisplayServer.screen_get_size()
screen_dpi = DisplayServer.screen_get_dpi()
var raw_rate: float = DisplayServer.screen_get_refresh_rate()
screen_refresh_rate = raw_rate if raw_rate >= 0.0 else 60.0
display_scale = _compute_display_scale()
# -- Locale
locale = OS.get_locale()
locale = OS.get_locale()
locale_language = OS.get_locale_language()
@@ -222,11 +214,16 @@ func _init_hardware() -> void:
## Values: 0=OTHER, 1=INTEGRATED, 2=DISCRETE, 3=VIRTUAL, 4=CPU.
static func _map_adapter_type(adapter_type: int) -> String:
match adapter_type:
1: return "integrated"
2: return "discrete"
3: return "virtual"
4: return "cpu"
_: return "other"
1:
return "integrated"
2:
return "discrete"
3:
return "virtual"
4:
return "cpu"
_:
return "other"
## Compute display scale for the primary screen.
@@ -241,17 +238,19 @@ func _compute_display_scale() -> float:
# -- Memory API ---------------------------------------------------------------
## Refresh free/total memory readings from the OS. Call before read if freshness matters.
func refresh_memory() -> void:
var mem := OS.get_memory_info()
# "available" = Linux MemAvailable / Windows ullAvailPhys (includes reclaimable pages).
# Fall back to "free" on platforms that don't provide "available".
free_memory_mb = float(mem.get("available", mem.get("free", 0))) / (1024.0 * 1024.0)
free_memory_mb = float(mem.get("available", mem.get("free", 0))) / (1024.0 * 1024.0)
total_memory_mb = float(mem.get("physical", 0)) / (1024.0 * 1024.0)
# -- Power API ----------------------------------------------------------------
## Classify an OS power_state integer into a human-readable string.
## 1 (ON_BATTERY) → "battery", 2/3/4 (plugged) → "plugged", 0 → "unknown".
static func classify_power_state(power_state: int) -> String:
@@ -293,9 +292,9 @@ func _poll_power() -> void:
if raw_power_state == _POWER_STATE_ON_BATTERY:
battery_percent = int(info.get("percent", -1))
var new_profile: PowerProfile = PowerProfile.BATTERY \
if raw_power_state == _POWER_STATE_ON_BATTERY \
else PowerProfile.FULL
var new_profile: PowerProfile = (
PowerProfile.BATTERY if raw_power_state == _POWER_STATE_ON_BATTERY else PowerProfile.FULL
)
if new_profile != power_profile:
var old_profile := power_profile
power_profile = new_profile
@@ -304,45 +303,46 @@ func _poll_power() -> void:
# -- Diagnostics --------------------------------------------------------------
## Returns all platform properties as a flat dictionary for inclusion in bug reports.
func get_diagnostics() -> Dictionary:
return {
# Power
"power_profile": int(power_profile),
"raw_power_state": raw_power_state,
"battery_percent": battery_percent,
"power_profile": int(power_profile),
"raw_power_state": raw_power_state,
"battery_percent": battery_percent,
# Memory
"free_memory_mb": free_memory_mb,
"total_memory_mb": total_memory_mb,
"free_memory_mb": free_memory_mb,
"total_memory_mb": total_memory_mb,
# CPU
"cpu_name": cpu_name,
"cpu_logical_cores": cpu_logical_cores,
"cpu_name": cpu_name,
"cpu_logical_cores": cpu_logical_cores,
# GPU
"gpu_name": gpu_name,
"gpu_vendor": gpu_vendor,
"gpu_api_version": gpu_api_version,
"gpu_type": gpu_type,
"gpu_driver_info": Array(gpu_driver_info),
"gpu_name": gpu_name,
"gpu_vendor": gpu_vendor,
"gpu_api_version": gpu_api_version,
"gpu_type": gpu_type,
"gpu_driver_info": Array(gpu_driver_info),
# Platform
"platform_name": platform_name,
"os_version": os_version,
"distribution": distribution,
"is_sandboxed": is_sandboxed,
"platform_name": platform_name,
"os_version": os_version,
"distribution": distribution,
"is_sandboxed": is_sandboxed,
# Display
"screen_count": screen_count,
"screen_size": {"x": screen_size.x, "y": screen_size.y},
"screen_dpi": screen_dpi,
"screen_count": screen_count,
"screen_size": {"x": screen_size.x, "y": screen_size.y},
"screen_dpi": screen_dpi,
"screen_refresh_rate": screen_refresh_rate,
"display_scale": display_scale,
"display_scale": display_scale,
# Locale
"locale": locale,
"locale_language": locale_language,
"locale": locale,
"locale_language": locale_language,
# Paths
"user_data_dir": user_data_dir,
"config_dir": config_dir,
"benchmark_cache_path": benchmark_cache_path,
"install_dir": install_dir,
"executable_path": executable_path,
"cache_dir": cache_dir,
"model_dir": model_dir,
"user_data_dir": user_data_dir,
"config_dir": config_dir,
"benchmark_cache_path": benchmark_cache_path,
"install_dir": install_dir,
"executable_path": executable_path,
"cache_dir": cache_dir,
"model_dir": model_dir,
}
+49 -20
View File
@@ -17,18 +17,26 @@ var _quit_dialog: ConfirmationDialog = null
## Returns the new game-id string.
func new_game() -> String:
var now := Time.get_datetime_dict_from_system()
var timestamp := "%04d%02d%02d-%02d%02d%02d" % [
now.year, now.month, now.day,
now.hour, now.minute, now.second,
]
var timestamp := (
"%04d%02d%02d-%02d%02d%02d"
% [
now.year,
now.month,
now.day,
now.hour,
now.minute,
now.second,
]
)
var rng := RandomNumberGenerator.new()
var hex_seed := "%06x" % (rng.randi() & 0xFFFFFF)
var game_id := "%s-%s" % [timestamp, hex_seed]
var save_path := SAVES_DIR + game_id + "/"
var err := DirAccess.make_dir_recursive_absolute(save_path)
if err != OK:
push_error("SessionManager: failed to create save dir %s: %s" % [
save_path, error_string(err)])
push_error(
"SessionManager: failed to create save dir %s: %s" % [save_path, error_string(err)]
)
return ""
GameState.current_game_id = game_id
@@ -71,15 +79,21 @@ func list_game_dirs() -> Array:
var mtime: int = 0
if newest_save != "":
mtime = FileAccess.get_modified_time(dir_path + newest_save)
results.append({
"game_id": entry,
"modified_time": mtime,
"newest_save": newest_save,
})
(
results
. append(
{
"game_id": entry,
"modified_time": mtime,
"newest_save": newest_save,
}
)
)
entry = dir.get_next()
dir.list_dir_end()
results.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return a.modified_time > b.modified_time)
results.sort_custom(
func(a: Dictionary, b: Dictionary) -> bool: return a.modified_time > b.modified_time
)
return results
@@ -105,11 +119,16 @@ func _do_quit_to_menu() -> void:
# SimBridge._process() flushes the outbound buffer before teardown.
if not GameState.current_game_id.is_empty():
var path := "user://saves/" + GameState.current_game_id + "/quicksave.sav"
SimBridge.send_input({
"action": InputMapper.Action.SAVE_GAME,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"path": path},
})
(
SimBridge
. send_input(
{
"action": InputMapper.Action.SAVE_GAME,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"path": path},
}
)
)
GameState.current_game_id = ""
_navigate_to_menu.call_deferred()
else:
@@ -131,7 +150,12 @@ func _cleanup_quit_dialog() -> void:
func _write_seed_file(save_path: String, seed: int) -> void:
var file := FileAccess.open(save_path + "world_seed", FileAccess.WRITE)
if file == null:
push_error("SessionManager: failed to write seed file: %s" % error_string(FileAccess.get_open_error()))
push_error(
(
"SessionManager: failed to write seed file: %s"
% error_string(FileAccess.get_open_error())
)
)
return
file.store_64(seed)
@@ -152,7 +176,12 @@ func save_character_archetype(game_id: String, archetype: String) -> void:
var save_path := SAVES_DIR + game_id + "/"
var file := FileAccess.open(save_path + "character.txt", FileAccess.WRITE)
if file == null:
push_error("SessionManager: failed to write character.txt: %s" % error_string(FileAccess.get_open_error()))
push_error(
(
"SessionManager: failed to write character.txt: %s"
% error_string(FileAccess.get_open_error())
)
)
return
file.store_string(archetype)
+179 -97
View File
@@ -1,37 +1,85 @@
extends Node
# Connection states
enum ConnectionState { DISCONNECTED, CONNECTING, HANDSHAKING, CONNECTED, ERROR }
var state: ConnectionState = ConnectionState.DISCONNECTED
var test_mode: bool = OS.get_environment("SR_LIVE") != "1" # SR_LIVE=1 connects to real server
# Type is TestHarness — untyped to avoid autoload parse-order issue.
var harness = null # Test simulation (D-020: game logic lives outside production client)
var _last_snapshot: Variant = null # Most recent decoded snapshot (consumed by poll_snapshot)
var _outbound_buffer: Array[Dictionary] = [] # Raw inputs awaiting batch encode + transport
# Transport layer (non-test mode)
var _bridge: LocalBridge = null
var _server: ServerProcess = null
var server_port: int = 9876 # Default matches server's default bind address
var server_path: String = "" # Path to server binary — set before connect_to_sim()
# Connection retry state — handles server startup delay (Critical fix #1)
const MAX_CONNECT_RETRIES: int = 20 # ~2 seconds at 60fps with 100ms delay
const CONNECT_RETRY_INTERVAL: float = 0.1 # Seconds between retry attempts
var _connect_retries: int = 0
var _retry_timer: float = 0.0
# Handshake state (#556)
const HANDSHAKE_TIMEOUT_USEC: int = 5_000_000 # 5 seconds
var _handshake_start_usec: int = 0
# Signals
signal connection_state_changed(old_state: ConnectionState, new_state: ConnectionState)
signal snapshot_received(snapshot: Dictionary)
signal handshake_complete(protocol_version: int)
signal handshake_failed(reason: String)
# Connection states
enum ConnectionState { DISCONNECTED, CONNECTING, HANDSHAKING, CONNECTED, ERROR }
# Connection retry state — handles server startup delay (Critical fix #1)
const MAX_CONNECT_RETRIES: int = 20 # ~2 seconds at 60fps with 100ms delay
const CONNECT_RETRY_INTERVAL: float = 0.1 # Seconds between retry attempts
# Handshake state (#556)
const HANDSHAKE_TIMEOUT_USEC: int = 5_000_000 # 5 seconds
var state: ConnectionState = ConnectionState.DISCONNECTED
var test_mode: bool = OS.get_environment("SR_LIVE") != "1" # SR_LIVE=1 connects to real server
# Type is TestHarness — untyped to avoid autoload parse-order issue.
var harness = null # Test simulation (D-020: game logic lives outside production client)
var server_port: int = 9876 # Default matches server's default bind address
var server_path: String = "" # Path to server binary — set before connect_to_sim()
var _last_snapshot: Variant = null # Most recent decoded snapshot (consumed by poll_snapshot)
var _outbound_buffer: Array[Dictionary] = [] # Raw inputs awaiting batch encode + transport
# Transport layer (non-test mode)
var _bridge: LocalBridge = null
var _server: ServerProcess = null
var _connect_retries: int = 0
var _retry_timer: float = 0.0
var _handshake_start_usec: int = 0
var _test_tick: int:
get:
return harness.tick if harness else 0
set(v):
if harness:
harness.tick = v
var _test_player_pos: Vector2i:
get:
return harness.player_pos if harness else Vector2i.ZERO
set(v):
if harness:
harness.player_pos = v
var _test_facing: String:
get:
return harness.facing if harness else "North"
set(v):
if harness:
harness.facing = v
var _test_in_dialogue: bool:
get:
return harness.in_dialogue if harness else false
set(v):
if harness:
harness.in_dialogue = v
var _test_gauntlet_mode: bool:
get:
return harness.gauntlet_mode if harness else false
set(v):
if harness:
harness.gauntlet_mode = v
var _test_npc_relationship: String:
get:
return harness.npc_relationship if harness else "Unknown"
set(v):
if harness:
harness.npc_relationship = v
var _test_input_queue: Array:
get:
return harness.input_queue if harness else []
func _ready() -> void:
if test_mode:
harness = load("res://scripts/protocol/test_harness.gd").new()
@@ -40,51 +88,23 @@ func _ready() -> void:
# -- Test mode proxy API (backward compat for 13+ test files) ------------------
func reset_test_state() -> void:
if harness: harness.reset()
if harness:
harness.reset()
func _test_snapshot() -> Dictionary:
return harness.snapshot()
func _test_has_los(from: Vector2i, to: Vector2i) -> bool:
return harness.has_los(from, to)
var _test_tick: int:
get: return harness.tick if harness else 0
set(v):
if harness: harness.tick = v
var _test_player_pos: Vector2i:
get: return harness.player_pos if harness else Vector2i.ZERO
set(v):
if harness: harness.player_pos = v
var _test_facing: String:
get: return harness.facing if harness else "North"
set(v):
if harness: harness.facing = v
var _test_in_dialogue: bool:
get: return harness.in_dialogue if harness else false
set(v):
if harness: harness.in_dialogue = v
var _test_gauntlet_mode: bool:
get: return harness.gauntlet_mode if harness else false
set(v):
if harness: harness.gauntlet_mode = v
var _test_npc_relationship: String:
get: return harness.npc_relationship if harness else "Unknown"
set(v):
if harness: harness.npc_relationship = v
var _test_input_queue: Array:
get: return harness.input_queue if harness else []
# -- Connection lifecycle ------------------------------------------------------
# Change connection state and emit signal
func _set_state(new_state: ConnectionState) -> void:
if state != new_state:
@@ -92,6 +112,7 @@ func _set_state(new_state: ConnectionState) -> void:
state = new_state
connection_state_changed.emit(old_state, new_state)
# Connect to simulation server.
# In test mode, immediately transitions to CONNECTED.
# In live mode, spawns server subprocess and defers TCP connection to _process()
@@ -123,6 +144,7 @@ func connect_to_sim() -> void:
_retry_timer = 0.0
_bridge = null
# Disconnect from simulation server
func disconnect_from_sim() -> void:
if _bridge != null:
@@ -134,17 +156,23 @@ func disconnect_from_sim() -> void:
_connect_retries = 0
_set_state(ConnectionState.DISCONNECTED)
# Attempt TCP connection. Called from _process() during CONNECTING state.
func _try_connect() -> void:
_bridge = LocalBridge.new()
var err := _bridge.connect_to_server("127.0.0.1", server_port)
if err != OK:
push_warning("SimBridge: TCP connect attempt %d/%d failed: %s" % [
_connect_retries + 1, MAX_CONNECT_RETRIES, error_string(err)])
push_warning(
(
"SimBridge: TCP connect attempt %d/%d failed: %s"
% [_connect_retries + 1, MAX_CONNECT_RETRIES, error_string(err)]
)
)
_bridge = null
# Poll transport layer every frame (non-test mode only)
func _process(delta: float) -> void:
func _process(delta: float) -> void: # gdlint:disable=max-returns
if test_mode:
return
@@ -156,7 +184,9 @@ func _process(delta: float) -> void:
_retry_timer = 0.0
_connect_retries += 1
if _connect_retries > MAX_CONNECT_RETRIES:
push_error("SimBridge: TCP connection failed after %d retries" % MAX_CONNECT_RETRIES)
push_error(
"SimBridge: TCP connection failed after %d retries" % MAX_CONNECT_RETRIES
)
_set_state(ConnectionState.ERROR)
return
_try_connect()
@@ -174,7 +204,9 @@ func _process(delta: float) -> void:
# Connection attempt failed — retry
_bridge = null
if _connect_retries >= MAX_CONNECT_RETRIES:
push_error("SimBridge: TCP connection failed after %d retries" % MAX_CONNECT_RETRIES)
push_error(
"SimBridge: TCP connection failed after %d retries" % MAX_CONNECT_RETRIES
)
_set_state(ConnectionState.ERROR)
StreamPeerTCP.STATUS_NONE:
_bridge = null # Reset and retry
@@ -189,7 +221,10 @@ func _process(delta: float) -> void:
# Check connection dropped during handshake
var bridge_status := _bridge.get_status()
if bridge_status == StreamPeerTCP.STATUS_ERROR or bridge_status == StreamPeerTCP.STATUS_NONE:
if (
bridge_status == StreamPeerTCP.STATUS_ERROR
or bridge_status == StreamPeerTCP.STATUS_NONE
):
var reason := "Connection dropped during handshake"
push_error("SimBridge: %s" % reason)
handshake_failed.emit(reason)
@@ -213,8 +248,11 @@ func _process(delta: float) -> void:
# Decode HandshakeMessage: { "protocol_version": N }
var decoded: Variant = Messagepack.decode(msg)
if decoded.status != null or not (decoded.value is Dictionary) \
or not decoded.value.has("protocol_version"):
if (
decoded.status != null
or not (decoded.value is Dictionary)
or not decoded.value.has("protocol_version")
):
var reason := "Handshake decode failed: malformed HandshakeMessage"
push_error("SimBridge: %s" % reason)
handshake_failed.emit(reason)
@@ -224,8 +262,10 @@ func _process(delta: float) -> void:
var server_version: int = decoded.value["protocol_version"]
if server_version != Protocol.PROTOCOL_VERSION:
var reason := "Protocol version mismatch: server=%d, client=%d" % [
server_version, Protocol.PROTOCOL_VERSION]
var reason := (
"Protocol version mismatch: server=%d, client=%d"
% [server_version, Protocol.PROTOCOL_VERSION]
)
push_error("SimBridge: %s" % reason)
handshake_failed.emit(reason)
_bridge.disconnect_from_server()
@@ -234,7 +274,11 @@ func _process(delta: float) -> void:
# Send startup message with world_seed and character appearance (#175, D-010/D-029, #718).
# Server blocks waiting for this before entering the tick loop.
var startup_bytes := Protocol.encode_startup_message(GameState.world_seed, GameState.character_archetype, GameState.character_visual_descriptor)
var startup_bytes := Protocol.encode_startup_message(
GameState.world_seed,
GameState.character_archetype,
GameState.character_visual_descriptor
)
if startup_bytes.size() > 0:
var send_err := _bridge.send_message(startup_bytes)
if send_err != OK:
@@ -256,10 +300,15 @@ func _process(delta: float) -> void:
_set_state(ConnectionState.CONNECTED)
# #646: Request full settings dump on connect — hydrates GameState.ai_enhanced_dialogue_enabled
# from server SQLite so the client reflects the authoritative persisted state (D-138).
_outbound_buffer.append({
"tick": 0,
"action_name": "RequestAllSettings",
})
(
_outbound_buffer
. append(
{
"tick": 0,
"action_name": "RequestAllSettings",
}
)
)
return
if _bridge == null:
@@ -286,7 +335,9 @@ func _process(delta: float) -> void:
if err != OK:
push_error("SimBridge: failed to send message: %s" % error_string(err))
else:
push_error("SimBridge: failed to batch-encode %d inputs (dropped)" % outbound.size())
push_error(
"SimBridge: failed to batch-encode %d inputs (dropped)" % outbound.size()
)
StreamPeerTCP.STATUS_CONNECTING:
pass # Should not happen in CONNECTED state
StreamPeerTCP.STATUS_ERROR:
@@ -301,6 +352,7 @@ func _process(delta: float) -> void:
# -- Input / snapshot ----------------------------------------------------------
# Send input to simulation server.
# player_input: Dictionary with "action" (int from InputMapper.Action enum) and "timestamp_msec".
# In test mode, inputs are delegated to the test harness.
@@ -327,13 +379,14 @@ func send_input(player_input: Dictionary) -> Error:
if action_name.is_empty():
return ERR_INVALID_PARAMETER
var tick: int = GameState.current_tick
var entry: Dictionary = { "tick": tick, "action_name": action_name }
var entry: Dictionary = {"tick": tick, "action_name": action_name}
var action_data: Variant = player_input.get("action_data")
if action_data != null:
entry["action_data"] = action_data
_outbound_buffer.append(entry)
return OK
# Poll for snapshot from simulation.
# In test mode delegates to test harness. In live mode, returns the last decoded snapshot.
func poll_snapshot() -> Variant:
@@ -353,6 +406,7 @@ func poll_snapshot() -> Variant:
return null
# Called by transport layer when raw bytes arrive from the server.
# Latest-wins for positional state (stale frames are worthless), but one-shot
# events (monologue, dialogue) are carried forward from overwritten snapshots
@@ -364,12 +418,21 @@ func receive_bytes(bytes: PackedByteArray) -> void:
return
if _last_snapshot != null:
# Carry forward one-shot events the client hasn't consumed yet.
if snapshot.get("current_monologue") == null and _last_snapshot.get("current_monologue") != null:
if (
snapshot.get("current_monologue") == null
and _last_snapshot.get("current_monologue") != null
):
snapshot["current_monologue"] = _last_snapshot["current_monologue"]
if snapshot.get("current_dialogue") == null and _last_snapshot.get("current_dialogue") != null:
if (
snapshot.get("current_dialogue") == null
and _last_snapshot.get("current_dialogue") != null
):
snapshot["current_dialogue"] = _last_snapshot["current_dialogue"]
# #535: Carry forward one-shot dialogue events (arrays merge, scalar falls through)
if snapshot.get("dialogue_response") == null and _last_snapshot.get("dialogue_response") != null:
if (
snapshot.get("dialogue_response") == null
and _last_snapshot.get("dialogue_response") != null
):
snapshot["dialogue_response"] = _last_snapshot["dialogue_response"]
var old_conv_events: Array = _last_snapshot.get("conversation_events", [])
if old_conv_events.size() > 0:
@@ -383,10 +446,14 @@ func receive_bytes(bytes: PackedByteArray) -> void:
if snapshot.get("save_result") == null and _last_snapshot.get("save_result") != null:
snapshot["save_result"] = _last_snapshot["save_result"]
# #646: Carry forward settings_response (one-shot, consumed by game_state apply_snapshot)
if snapshot.get("settings_response") == null and _last_snapshot.get("settings_response") != null:
if (
snapshot.get("settings_response") == null
and _last_snapshot.get("settings_response") != null
):
snapshot["settings_response"] = _last_snapshot["settings_response"]
_last_snapshot = snapshot
# Drain the outbound buffer. Returns raw input entries for batch encoding.
func drain_outbound() -> Array[Dictionary]:
var inputs = _outbound_buffer.duplicate()
@@ -396,24 +463,39 @@ func drain_outbound() -> Array[Dictionary]:
# -- Wire protocol mapping -----------------------------------------------------
# Map InputMapper.Action enum values to wire-format action names (matching Rust PlayerAction).
# OPEN_MENU is client-only — no Rust equivalent, not sent over the wire.
static func action_enum_to_wire(action: int) -> String:
match action:
InputMapper.Action.MOVE_NORTH: return "MoveNorth"
InputMapper.Action.MOVE_NORTHEAST: return "MoveNortheast"
InputMapper.Action.MOVE_EAST: return "MoveEast"
InputMapper.Action.MOVE_SOUTHEAST: return "MoveSoutheast"
InputMapper.Action.MOVE_SOUTH: return "MoveSouth"
InputMapper.Action.MOVE_SOUTHWEST: return "MoveSouthwest"
InputMapper.Action.MOVE_WEST: return "MoveWest"
InputMapper.Action.MOVE_NORTHWEST: return "MoveNorthwest"
InputMapper.Action.INTERACT: return "Interact"
InputMapper.Action.USE_PERCEPTION_MODE: return "UsePerceptionMode"
InputMapper.Action.PAUSE: return "Pause"
InputMapper.Action.UNPAUSE: return "Unpause"
InputMapper.Action.TOGGLE_STANCE_UP: return "ToggleStanceUp"
InputMapper.Action.TOGGLE_STANCE_DOWN: return "ToggleStanceDown"
InputMapper.Action.MOVE_NORTH:
return "MoveNorth"
InputMapper.Action.MOVE_NORTHEAST:
return "MoveNortheast"
InputMapper.Action.MOVE_EAST:
return "MoveEast"
InputMapper.Action.MOVE_SOUTHEAST:
return "MoveSoutheast"
InputMapper.Action.MOVE_SOUTH:
return "MoveSouth"
InputMapper.Action.MOVE_SOUTHWEST:
return "MoveSouthwest"
InputMapper.Action.MOVE_WEST:
return "MoveWest"
InputMapper.Action.MOVE_NORTHWEST:
return "MoveNorthwest"
InputMapper.Action.INTERACT:
return "Interact"
InputMapper.Action.USE_PERCEPTION_MODE:
return "UsePerceptionMode"
InputMapper.Action.PAUSE:
return "Pause"
InputMapper.Action.UNPAUSE:
return "Unpause"
InputMapper.Action.TOGGLE_STANCE_UP:
return "ToggleStanceUp"
InputMapper.Action.TOGGLE_STANCE_DOWN:
return "ToggleStanceDown"
InputMapper.Action.OPEN_MENU:
return "" # Client-only action, not part of wire protocol
InputMapper.Action.BUG_REPORT:
@@ -429,11 +511,11 @@ static func action_enum_to_wire(action: int) -> String:
InputMapper.Action.DEBUG_COMMAND:
return "DebugCommand" # #581: debug console command dispatch
InputMapper.Action.CHANGE_SETTINGS:
return "ChangeSettings" # #646: persist setting to server SQLite (D-138)
return "ChangeSettings" # #646: persist setting to server SQLite (D-138)
InputMapper.Action.REQUEST_ALL_SETTINGS:
return "RequestAllSettings" # #646: unit variant — server sends full settings dump
InputMapper.Action.DELETE_SETTING:
return "DeleteSetting" # #646: struct variant — delete setting by key
return "DeleteSetting" # #646: struct variant — delete setting by key
_:
push_warning("SimBridge: unknown action enum %s" % action)
return ""
+7
View File
@@ -9,9 +9,11 @@ const STRINGS_PATH: String = "res://data/ui-strings.yaml"
var _strings: Dictionary = {}
var _loaded: bool = false
func _ready() -> void:
_load_strings()
func _load_strings() -> void:
if not FileAccess.file_exists(STRINGS_PATH):
push_warning("UIStrings: file not found: %s" % STRINGS_PATH)
@@ -26,6 +28,7 @@ func _load_strings() -> void:
_loaded = true
print("UIStrings: loaded %d strings from %s" % [_strings.size(), STRINGS_PATH])
## Get a UI string by dotted key. Returns the key itself if not found.
func get_text(key: String) -> String:
if _strings.has(key):
@@ -33,20 +36,24 @@ func get_text(key: String) -> String:
push_warning("UIStrings: missing key '%s'" % key)
return key
## Check if a key exists.
func has_key(key: String) -> bool:
return _strings.has(key)
## Get all keys.
func get_all_keys() -> PackedStringArray:
return PackedStringArray(_strings.keys())
## Reload from disk (useful for hot-reload during development).
func reload() -> void:
_strings.clear()
_loaded = false
_load_strings()
## Parse YAML with arbitrary nesting depth.
## Returns flat Dictionary with dotted keys: { "section.sub.key": "value" }.
## Delegates to YamlParser.parse_flat() (#560).
+26 -14
View File
@@ -15,11 +15,11 @@ extends RefCounted
##
## Spec ref: D-030 (testability), checklist.schema.json (#497).
var _room_conditions: Array = [] # Conditions from per-room checklist
var _cross_conditions: Array = [] # Conditions from cross_room_checks.yaml
var _latched: Dictionary = {} # condition_id -> true (once met, stays met)
var _room_conditions: Array = [] # Conditions from per-room checklist
var _cross_conditions: Array = [] # Conditions from cross_room_checks.yaml
var _latched: Dictionary = {} # condition_id -> true (once met, stays met)
var _current_room_id: String = ""
var _content_base: String = "" # Absolute path to content/ directory
var _content_base: String = "" # Absolute path to content/ directory
var _loaded: bool = false
@@ -54,8 +54,7 @@ func load_room(room_id: String) -> void:
_latched = kept
# Load per-room checklist
var room_path := _content_base.path_join(
"gauntlet/rooms/%s/checklist.yaml" % room_id)
var room_path := _content_base.path_join("gauntlet/rooms/%s/checklist.yaml" % room_id)
var room_data := _load_checklist_file(room_path)
if room_data.has("conditions"):
_room_conditions = room_data["conditions"]
@@ -90,12 +89,17 @@ func get_results() -> Array:
var cid: String = cond.get("id", "")
if cid.is_empty():
continue
results.append({
"id": cid,
"description": cond.get("description", ""),
"condition_type": cond.get("condition_type", ""),
"met": _latched.has(cid),
})
(
results
. append(
{
"id": cid,
"description": cond.get("description", ""),
"condition_type": cond.get("condition_type", ""),
"met": _latched.has(cid),
}
)
)
return results
@@ -135,12 +139,18 @@ func reset() -> void:
static func _warn_empty_ids(conditions: Array, path: String) -> void:
for i in conditions.size():
if conditions[i].get("id", "").is_empty():
push_warning("ChecklistEvaluator: condition at index %d in %s has empty id — will be excluded from results" % [i, path])
push_warning(
(
"ChecklistEvaluator: condition at index %d in %s has empty id — will be excluded from results"
% [i, path]
)
)
# -- Condition evaluation ------------------------------------------------------
func _evaluate_condition(cond: Dictionary) -> bool:
func _evaluate_condition(cond: Dictionary) -> bool: # gdlint:disable=max-returns
match cond.get("condition_type", ""):
"player_near":
return _eval_player_near(cond)
@@ -224,6 +234,7 @@ func _eval_expected_interaction_verb(cond: Dictionary) -> bool:
# -- Helpers -------------------------------------------------------------------
func _find_entity(entity_id: int) -> bool:
for entity in GameState.visible_entities:
if not entity is Dictionary:
@@ -235,6 +246,7 @@ func _find_entity(entity_id: int) -> bool:
# -- YAML parsing --------------------------------------------------------------
func _load_checklist_file(path: String) -> Dictionary:
if not FileAccess.file_exists(path):
return {}
+60 -48
View File
@@ -12,35 +12,35 @@ const TILE_SIZE: int = 32
# All world content composited into one texture, then fog drawn over it.
# Y-sort contract: all children of YSortGroup MUST use z_index = 0.
# z_index is PRIMARY sort, y-position is SECONDARY (Godot #62715).
const Z_FLOOR: int = 0 # Floor tiles — ground plane
const Z_FLOOR_OBJECTS: int = 10 # Floor objects — cosmetic, ground shadows
const Z_FLOOR: int = 0 # Floor tiles — ground plane
const Z_FLOOR_OBJECTS: int = 10 # Floor objects — cosmetic, ground shadows
# z:20-99 reserved: liquid surface (z:110), surface effects
const Z_YSORT: int = 100 # YSortGroup — furniture + entities + walls, all z:0 relative
const Z_YSORT: int = 100 # YSortGroup — furniture + entities + walls, all z:0 relative
# z:110 reserved: liquid surface occlusion (alpha by depth)
# z:150-199 reserved: ground VFX (smoke origins, gas pools, sparks)
const Z_AIRBORNE: int = 200 # Projectiles, low-flying objects (scale ~1.0)
const Z_AIRBORNE: int = 200 # Projectiles, low-flying objects (scale ~1.0)
# z:250-299 reserved: mid-air VFX (rising smoke, floating particles)
const Z_OVERHEAD: int = 300 # Ceiling edges, upper structure, semi-transparent
const Z_OVERHEAD: int = 300 # Ceiling edges, upper structure, semi-transparent
# z:325-349 reserved: ceiling VFX (smoke through ceiling)
const Z_HIGH_AIRBORNE: int = 350 # Above-ceiling flying (scale 1.03-1.30, alpha fades)
const Z_UPPER_CONTENT: int = 400 # Upper-floor entities (rare with fixed camera)
const Z_HIGH_AIRBORNE: int = 350 # Above-ceiling flying (scale 1.03-1.30, alpha fades)
const Z_UPPER_CONTENT: int = 400 # Upper-floor entities (rare with fixed camera)
# z:500-899 reserved: edge cases
const Z_FOG: int = 900 # FogOverlay — OUTSIDE FogGroup, fog shader
const Z_FOG_ENTITIES: int = 950 # FogEntities — cognitive delay blobs/pings (D-059/D-060)
const Z_FOG: int = 900 # FogOverlay — OUTSIDE FogGroup, fog shader
const Z_FOG_ENTITIES: int = 950 # FogEntities — cognitive delay blobs/pings (D-059/D-060)
# Lower floors: z:-100 per floor (floor-1: z:-100 to z:-1, floor-2: z:-200 to z:-101)
# z:-75 to z:-51 reserved: lower floor VFX
#
# INSERT SCOPE (CanvasLayer 10)
# Bloom-rendered, not affected by fog or camera transform.
const CANVAS_INSERT: int = 10 # CanvasLayer number for InsertOverlay
const CANVAS_INSERT: int = 10 # CanvasLayer number for InsertOverlay
#
# UI SCOPE (CanvasLayer 20)
# HUD, monologue, cursor — always visible.
const CANVAS_UI: int = 20 # CanvasLayer number for UILayer
const CANVAS_UI: int = 20 # CanvasLayer number for UILayer
#
# MODAL SCOPE (CanvasLayer 30)
# Full-screen overlays: pause, inventory modal, death screen.
const CANVAS_MODAL: int = 30 # CanvasLayer number for ModalLayer
const CANVAS_MODAL: int = 30 # CanvasLayer number for ModalLayer
#
# Rendering ceiling: 10 floors (25m) above current floor.
# Above this: no sprites, ground shadows + environmental effects only.
@@ -52,36 +52,18 @@ const VISIBLE_FLOOR_DEPTH: int = 2
# Color represents the player's RELATIONSHIP to the entity, not an objective property.
# Phase 1: default colors mapped by entity kind (Player/Npc/Object/Terrain).
# Phase 2 (#361): colors derived from RelationshipState via the knowledge graph.
const ENTITY_COLOR_UNKNOWN: Color = Color("#4a9ebb") # Unknown/Neutral — cool teal
const ENTITY_COLOR_UNKNOWN: Color = Color("#4a9ebb") # Unknown/Neutral — cool teal
const ENTITY_COLOR_FRIENDLY: Color = Color("#6bc9a6") # Known/Friendly — soft green
const ENTITY_COLOR_POI: Color = Color("#e8c547") # Person of Interest — warm amber
const ENTITY_COLOR_HOSTILE: Color = Color("#d45d5d") # Hostile/Dangerous — muted red
const ENTITY_COLOR_OBJECT: Color = Color("#8b8ba0") # Static objects — muted grey
const ENTITY_COLOR_PLAYER: Color = Color("#e0e8ff") # Player character (detective)
# D-033 color lookup by relationship string (#521)
static func color_for_relationship(relationship: String) -> Color:
match relationship:
"Friendly": return ENTITY_COLOR_FRIENDLY
"PersonOfInterest": return ENTITY_COLOR_POI
"Hostile": return ENTITY_COLOR_HOSTILE
"Unknown": return ENTITY_COLOR_UNKNOWN
_: return ENTITY_COLOR_UNKNOWN
# D-033 color lookup by entity data — uses relationship for NPCs (#521)
static func color_for_entity_kind(entity_data: Dictionary) -> Color:
var kind_variant: String = entity_data.get("kind", {}).get("variant", "")
match kind_variant:
"Player": return ENTITY_COLOR_PLAYER
"Object", "Terrain": return ENTITY_COLOR_OBJECT
"Npc": return color_for_relationship(entity_data.get("relationship", "Unknown"))
_: return ENTITY_COLOR_OBJECT
const ENTITY_COLOR_POI: Color = Color("#e8c547") # Person of Interest — warm amber
const ENTITY_COLOR_HOSTILE: Color = Color("#d45d5d") # Hostile/Dangerous — muted red
const ENTITY_COLOR_OBJECT: Color = Color("#8b8ba0") # Static objects — muted grey
const ENTITY_COLOR_PLAYER: Color = Color("#e0e8ff") # Player character (detective)
# D-048/D-056: Insert-styled UI color palette
# Used by dialogue box, interaction list, radial menu, and other diegetic insert UI.
const INSERT_COLOR_TEXT: Color = Color("#c8d0e0") # Default insert text — white-blue
const INSERT_COLOR_HOVER: Color = Color("#e8c547") # Hover/highlight — amber POI
const INSERT_COLOR_ACTIVE: Color = Color("#6bc9a6") # Active/pressed — friendly green
const INSERT_COLOR_TEXT: Color = Color("#c8d0e0") # Default insert text — white-blue
const INSERT_COLOR_HOVER: Color = Color("#e8c547") # Hover/highlight — amber POI
const INSERT_COLOR_ACTIVE: Color = Color("#6bc9a6") # Active/pressed — friendly green
# D-015: Peripheral vision dimming
const PERIPHERAL_ALPHA: float = 0.5
@@ -96,11 +78,6 @@ const FACING_INDICATOR_OFFSET: float = 14.0
# two columns of text comfortably, leaves world game visible alongside.
const DIALOGUE_MAX_WIDTH: int = 1200
# D-031: Format game-minutes (0..1439) as station local time string "HH:MM".
static func format_game_time(time_of_day: int) -> String:
var clamped: int = clampi(time_of_day, 0, 1439)
return "%02d:%02d" % [clamped / 60, clamped % 60]
# Default camera zoom — used as fallback when get_camera_2d() returns null
const CAMERA_DEFAULT_ZOOM: Vector2 = Vector2(2.0, 2.0)
@@ -110,8 +87,43 @@ const CAMERA_DEFAULT_ZOOM: Vector2 = Vector2(2.0, 2.0)
const CAMERA_SMOOTHING_SPEED: float = 8.0
# #517: Implant UI font color grading — avoid pure white, project through a lens
const IMPLANT_TEXT_COLOR: Color = Color("#E0F7FA") # Cyan-white — primary text
const IMPLANT_TEXT_DIM: Color = Color("#9EBFC4") # Dimmed variant — secondary text
const IMPLANT_PULSE_MIN: float = 0.85 # Alpha pulse floor
const IMPLANT_PULSE_MAX: float = 1.0 # Alpha pulse ceiling
const IMPLANT_PULSE_PERIOD: float = 2.5 # Seconds per pulse cycle
const IMPLANT_TEXT_COLOR: Color = Color("#E0F7FA") # Cyan-white — primary text
const IMPLANT_TEXT_DIM: Color = Color("#9EBFC4") # Dimmed variant — secondary text
const IMPLANT_PULSE_MIN: float = 0.85 # Alpha pulse floor
const IMPLANT_PULSE_MAX: float = 1.0 # Alpha pulse ceiling
const IMPLANT_PULSE_PERIOD: float = 2.5 # Seconds per pulse cycle
# D-033 color lookup by relationship string (#521)
static func color_for_relationship(relationship: String) -> Color:
match relationship:
"Friendly":
return ENTITY_COLOR_FRIENDLY
"PersonOfInterest":
return ENTITY_COLOR_POI
"Hostile":
return ENTITY_COLOR_HOSTILE
"Unknown":
return ENTITY_COLOR_UNKNOWN
_:
return ENTITY_COLOR_UNKNOWN
# D-033 color lookup by entity data — uses relationship for NPCs (#521)
static func color_for_entity_kind(entity_data: Dictionary) -> Color:
var kind_variant: String = entity_data.get("kind", {}).get("variant", "")
match kind_variant:
"Player":
return ENTITY_COLOR_PLAYER
"Object", "Terrain":
return ENTITY_COLOR_OBJECT
"Npc":
return color_for_relationship(entity_data.get("relationship", "Unknown"))
_:
return ENTITY_COLOR_OBJECT
# D-031: Format game-minutes (0..1439) as station local time string "HH:MM".
static func format_game_time(time_of_day: int) -> String:
var clamped: int = clampi(time_of_day, 0, 1439)
return "%02d:%02d" % [clamped / 60, clamped % 60]
+181
View File
@@ -0,0 +1,181 @@
class_name DialogueCoordinator
## Dialogue snapshot consumers and signal handlers extracted from main.gd (#775).
##
## Owns NPC identity tracking state (_last_dialogue_npc_id/name) shared between
## consuming dialogue snapshots and handling dialogue_box signals.
## Registered with SnapshotEventRouter; reads from GameState directly.
var dialogue_box: Node = null
var monologue_display: Node = null
var journal_panel: Node = null
# Shared mutable reference — GDScript arrays are reference types.
# main.gd and this coordinator both append to the same array.
var _pending_record_inputs: Array = []
var _last_dialogue_npc_id: int = -1 # D-064: NPC entity_id for WalkAway input
var _last_dialogue_npc_name: String = "" # #535: NPC name for dialogue_response attribution
var _last_dialogue_tick: int = -1
var _last_confrontation_tick: int = -1
func init(refs: Dictionary, pending_record_inputs: Array) -> DialogueCoordinator:
dialogue_box = refs.get("dialogue_box")
monologue_display = refs.get("monologue_display")
journal_panel = refs.get("journal_panel")
_pending_record_inputs = pending_record_inputs
return self
## Connect dialogue_box signals. Call from main.gd._ready() after init().
func connect_signals() -> void:
if not dialogue_box:
return
dialogue_box.option_selected.connect(on_dialogue_option_selected)
dialogue_box.dialogue_dismissed.connect(on_dialogue_dismissed)
dialogue_box.confrontation_monologue.connect(on_confrontation_monologue)
dialogue_box.pause_requested.connect(on_dialogue_pause_requested)
dialogue_box.unpause_requested.connect(on_dialogue_unpause_requested)
# D-020 (#558): Decoupled signals — coordinator routes state changes.
dialogue_box.dialogue_state_changed.connect(on_dialogue_state_changed)
dialogue_box.audio_dip_requested.connect(on_audio_dip_requested)
dialogue_box.audio_dip_cleared.connect(on_audio_dip_cleared)
# -- Snapshot consumers (registered with SnapshotEventRouter) -----------------
# Consume-once per tick with ID tracking: show dialogue, then clear.
func consume_dialogue() -> void:
if GameState.current_dialogue == null or not dialogue_box:
return
if GameState.current_tick == _last_dialogue_tick:
return
if dialogue_box.is_dialogue_active():
GameState.current_dialogue = null
return
_last_dialogue_tick = GameState.current_tick
# #264: Close journal when dialogue opens
if journal_panel and journal_panel.has_method("close"):
journal_panel.close()
var dlg: Dictionary = GameState.current_dialogue
_last_dialogue_npc_id = dlg.get("npc_entity_id", -1)
_last_dialogue_npc_name = dlg.get("npc_name", "")
dialogue_box.show_dialogue(
dlg.get("npc_name", ""),
dlg.get("speech", ""),
dlg.get("options", []),
_last_dialogue_npc_id
)
GameState.current_dialogue = null
# #535: Consume overheard NPC-NPC conversation events (D-078).
func consume_conversation_events() -> void:
if not dialogue_box:
return
for event in GameState.conversation_events:
dialogue_box.append_conversation_event(event)
GameState.conversation_events = []
# #535: Handle conversation_ended events.
func consume_conversation_ended() -> void:
if not dialogue_box:
return
for event in GameState.conversation_ended:
dialogue_box.on_conversation_ended(event)
GameState.conversation_ended = []
# #535: Consume dialogue_response — NPC follow-up line after player picks an option.
func consume_dialogue_response() -> void:
if GameState.dialogue_response == null or not dialogue_box:
return
var dr: Dictionary = GameState.dialogue_response
var speaker_entity_id: int = dr.get("speaker_entity_id", _last_dialogue_npc_id)
var speaker_color_index: int = dr.get("speaker_color_index", -1)
var speaker_name: String = dr.get("speaker_name", _last_dialogue_npc_name)
dialogue_box.update_entity_display(speaker_entity_id, speaker_name, speaker_color_index)
dialogue_box.append_dialogue_response(speaker_name, dr.get("text", ""), speaker_entity_id)
GameState.dialogue_response = null
# -- Signal handlers ----------------------------------------------------------
# D-061: Handle dialogue option selection -> send to server
func on_dialogue_option_selected(response_id: String, _text: String) -> void:
(
SimBridge
. send_input(
{
"action": InputMapper.Action.INTERACT,
"timestamp_msec": Time.get_ticks_msec(),
"action_data":
{
"target_entity_id": null,
"verb": "DialogueResponse",
"response_id": response_id,
},
}
)
)
# D-063: Confrontation beat monologue -> show on monologue display (layer 7)
func on_confrontation_monologue(text: String, duration: float) -> void:
if not monologue_display:
return
if GameState.current_tick == _last_confrontation_tick:
return
_last_confrontation_tick = GameState.current_tick
monologue_display.show_monologue(text, duration, 3, true)
# D-061: Auto-pause on dialogue open
func on_dialogue_pause_requested() -> void:
var input := {"action": InputMapper.Action.PAUSE, "timestamp_msec": Time.get_ticks_msec()}
SimBridge.send_input(input)
_pending_record_inputs.append(input)
# D-061: Auto-unpause on dialogue close
func on_dialogue_unpause_requested() -> void:
var input := {"action": InputMapper.Action.UNPAUSE, "timestamp_msec": Time.get_ticks_msec()}
SimBridge.send_input(input)
_pending_record_inputs.append(input)
# D-064: Handle walk-away -> send WalkAway{npc_id} to server
func on_dialogue_dismissed() -> void:
(
SimBridge
. send_input(
{
"action": InputMapper.Action.INTERACT,
"timestamp_msec": Time.get_ticks_msec(),
"action_data":
{
"target_entity_id":
_last_dialogue_npc_id if _last_dialogue_npc_id >= 0 else null,
"verb": "WalkAway",
},
}
)
)
# D-020 (#558): Coordinator handles dialogue state changes.
func on_dialogue_state_changed(active: bool) -> void:
GameState.dialogue_active = active
# D-020 (#558): Route audio dip requests.
func on_audio_dip_requested(profile: String) -> void:
AudioManager.apply_dip(profile)
# D-020 (#558): Route audio dip clear.
func on_audio_dip_cleared() -> void:
AudioManager.clear_dip()
+120 -398
View File
@@ -1,9 +1,19 @@
extends Node2D
const TELEPORT_DISTANCE_THRESHOLD: float = 5.0
var _camera_anchored: bool = false
var _flash_rect: ColorRect = null # #502/#501: ephemeral screen flash overlay
var _teleport_in_progress: bool = false # #501/#117: forces camera snap on next frame
var _pending_record_inputs: Array = [] # #507: accumulates server-bound inputs across frames
var _router: SnapshotEventRouter # #559: callable-based snapshot dispatch
var _consumers: SnapshotConsumers # #775: non-dialogue snapshot consumers
var _dialogue: DialogueCoordinator # #775: dialogue consumers + signal handlers
@onready var world_renderer = $World
@onready var fog_entities = $World/FogEntities # D-059/D-060: cognitive delay fog visualization
@onready var camera = $Camera2D
@onready var hud = $UILayer/HUD
@onready var hud = $InsertOverlay/HUD
@onready var monologue_display = $UILayer/MonologueDisplay
@onready var interaction_prompt = $InsertOverlay/InteractionPrompt # v0.1 single-line fallback
@onready var interaction_list = $InsertOverlay/InteractionList # D-057: z-layer 6
@@ -14,49 +24,28 @@ extends Node2D
@onready var cursor_renderer = $UILayer/CursorRenderer # D-056: z-layer 7
@onready var gauntlet_hud = $UILayer/GauntletHUD # #496: room timer + personal bests
@onready var checklist_overlay = $UILayer/ChecklistOverlay # #503: auto-checklist progress
@onready var time_display = $InsertOverlay/TimeDisplay # #263: diegetic time display (D-013, D-031)
@onready var minimap = $InsertOverlay/Minimap # #151: diegetic minimap overlay (D-013, D-049)
@onready var examine_display = $InsertOverlay/ExamineDisplay # #174: examine result overlay
@onready var journal_panel = $InsertOverlay/JournalPanel # #264: knowledge journal (D-041)
@onready var debug_overlay = $UILayer/DebugOverlay # #511: F3 debug overlay
@onready var bug_report_dialog = $ModalLayer/BugReportDialog # #495: F12 WRONG button
@onready var settings_dialog = $ModalLayer/SettingsDialog # #528: audio settings (ESC/OPEN_MENU)
@onready var loading_screen = $ModalLayer/LoadingScreen # #257: blocking overlay during load
@onready var debug_console = $ModalLayer/DebugConsole # #581: tilde debug console
@onready var news_ticker = $UILayer/NewsTicker # #592: scrolling headline bar (D-049 z-7)
@onready var star_map = $UILayer/HUD/StarMap # #674: star map insert module (hop-ring view)
@onready var settings_dialog = $ModalLayer/SettingsDialog # #528: audio settings (ESC/OPEN_MENU)
@onready var loading_screen = $ModalLayer/LoadingScreen # #257: blocking overlay during load
@onready var debug_console = $ModalLayer/DebugConsole # #581: tilde debug console
@onready var news_ticker = $UILayer/NewsTicker # #592: scrolling headline bar (D-049 z-7)
@onready var star_map = $InsertOverlay/HUD/StarMap # #674: star map insert module (hop-ring view)
var _last_dialogue_npc_id: int = -1 # D-064: NPC entity_id for WalkAway input
var _last_dialogue_npc_name: String = "" # #535: NPC name for dialogue_response attribution
var _camera_anchored: bool = false
var _last_monologue_tick: int = -1 # Prevent re-consuming monologue when same tick polled twice
var _last_dialogue_tick: int = -1
var _last_confrontation_tick: int = -1 # Deduplicate confrontation_monologue signals within same tick
var _known_recognition_ids: Dictionary = {} # D-067: entity_ids that have already chimed
var _known_triangle_ids: Dictionary = {} # #590: triangle_ids that have already fired the activation chime
var _flash_rect: ColorRect = null # #502/#501: ephemeral screen flash overlay (shared: teleport preempts amber)
var _teleport_in_progress: bool = false # #501/#117: forces camera snap (not lerp) on next _process frame
var _pending_record_inputs: Array = [] # #507: accumulates server-bound inputs across frames; flushed into record_tick() on snapshot arrival
var _current_zone: String = "" # D-073 (#529): zone tracking for ambient crossfades
var _router: SnapshotEventRouter # #559: callable-based snapshot dispatch
const LISTENING_FOCUS_TICKS: int = 30 # D-071: stationary ticks before ListeningFocus boost activates
func _ready() -> void:
print("The Settled Reach — client initialized")
# #117: Manual lerp approach — disable Godot's built-in Camera2D smoothing.
# We lerp camera.global_position directly in _process() using CAMERA_SMOOTHING_SPEED,
# matching entity_renderer.gd's exponential smoothing pattern. Built-in smoothing
# would conflict because we'd be setting global_position to the target every frame.
camera.position_smoothing_enabled = false
# Connect to simulation (test mode sets CONNECTED immediately)
SimBridge.connect_to_sim()
# #257: If returning from main menu "Load Game" selection, defer dispatch until connected.
# In test mode, connect_to_sim() sets CONNECTED synchronously — dispatch fires immediately.
# In live mode, state is CONNECTING — signal handler dispatches once connected.
# #257: Deferred load dispatch
if not GameState.pending_load_path.is_empty():
if loading_screen:
loading_screen.show_loading()
@@ -66,79 +55,121 @@ func _ready() -> void:
SimBridge.connection_state_changed.connect(_on_sim_connected_for_load)
# Camera anchor: snap to player position before the first frame renders.
# In test mode poll_snapshot() returns synchronously — position is set
# immediately. In live mode the snapshot isn't available yet — _process
# handles it via the lerp block in _process().
var first_snapshot: Variant = SimBridge.poll_snapshot()
if first_snapshot != null:
GameState.apply_snapshot(first_snapshot)
camera.global_position = GameState.player_position * Constants.TILE_SIZE
_camera_anchored = true
# D-061: Connect dialogue box signals
if dialogue_box:
dialogue_box.option_selected.connect(_on_dialogue_option_selected)
dialogue_box.dialogue_dismissed.connect(_on_dialogue_dismissed)
dialogue_box.confrontation_monologue.connect(_on_confrontation_monologue)
dialogue_box.pause_requested.connect(_on_dialogue_pause_requested)
dialogue_box.unpause_requested.connect(_on_dialogue_unpause_requested)
# D-020 (#558): Decoupled signals — coordinator routes state changes.
dialogue_box.dialogue_state_changed.connect(_on_dialogue_state_changed)
dialogue_box.audio_dip_requested.connect(_on_audio_dip_requested)
dialogue_box.audio_dip_cleared.connect(_on_audio_dip_cleared)
# D-170: Register HUD nodes into layer groups
for node in [
hud,
minimap,
stance_indicator,
interaction_prompt,
interaction_list,
inventory_grid,
news_ticker,
examine_display,
world_radial,
]:
if node and node is CanvasItem:
HudGroups.register(node, "gameplay")
# #775: Initialize extracted components
_consumers = (
SnapshotConsumers
. new()
. init(
{
"monologue_display": monologue_display,
"dialogue_box": dialogue_box,
"examine_display": examine_display,
"loading_screen": loading_screen,
"debug_console": debug_console,
"cursor_renderer": cursor_renderer,
"interaction_list": interaction_list,
"interaction_prompt": interaction_prompt,
"minimap": minimap,
"star_map": star_map,
},
_screen_flash
)
)
_dialogue = (
DialogueCoordinator
. new()
. init(
{
"dialogue_box": dialogue_box,
"monologue_display": monologue_display,
"journal_panel": journal_panel,
},
_pending_record_inputs
)
)
_dialogue.connect_signals()
# #496: Print gauntlet session summary on disconnect
if gauntlet_hud:
SimBridge.connection_state_changed.connect(_on_connection_state_changed)
# #559: Register snapshot dispatch handlers — replaces inline dispatch in _process().
# #559: Register snapshot dispatch handlers
_router = SnapshotEventRouter.new()
# Always-run: child nodes that update from GameState on every snapshot tick.
if world_renderer:
_router.register_always(world_renderer.update_from_state)
_router.register_always(_propagate_insert_state)
_router.register_always(_update_interaction_list)
_router.register_always(_consumers.propagate_insert_state)
_router.register_always(_consumers.update_interaction_list)
if inventory_grid:
_router.register_always(inventory_grid.update_from_state)
if stance_indicator:
_router.register_always(stance_indicator.update_from_state)
if fog_entities:
_router.register_always(fog_entities.update_from_state)
_router.register_always(_play_recognition_chimes)
_router.register_always(_handle_triangle_crisis_events)
_router.register_always(_consumers.play_recognition_chimes)
_router.register_always(_consumers.handle_triangle_crisis_events)
if gauntlet_hud:
_router.register_always(gauntlet_hud.update_from_state)
if checklist_overlay:
_router.register_always(checklist_overlay.update_from_state)
if time_display:
_router.register_always(time_display.update_from_state)
if hud:
_router.register_always(hud.update_from_state)
if news_ticker:
_router.register_always(news_ticker.update_from_state)
if journal_panel:
_router.register_always(journal_panel.update_from_state)
if debug_overlay:
_router.register_always(debug_overlay.update_from_state)
_router.register_always(_play_close_sound_events)
_router.register_always(_update_zone)
_router.register_always(_update_listening_focus)
_router.register_always(_consume_examine_result)
_router.register_always(_consumers.play_close_sound_events)
_router.register_always(_consumers.update_zone)
_router.register_always(_consumers.update_listening_focus)
_router.register_always(_consumers.consume_examine_result)
# Keyed: consume methods guarded by specific snapshot fields.
_router.register("current_monologue", _consume_monologue)
_router.register("current_dialogue", _consume_dialogue)
_router.register("conversation_events", _consume_conversation_events)
_router.register("conversation_ended", _consume_conversation_ended)
_router.register("dialogue_response", _consume_dialogue_response)
_router.register("save_result", _consume_save_result)
_router.register("debug_response", _consume_debug_response)
_router.register("current_monologue", _consumers.consume_monologue)
_router.register("current_dialogue", _dialogue.consume_dialogue)
_router.register("conversation_events", _dialogue.consume_conversation_events)
_router.register("conversation_ended", _dialogue.consume_conversation_ended)
_router.register("dialogue_response", _dialogue.consume_dialogue_response)
_router.register("save_result", _consumers.consume_save_result)
_router.register("debug_response", _consumers.consume_debug_response)
# #581: Wire settings_dialog debug console toggle → debug_console.set_enabled
# #581: Wire settings_dialog debug console toggle
if settings_dialog and debug_console:
settings_dialog.debug_console_toggled.connect(debug_console.set_enabled)
# #581 D-088: Wire debug console pause/unpause — sim must not advance during debug input
# #581 D-088: Wire debug console pause/unpause
if debug_console:
debug_console.pause_requested.connect(_on_dialogue_pause_requested)
debug_console.unpause_requested.connect(_on_dialogue_unpause_requested)
debug_console.pause_requested.connect(_dialogue.on_dialogue_pause_requested)
debug_console.unpause_requested.connect(_dialogue.on_dialogue_unpause_requested)
func _unhandled_key_input(event: InputEvent) -> void:
if event.is_pressed() and not event.is_echo():
if event is InputEventKey and event.keycode == KEY_M:
if star_map:
star_map.toggle_visible()
func _process(delta: float) -> void:
@@ -153,20 +184,15 @@ func _process(delta: float) -> void:
_teleport_transition()
# Late anchor: live mode — first snapshot arrives during _process.
# Smoothing is already OFF (disabled in _ready), so setting
# global_position takes effect immediately with no lerp.
if not _camera_anchored:
camera.global_position = GameState.player_position * Constants.TILE_SIZE
_camera_anchored = true
# #559: Dispatch snapshot to registered handlers (router pattern).
# Always-run handlers update child nodes; keyed handlers fire for present fields.
_router.dispatch(snapshot)
# Track camera to player (D-015: locked, fixed-north).
# #117: Manual exponential smoothing — same pattern as EntityRenderer.LERP_SPEED.
# Teleport (flag set by _teleport_transition): snap immediately, resume lerp next frame.
# Init: camera already snapped in _ready() or late-anchor path above.
# #117: Manual exponential smoothing.
if _camera_anchored:
var target := GameState.player_position * Constants.TILE_SIZE
if _teleport_in_progress:
@@ -177,11 +203,9 @@ func _process(delta: float) -> void:
camera.global_position = camera.global_position.lerp(target, weight)
# Send queued input to simulation
# #507: Server-bound inputs are accumulated into _pending_record_inputs across frames.
# At 60fps/10tps, inputs on non-snapshot frames must not be lost from the ring buffer.
var inputs = InputMapper.flush_queue()
for input in inputs:
# #495: F12 WRONG button — client-only, trigger bug report capture
# #495: F12 WRONG button — client-only
if input.action == InputMapper.Action.BUG_REPORT:
if bug_report_dialog and not bug_report_dialog.is_active():
bug_report_dialog.start_capture()
@@ -190,7 +214,7 @@ func _process(delta: float) -> void:
if input.action == InputMapper.Action.OPEN_JOURNAL:
_toggle_journal()
continue
# #257: LOAD_GAME — send first, then show loading screen (avoids stuck overlay if send fails)
# #257: LOAD_GAME — send first, then show loading screen
if input.action == InputMapper.Action.LOAD_GAME:
var err := SimBridge.send_input(input)
_pending_record_inputs.append(input)
@@ -217,7 +241,6 @@ func _process(delta: float) -> void:
if target_id < 0 and interaction_prompt:
target_id = interaction_prompt.get_interaction_target()
verb = interaction_prompt.get_selected_verb()
# Always send struct form for Interact (#415) — server expects named fields
if target_id >= 0:
input["action_data"] = {
"target_entity_id": target_id,
@@ -231,9 +254,7 @@ func _process(delta: float) -> void:
SimBridge.send_input(input)
_pending_record_inputs.append(input)
# #507: Record tick data to ring buffer — once per server tick (snapshot arrival).
# Flushes all inputs accumulated since the last snapshot (across multiple display frames),
# then clears the accumulator for the next tick.
# #507: Record tick data to ring buffer
if snapshot != null and bug_report_dialog and bug_report_dialog.has_method("record_tick"):
bug_report_dialog.record_tick(
GameState.current_tick,
@@ -243,297 +264,18 @@ func _process(delta: float) -> void:
_pending_record_inputs.clear()
# OQ-07 (#522): Propagate insert state to all z-layer-6 display nodes.
# Cursor shape still fires (D-056 option a) — only verb labels suppressed.
func _propagate_insert_state() -> void:
var insert_state := GameState.insert_active
if cursor_renderer:
cursor_renderer.set_insert_active(insert_state)
if interaction_list:
interaction_list.set_insert_active(insert_state)
if interaction_prompt:
interaction_prompt.set_insert_active(insert_state)
if minimap:
minimap.set_insert_active(insert_state)
if star_map:
star_map.set_insert_active(insert_state)
# D-057: Update interaction list from game state.
# Suppress during dialogue — player is in conversation, verb list is noise.
func _update_interaction_list() -> void:
if not interaction_list:
return
if dialogue_box and dialogue_box.is_dialogue_active():
if interaction_list.is_showing():
interaction_list.hide_list()
else:
interaction_list.update_from_state()
# D-018 #125: Play close-range sound events — fired once per snapshot tick.
# Each event is passed to AudioManager.play_sound_event() for 2D positional playback
# on the WorldSFX bus. Events with no registered asset are silently skipped (D-038).
# Consume-once: events are cleared after processing so they don't replay if
# _process runs again before the next server tick (D-009 multiplayer-safe pattern).
func _play_close_sound_events() -> void:
for evt in GameState.close_sound_events:
if not evt is Dictionary or not evt.has("x") or not evt.has("y"):
continue
AudioManager.play_sound_event(
evt.get("event_type", ""),
Vector2(float(evt.x), float(evt.y))
)
GameState.close_sound_events = []
# D-067: Recognition chime — fires sfx_monologue_chime when a fog entity
# enters the cognitive delay recognition queue for the first time.
# "The chime marks the character's attention shifting" (D-067).
# IDs persist for the session — one chime per entity, no re-trigger on
# fog oscillation or server re-send. Cleared on room change (teleport).
func _play_recognition_chimes() -> void:
for rec in GameState.pending_recognitions:
if not rec is Dictionary or not rec.has("entity_id"):
continue
var eid: int = rec.entity_id
if not _known_recognition_ids.has(eid):
_known_recognition_ids[eid] = true
AudioManager.play(AudioManager.CHIME_RECOGNITION)
# #590 D-072/D-089: Triangle activation consumer — fires sfx_monologue_chime_urgent once
# per triangle_id. The tell_state on the activated NPC and subsequent proximity monologue
# lines are the visible consequence (D-039 wow moment #2 "The Character's Eye").
# No overlay is shown — the chime is the only client-side reaction (D-039 intent).
func _handle_triangle_crisis_events() -> void:
var events: Array = GameState.current_snapshot.get("triangle_crisis_events", [])
for ev in events:
if not ev is Dictionary or not ev.has("triangle_id"):
continue
var tid: int = ev.triangle_id
if not _known_triangle_ids.has(tid):
_known_triangle_ids[tid] = true
AudioManager.play(AudioManager.CHIME_ACTIVATION, AudioManager.BUS_UI_SOUNDS)
# D-073 (#529): Zone ambient crossfade — reads zone_id from GameState.current_zone_id
# (extracted in apply_snapshot(), server-authoritative per D-020).
# Calls AudioManager.set_zone() when zone changes (AudioManager handles crossfade).
func _update_zone() -> void:
var zone := GameState.current_zone_id
if zone != _current_zone:
_current_zone = zone
AudioManager.set_zone(zone)
# D-071 (#530): ListeningFocus boost — World SFX +2.5dB when stationary 30+ ticks.
# Uses AudioManager.get_active_dip() as single source of truth (no separate flag).
# Only activates when no other dip (dialogue/confrontation) is running.
# Only deactivates its own dip — never touches dialogue/confrontation.
# D-070: no UI indicator — the boost is "felt, not computed."
func _update_listening_focus() -> void:
var current_dip := AudioManager.get_active_dip()
var threshold_met := GameState.stationary_ticks >= LISTENING_FOCUS_TICKS
if threshold_met and current_dip == "":
AudioManager.apply_dip("listening_focus")
elif not threshold_met and current_dip == "listening_focus":
AudioManager.clear_dip()
# Consume-once per tick: show monologue text, then clear.
# Tick guard prevents re-triggering when the same tick is polled multiple
# times (client FPS > sim tick rate).
func _consume_monologue() -> void:
if GameState.current_monologue == null or not monologue_display:
return
if GameState.current_tick == _last_monologue_tick:
return
_last_monologue_tick = GameState.current_tick
var mono: Dictionary = GameState.current_monologue
monologue_display.show_monologue(
mono.get("text", ""),
mono.get("duration_seconds", 5.0),
mono.get("priority", 2),
mono.get("is_urgent", false)
)
# #502: Amber flash on room reset
var mono_id: String = mono.get("id", "")
if mono_id.begins_with("room_reset"):
_screen_flash(Constants.ENTITY_COLOR_POI, 0.15)
GameState.current_monologue = null
# Consume-once per tick with ID tracking: show dialogue, then clear.
# Tick guard + is_dialogue_active check prevent re-triggering.
func _consume_dialogue() -> void:
if GameState.current_dialogue == null or not dialogue_box:
return
if GameState.current_tick == _last_dialogue_tick:
return
if dialogue_box.is_dialogue_active():
GameState.current_dialogue = null
return
_last_dialogue_tick = GameState.current_tick
# #264: Close journal when dialogue opens (cannot be open simultaneously)
if journal_panel and journal_panel.has_method("close"):
journal_panel.close()
var dlg: Dictionary = GameState.current_dialogue
_last_dialogue_npc_id = dlg.get("npc_entity_id", -1)
_last_dialogue_npc_name = dlg.get("npc_name", "")
dialogue_box.show_dialogue(
dlg.get("npc_name", ""),
dlg.get("speech", ""),
dlg.get("options", []),
_last_dialogue_npc_id
)
GameState.current_dialogue = null
# #535: Consume overheard NPC-NPC conversation events (D-078).
# Each event carries pre-occluded text — render verbatim in the dialogue log.
func _consume_conversation_events() -> void:
if not dialogue_box:
return
for event in GameState.conversation_events:
dialogue_box.append_conversation_event(event)
GameState.conversation_events = []
# #535: Handle conversation_ended events — notify dialogue box to stop tracking pairs.
func _consume_conversation_ended() -> void:
if not dialogue_box:
return
for event in GameState.conversation_ended:
dialogue_box.on_conversation_ended(event)
GameState.conversation_ended = []
# #535: Consume dialogue_response — NPC follow-up line after player picks an option.
# Updates dialogue_box entity display registry with speaker identity from the wire.
func _consume_dialogue_response() -> void:
if GameState.dialogue_response == null or not dialogue_box:
return
var dr: Dictionary = GameState.dialogue_response
# v0.1: falls back to _last_dialogue_npc_id if wire omits speaker_entity_id.
# Edge case: fast re-engagement with a different NPC could misattribute — low probability.
var speaker_entity_id: int = dr.get("speaker_entity_id", _last_dialogue_npc_id)
var speaker_color_index: int = dr.get("speaker_color_index", -1)
var speaker_name: String = dr.get("speaker_name", _last_dialogue_npc_name)
dialogue_box.update_entity_display(speaker_entity_id, speaker_name, speaker_color_index)
dialogue_box.append_dialogue_response(speaker_name, dr.get("text", ""), speaker_entity_id)
GameState.dialogue_response = null
# #554/#257: Show save/load result notification; hide loading screen on load complete.
func _consume_save_result() -> void:
if GameState.save_result == null:
return
var result: Dictionary = GameState.save_result
GameState.save_result = null # consume once
# #257: Dismiss loading screen regardless of success/failure
if loading_screen:
loading_screen.hide_loading()
var msg: String
if result.get("success", false):
if result.get("kind", "") == "save":
msg = UIStrings.get_text("notifications.save_complete")
else:
msg = UIStrings.get_text("notifications.load_complete")
else:
if result.get("kind", "") == "save":
msg = UIStrings.get_text("notifications.save_failed")
else:
msg = UIStrings.get_text("notifications.load_failed")
if monologue_display:
monologue_display.show_notification(msg)
# #581: Forward debug_response from server to the debug console.
func _consume_debug_response() -> void:
if GameState.debug_response == null or not debug_console:
return
debug_console.append_response(GameState.debug_response)
GameState.debug_response = null
# D-061: Handle dialogue option selection → send to server
func _on_dialogue_option_selected(response_id: String, text: String) -> void:
SimBridge.send_input({
"action": InputMapper.Action.INTERACT,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {
"target_entity_id": null,
"verb": "DialogueResponse",
"response_id": response_id,
},
})
# D-063: Handle confrontation beat monologue → show on monologue display (layer 7)
# Confrontation lines are high-priority (3) and urgent — full opacity, elevated colour.
# Tick guard deduplicates if dialogue box emits the signal multiple times in one tick.
func _on_confrontation_monologue(text: String, duration: float) -> void:
if not monologue_display:
return
if GameState.current_tick == _last_confrontation_tick:
return
_last_confrontation_tick = GameState.current_tick
monologue_display.show_monologue(text, duration, 3, true)
# D-061: Auto-pause on dialogue open — routed through input recording (#507, Tyre #3)
func _on_dialogue_pause_requested() -> void:
var input := {"action": InputMapper.Action.PAUSE, "timestamp_msec": Time.get_ticks_msec()}
SimBridge.send_input(input)
_pending_record_inputs.append(input)
# D-061: Auto-unpause on dialogue close — routed through input recording (#507, Tyre #3)
func _on_dialogue_unpause_requested() -> void:
var input := {"action": InputMapper.Action.UNPAUSE, "timestamp_msec": Time.get_ticks_msec()}
SimBridge.send_input(input)
_pending_record_inputs.append(input)
# D-064: Handle walk-away → send WalkAway{npc_id} to server
func _on_dialogue_dismissed() -> void:
SimBridge.send_input({
"action": InputMapper.Action.INTERACT,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {
"target_entity_id": _last_dialogue_npc_id if _last_dialogue_npc_id >= 0 else null,
"verb": "WalkAway",
},
})
# D-020 (#558): Coordinator handles dialogue state changes from dialogue_box.
# Synchronous signal — GameState.dialogue_active updates same frame (D-064).
func _on_dialogue_state_changed(active: bool) -> void:
GameState.dialogue_active = active
# D-020 (#558): Coordinator routes audio dip requests from dialogue_box.
func _on_audio_dip_requested(profile: String) -> void:
AudioManager.apply_dip(profile)
# D-020 (#558): Coordinator routes audio dip clear from dialogue_box.
func _on_audio_dip_cleared() -> void:
AudioManager.clear_dip()
# #496: Finalize gauntlet stats on disconnect
func _on_connection_state_changed(old_state: SimBridge.ConnectionState, new_state: SimBridge.ConnectionState) -> void:
func _on_connection_state_changed(
_old_state: SimBridge.ConnectionState, new_state: SimBridge.ConnectionState
) -> void:
if new_state == SimBridge.ConnectionState.DISCONNECTED and gauntlet_hud:
gauntlet_hud.finalize()
# #257: Deferred LOAD_GAME dispatch — fires once when SimBridge reaches CONNECTED.
# pending_load_path is set by main_menu.gd before scene change.
func _on_sim_connected_for_load(_old_state: SimBridge.ConnectionState, new_state: SimBridge.ConnectionState) -> void:
func _on_sim_connected_for_load(
_old_state: SimBridge.ConnectionState, new_state: SimBridge.ConnectionState
) -> void:
if new_state != SimBridge.ConnectionState.CONNECTED:
return
if SimBridge.connection_state_changed.is_connected(_on_sim_connected_for_load):
@@ -546,30 +288,29 @@ func _dispatch_pending_load() -> void:
if load_path.is_empty():
return
GameState.pending_load_path = ""
var err := SimBridge.send_input({
"action": InputMapper.Action.LOAD_GAME,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"path": load_path},
})
var err := (
SimBridge
. send_input(
{
"action": InputMapper.Action.LOAD_GAME,
"timestamp_msec": Time.get_ticks_msec(),
"action_data": {"path": load_path},
}
)
)
if err != OK:
push_error("main.gd: failed to send LOAD_GAME after connection — %s" % error_string(err))
if loading_screen:
loading_screen.hide_loading(false)
# #501: Detect large position jump indicating a teleport (not normal movement).
const TELEPORT_DISTANCE_THRESHOLD: float = 5.0
# #501: Detect large position jump indicating a teleport.
func _detect_teleport(old_pos: Vector2, new_pos: Vector2) -> bool:
return old_pos.distance_to(new_pos) > TELEPORT_DISTANCE_THRESHOLD
# #501: Gauntlet dev teleport transition — snap camera + 0.3s fade-from-black.
# Clears dialogue/monologue/interaction state (server clears its side too).
# Scoped to Gauntlet testing only — production fast-travel uses diegetic gates.
func _teleport_transition() -> void:
# Set teleport flag — the camera tracking block in _process() will snap
# to the player's new position this frame (no lerp). Flag clears after snap.
_camera_anchored = true
_teleport_in_progress = true
@@ -577,12 +318,11 @@ func _teleport_transition() -> void:
GameState.current_monologue = null
GameState.current_dialogue = null
GameState.dialogue_active = false
_known_recognition_ids.clear() # D-067: reset chimes for new room
_known_triangle_ids.clear() # #590: reset activation chimes for new room
_consumers.clear_recognition_state()
if dialogue_box and dialogue_box.is_dialogue_active():
dialogue_box.hide_dialogue()
# Fade from black: instant black overlay, fades to transparent over 0.3s
# Fade from black
if _flash_rect and is_instance_valid(_flash_rect):
_flash_rect.queue_free()
_flash_rect = ColorRect.new()
@@ -595,35 +335,17 @@ func _teleport_transition() -> void:
tween.tween_callback(_flash_rect.queue_free)
# #174: Consume examine result — show overlay when server sends character-filtered observation.
# Clears after display (single-consume). Dismiss examine when dialogue opens.
func _consume_examine_result() -> void:
if GameState.current_examine_result == null or not examine_display:
return
var result: Dictionary = GameState.current_examine_result
# Dismiss existing examine result if dialogue is active (focus priority)
if dialogue_box and dialogue_box.is_dialogue_active():
if examine_display.has_method("dismiss"):
examine_display.dismiss()
else:
if examine_display.has_method("show_result"):
examine_display.show_result(result)
GameState.current_examine_result = null
# #264: Toggle journal panel. Called from input handler when J key pressed.
# #264: Toggle journal panel.
func _toggle_journal() -> void:
if not journal_panel:
return
# Journal and dialogue cannot be open simultaneously (sprint briefing)
if dialogue_box and dialogue_box.is_dialogue_active():
return
if journal_panel.has_method("toggle"):
journal_panel.toggle()
# #502: Full-screen color flash — fades from color to transparent over duration.
# Used for room reset amber flash. Creates ephemeral ColorRect on UILayer.
# #502: Full-screen color flash.
func _screen_flash(color: Color, duration: float) -> void:
if _flash_rect and is_instance_valid(_flash_rect):
_flash_rect.queue_free()
+13 -3
View File
@@ -86,14 +86,23 @@ func _try_extract_message() -> PackedByteArray:
if _pending_length < 0:
if _read_buffer.size() < 4:
return PackedByteArray()
_pending_length = (_read_buffer[0] << 24) | (_read_buffer[1] << 16) | \
(_read_buffer[2] << 8) | _read_buffer[3]
_pending_length = (
(_read_buffer[0] << 24)
| (_read_buffer[1] << 16)
| (_read_buffer[2] << 8)
| _read_buffer[3]
)
_read_buffer = _read_buffer.slice(4)
if _pending_length > MAX_MESSAGE_SIZE:
# Stream is corrupt — we can't find the next valid frame boundary.
# Disconnect rather than silently discarding valid buffered data.
push_error("LocalBridge: incoming message too large: %d bytes (max %d) — disconnecting" % [_pending_length, MAX_MESSAGE_SIZE])
push_error(
(
"LocalBridge: incoming message too large: %d bytes (max %d) — disconnecting"
% [_pending_length, MAX_MESSAGE_SIZE]
)
)
_corrupt = true
_pending_length = -1
_read_buffer.clear()
@@ -128,6 +137,7 @@ func reset() -> void:
# These exist for unit tests that verify framing logic without a live TCP
# connection. Not used in production code paths.
## Encode a payload into a framed byte array: [4-byte BE length][payload].
static func frame_encode(payload: PackedByteArray) -> PackedByteArray:
var len := payload.size()
+192 -90
View File
@@ -14,9 +14,9 @@ extends Node
## v20: adds settings_response field to ObserverSnapshot (#627, D-138).
const PROTOCOL_VERSION: int = 20
# -- Decode: bytes from server → GDScript types --------------------------------
## Decode an ObserverSnapshot from MessagePack bytes.
## Returns decoded snapshot Dictionary or null on error.
## v2 fields (version, game_time, player_facing, visible_tiles) default to null/empty
@@ -35,7 +35,12 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
# Version check: reject snapshots from incompatible server
var version: Variant = raw.get("version")
if version != PROTOCOL_VERSION:
push_error("Protocol: version mismatch (got %s, expected %s). Server and client are out of sync." % [version, PROTOCOL_VERSION])
push_error(
(
"Protocol: version mismatch (got %s, expected %s). Server and client are out of sync."
% [version, PROTOCOL_VERSION]
)
)
return null
var entities: Array[Dictionary] = []
@@ -49,7 +54,12 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
dropped += 1
if dropped > 0:
push_error("Protocol: %d/%d entities failed to decode (D-010 information boundary violation)" % [dropped, raw_entities.size()])
push_error(
(
"Protocol: %d/%d entities failed to decode (D-010 information boundary violation)"
% [dropped, raw_entities.size()]
)
)
# GDScript int is signed 64-bit. Rust tick is u64 but will not exceed 2^63
# in any realistic scenario (would require ~29 billion years at 10 ticks/game-minute per D-031).
@@ -69,7 +79,12 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
var raw_vtiles: Variant = raw.get("visible_tiles")
if raw_vtiles is Array:
for raw_tile in raw_vtiles:
if raw_tile is Dictionary and raw_tile.has("x") and raw_tile.has("y") and raw_tile.has("z"):
if (
raw_tile is Dictionary
and raw_tile.has("x")
and raw_tile.has("y")
and raw_tile.has("z")
):
var tile_entry := {
"x": int(raw_tile["x"]),
"y": int(raw_tile["y"]),
@@ -117,11 +132,16 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_inventory is Array:
for raw_item in raw_inventory:
if raw_item is Dictionary and raw_item.has("item_id") and raw_item.has("name"):
player_inventory.append({
"item_id": int(raw_item["item_id"]),
"name": str(raw_item["name"]),
"slot": int(raw_item.get("slot", 0)),
})
(
player_inventory
. append(
{
"item_id": int(raw_item["item_id"]),
"name": str(raw_item["name"]),
"slot": int(raw_item.get("slot", 0)),
}
)
)
# v7: pending_recognitions (#431, D-059/D-060) — cognitive delay fog entities
# Bounded: server sends at most ~50 pending recognitions per snapshot (practical limit
@@ -133,17 +153,32 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
var count := 0
for raw_pr in raw_recognitions:
if count >= MAX_PENDING_RECOGNITIONS:
push_warning("Protocol: pending_recognitions truncated at %d entries" % MAX_PENDING_RECOGNITIONS)
push_warning(
(
"Protocol: pending_recognitions truncated at %d entries"
% MAX_PENDING_RECOGNITIONS
)
)
break
if raw_pr is Dictionary and raw_pr.has("entity_id") and raw_pr.has("x") and raw_pr.has("y"):
pending_recognitions.append({
"entity_id": int(raw_pr["entity_id"]),
"x": float(raw_pr["x"]),
"y": float(raw_pr["y"]),
"z": int(raw_pr.get("z", 0)),
"remaining_ticks": int(raw_pr.get("remaining_ticks", 0)),
"total_delay_ticks": int(raw_pr.get("total_delay_ticks", 1)),
})
if (
raw_pr is Dictionary
and raw_pr.has("entity_id")
and raw_pr.has("x")
and raw_pr.has("y")
):
(
pending_recognitions
. append(
{
"entity_id": int(raw_pr["entity_id"]),
"x": float(raw_pr["x"]),
"y": float(raw_pr["y"]),
"z": int(raw_pr.get("z", 0)),
"remaining_ticks": int(raw_pr.get("remaining_ticks", 0)),
"total_delay_ticks": int(raw_pr.get("total_delay_ticks", 1)),
}
)
)
count += 1
# v7: current_dialogue (#435, D-061/D-062) — NPC speech + player response options
@@ -157,12 +192,17 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_options is Array:
for raw_opt in raw_options:
if raw_opt is Dictionary and raw_opt.has("text"):
dialogue_options.append({
"text": str(raw_opt["text"]),
"response_id": str(raw_opt.get("response_id", "")),
"priority": int(raw_opt.get("priority", 0)),
"confrontation": bool(raw_opt.get("confrontation", false)),
})
(
dialogue_options
. append(
{
"text": str(raw_opt["text"]),
"response_id": str(raw_opt.get("response_id", "")),
"priority": int(raw_opt.get("priority", 0)),
"confrontation": bool(raw_opt.get("confrontation", false)),
}
)
)
current_dialogue = {
"npc_name": str(raw_dialogue.get("npc_name", "")),
"npc_entity_id": int(raw_dialogue.get("npc_entity_id", -1)),
@@ -188,13 +228,18 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_conv_events is Array:
for raw_ce in raw_conv_events:
if raw_ce is Dictionary and raw_ce.has("occluded_line"):
conversation_events.append({
"speaker_id": int(raw_ce.get("speaker_id", 0)),
"target_id": int(raw_ce.get("target_id", 0)),
"speaker_name": str(raw_ce.get("speaker_name", "")),
"target_name": str(raw_ce.get("target_name", "")),
"occluded_line": str(raw_ce["occluded_line"]),
})
(
conversation_events
. append(
{
"speaker_id": int(raw_ce.get("speaker_id", 0)),
"target_id": int(raw_ce.get("target_id", 0)),
"speaker_name": str(raw_ce.get("speaker_name", "")),
"target_name": str(raw_ce.get("target_name", "")),
"occluded_line": str(raw_ce["occluded_line"]),
}
)
)
# v9: conversation_ended (#535, D-078) — pairs whose conversation ended this tick.
var conversation_ended: Array = []
@@ -202,10 +247,15 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_conv_ended is Array:
for raw_end in raw_conv_ended:
if raw_end is Dictionary:
conversation_ended.append({
"speaker_id": int(raw_end.get("speaker_id", 0)),
"target_id": int(raw_end.get("target_id", 0)),
})
(
conversation_ended
. append(
{
"speaker_id": int(raw_end.get("speaker_id", 0)),
"target_id": int(raw_end.get("target_id", 0)),
}
)
)
# v14: poi_list (#151) — discovered POIs for minimap rendering.
# Each entry: {poi_id, name, x, y, z, poi_category}. Positions in sim tile coords.
@@ -213,15 +263,26 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
var raw_pois: Variant = raw.get("poi_list")
if raw_pois is Array:
for raw_poi in raw_pois:
if raw_poi is Dictionary and raw_poi.has("poi_id") and raw_poi.has("x") and raw_poi.has("y"):
poi_list.append({
"poi_id": str(raw_poi["poi_id"]),
"name": str(raw_poi.get("name", "")),
"x": int(raw_poi["x"]),
"y": int(raw_poi["y"]),
"z": int(raw_poi.get("z", 0)),
"poi_category": str(raw_poi.get("poi_category", raw_poi.get("category", "Location"))),
})
if (
raw_poi is Dictionary
and raw_poi.has("poi_id")
and raw_poi.has("x")
and raw_poi.has("y")
):
(
poi_list
. append(
{
"poi_id": str(raw_poi["poi_id"]),
"name": str(raw_poi.get("name", "")),
"x": int(raw_poi["x"]),
"y": int(raw_poi["y"]),
"z": int(raw_poi.get("z", 0)),
"poi_category":
str(raw_poi.get("poi_category", raw_poi.get("category", "Location"))),
}
)
)
# v14: examine_result (#174, #242) — character-filtered observation text.
# {entity_id, text, confidence} or null. Auto-dismisses on client after 4-6 seconds.
@@ -266,9 +327,14 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_tce is Array:
for raw_ev in raw_tce:
if raw_ev is Dictionary and raw_ev.has("triangle_id"):
triangle_crisis_events.append({
"triangle_id": int(raw_ev["triangle_id"]),
})
(
triangle_crisis_events
. append(
{
"triangle_id": int(raw_ev["triangle_id"]),
}
)
)
# v20: settings_response (#627, D-138) — server ack after ChangeSettings / full settings dump
# after RequestAllSettings. kind = "full"|"ack". "full": settings array [{key, value}].
@@ -283,10 +349,15 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_sr_settings is Array:
for raw_s in raw_sr_settings:
if raw_s is Dictionary and raw_s.has("key"):
sr_settings.append({
"key": str(raw_s["key"]),
"value": raw_s.get("value"),
})
(
sr_settings
. append(
{
"key": str(raw_s["key"]),
"value": raw_s.get("value"),
}
)
)
settings_response = {"kind": "full", "settings": sr_settings}
elif sr_kind == "ack":
settings_response = {
@@ -336,27 +407,37 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
if raw_kg_entities is Array:
for raw_ke in raw_kg_entities:
if raw_ke is Dictionary and raw_ke.has("entity_id"):
kg_entities.append({
"entity_id": int(raw_ke["entity_id"]),
"name": str(raw_ke.get("name", "Unknown")),
"confidence": str(raw_ke.get("confidence", "Suspects")),
"source": str(raw_ke.get("source", "")),
"state": str(raw_ke.get("state", "Active")),
"relationship": str(raw_ke.get("relationship", "Unknown")),
"last_observed_tick": int(raw_ke.get("last_observed_tick", 0)),
})
(
kg_entities
. append(
{
"entity_id": int(raw_ke["entity_id"]),
"name": str(raw_ke.get("name", "Unknown")),
"confidence": str(raw_ke.get("confidence", "Suspects")),
"source": str(raw_ke.get("source", "")),
"state": str(raw_ke.get("state", "Active")),
"relationship": str(raw_ke.get("relationship", "Unknown")),
"last_observed_tick": int(raw_ke.get("last_observed_tick", 0)),
}
)
)
var kg_facts: Array = []
var raw_kg_facts: Variant = raw_pk.get("facts")
if raw_kg_facts is Array:
for raw_kf in raw_kg_facts:
if raw_kf is Dictionary and raw_kf.has("fact_id"):
kg_facts.append({
"fact_id": str(raw_kf["fact_id"]),
"confidence": str(raw_kf.get("confidence", "Suspects")),
"source": str(raw_kf.get("source", "")),
"state": str(raw_kf.get("state", "Active")),
"acquired_tick": int(raw_kf.get("acquired_tick", 0)),
})
(
kg_facts
. append(
{
"fact_id": str(raw_kf["fact_id"]),
"confidence": str(raw_kf.get("confidence", "Suspects")),
"source": str(raw_kf.get("source", "")),
"state": str(raw_kf.get("state", "Active")),
"acquired_tick": int(raw_kf.get("acquired_tick", 0)),
}
)
)
player_knowledge = {
"entities": kg_entities,
"facts": kg_facts,
@@ -394,8 +475,13 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
## Decode a single VisibleEntity from a raw msgpack map.
static func _decode_entity(raw: Dictionary) -> Variant:
if not raw.has("entity_id") or not raw.has("x") or not raw.has("y") \
or not raw.has("z") or not raw.has("kind"):
if (
not raw.has("entity_id")
or not raw.has("x")
or not raw.has("y")
or not raw.has("z")
or not raw.has("kind")
):
push_warning("Protocol: entity missing required fields: %s" % str(raw.keys()))
return null
@@ -483,23 +569,25 @@ static func _decode_verb_option(raw) -> Variant:
## Returns { "variant": String, "data": Variant } in both cases.
static func _decode_enum_variant(raw) -> Dictionary:
if raw is String:
return { "variant": raw, "data": null }
elif raw is Dictionary and raw.size() == 1:
return {"variant": raw, "data": null}
if raw is Dictionary and raw.size() == 1:
var variant_name: String = raw.keys()[0]
return { "variant": variant_name, "data": raw[variant_name] }
else:
push_warning("Protocol: unexpected enum encoding: %s" % str(raw))
return { "variant": "Unknown", "data": raw }
return {"variant": variant_name, "data": raw[variant_name]}
push_warning("Protocol: unexpected enum encoding: %s" % str(raw))
return {"variant": "Unknown", "data": raw}
# -- Encode: GDScript types → bytes to server ----------------------------------
## Encode a StartupMessage to MessagePack bytes (#175, #588, #718).
## Sent by the client immediately after handshake validation.
## Server reads this to initialize SimRng (D-010, D-029) and select monologue pool (D-032).
## character_archetype: "detective" → "Detective", "smuggler" → "Smuggler" (server enum variant).
## character_visual: optional CharacterVisualDescriptor — included as "character_visual_descriptor" dict.
static func encode_startup_message(world_seed: int, character_archetype: String = "detective", character_visual: Variant = null) -> PackedByteArray:
static func encode_startup_message(
world_seed: int, character_archetype: String = "detective", character_visual: Variant = null
) -> PackedByteArray:
# Map client lowercase archetype string to server PascalCase enum variant.
# Explicit match prevents unknown strings silently reaching the server as
# garbage enum values — fail loudly and fall back to "Detective".
@@ -510,7 +598,12 @@ static func encode_startup_message(world_seed: int, character_archetype: String
"smuggler":
archetype_variant = "Smuggler"
_:
push_error("Protocol: unknown character_archetype '%s' — defaulting to 'Detective'" % character_archetype)
push_error(
(
"Protocol: unknown character_archetype '%s' — defaulting to 'Detective'"
% character_archetype
)
)
archetype_variant = "Detective"
var msg := {
"world_seed": world_seed,
@@ -529,7 +622,9 @@ static func encode_startup_message(world_seed: int, character_archetype: String
## action_name: one of "MoveNorth", "MoveSouth", "MoveEast", "MoveWest",
## "Interact", "UsePerceptionMode", "Pause", "Unpause"
## action_data: null for unit variants, String for UsePerceptionMode
static func encode_player_input(tick: int, action_name: String, action_data: Variant = null) -> PackedByteArray:
static func encode_player_input(
tick: int, action_name: String, action_data: Variant = null
) -> PackedByteArray:
var action_value: Variant = _encode_action(action_name, action_data)
var input := {
@@ -553,10 +648,15 @@ static func encode_player_inputs(inputs: Array) -> PackedByteArray:
for input in inputs:
var action_name: String = input["action_name"]
var action_data: Variant = input.get("action_data")
wire_inputs.append({
"tick": input["tick"],
"action": _encode_action(action_name, action_data),
})
(
wire_inputs
. append(
{
"tick": input["tick"],
"action": _encode_action(action_name, action_data),
}
)
)
var result = Messagepack.encode(wire_inputs)
if result.status != null:
@@ -571,10 +671,10 @@ static func encode_player_inputs(inputs: Array) -> PackedByteArray:
## Unit variants (MoveNorth, Pause, etc.) encode as bare strings.
static func _encode_action(action_name: String, action_data: Variant) -> Variant:
if action_data != null:
return { action_name: action_data }
return {action_name: action_data}
# Interact is a struct variant — server expects named fields, not a bare string
if action_name == "Interact":
return { "Interact": { "target_entity_id": null, "verb": null } }
return {"Interact": {"target_entity_id": null, "verb": null}}
return action_name
@@ -584,11 +684,13 @@ static func _encode_action(action_name: String, action_data: Variant) -> Variant
## queuing via SimBridge._outbound_buffer.
## The server receives this as a PlayerAction::ChangeSettings variant.
static func encode_change_settings(enabled: bool) -> PackedByteArray:
var entries: Array = [{
"tick": 0,
"action_name": "ChangeSettings",
"action_data": {"ai_enhanced_dialogue": enabled},
}]
var entries: Array = [
{
"tick": 0,
"action_name": "ChangeSettings",
"action_data": {"ai_enhanced_dialogue": enabled},
}
]
var result = Messagepack.encode(entries)
if result.status != null:
push_error("Protocol: encode_change_settings failed: %s" % result.status)
+204 -90
View File
@@ -5,6 +5,40 @@ extends RefCounted
## interactions. Extracted from sim_bridge.gd to enforce D-020 information
## boundary (no game logic in the production client autoload).
const _WALLS: Array = [
# Room walls (8x8 room from (7,7) to (14,14))
Vector2i(7, 7),
Vector2i(8, 7),
Vector2i(9, 7),
Vector2i(10, 7),
Vector2i(11, 7),
Vector2i(12, 7),
Vector2i(13, 7),
Vector2i(14, 7),
Vector2i(7, 14),
Vector2i(8, 14),
Vector2i(9, 14),
Vector2i(10, 14),
Vector2i(11, 14),
Vector2i(12, 14),
Vector2i(13, 14),
Vector2i(14, 14),
Vector2i(7, 8),
Vector2i(7, 9),
Vector2i(7, 10),
Vector2i(7, 11),
Vector2i(7, 12),
Vector2i(7, 13),
Vector2i(14, 8),
Vector2i(14, 9),
Vector2i(14, 10),
Vector2i(14, 11),
Vector2i(14, 12),
Vector2i(14, 13),
# Interior wall blocking NPC
Vector2i(12, 10),
]
var tick: int = 0
var player_pos: Vector2i = Vector2i(10, 10)
var facing: String = "North"
@@ -34,6 +68,7 @@ func process_facing(new_facing: String) -> void:
# -- Snapshot generation -------------------------------------------------------
func snapshot() -> Dictionary:
tick += 1
@@ -62,42 +97,60 @@ func snapshot() -> Dictionary:
var py := player_pos.y
# Build entities — player always visible
var entities: Array = [{
"entity_id": 1,
"x": float(px),
"y": float(py),
"z": 0,
"kind": { "variant": "Player", "data": null },
"visibility": "Forward",
}]
var entities: Array = [
{
"entity_id": 1,
"x": float(px),
"y": float(py),
"z": 0,
"kind": {"variant": "Player", "data": null},
"visibility": "Forward",
}
]
# NPC at (12, 9) — visible if within range and not blocked by wall at (12, 10)
var npc_pos := Vector2i(12, 9)
var npc_dist := absi(px - npc_pos.x) + absi(py - npc_pos.y)
if npc_dist <= 4 and has_los(Vector2i(px, py), npc_pos):
var sector: String = "Forward" if npc_pos.y <= py else "Peripheral"
entities.append({
"entity_id": 2,
"x": float(npc_pos.x),
"y": float(npc_pos.y),
"z": 0,
"kind": { "variant": "Npc", "data": null },
"visibility": sector,
"relationship": npc_relationship,
})
(
entities
. append(
{
"entity_id": 2,
"x": float(npc_pos.x),
"y": float(npc_pos.y),
"z": 0,
"kind": {"variant": "Npc", "data": null},
"visibility": sector,
"relationship": npc_relationship,
}
)
)
# v4: nearby_interactions when NPC is nearby and visible (#404/#405)
var nearby: Array = []
if npc_dist <= 2 and has_los(Vector2i(px, py), npc_pos):
nearby.append({
"entity_id": 2,
"entity_type": "Npc",
"distance": npc_dist,
"verbs": [
{"kind": "Talk", "label": "Talk", "priority": 1, "available": true},
{"kind": "ExamineNpc", "label": "Observe", "priority": 2, "available": true},
],
})
(
nearby
. append(
{
"entity_id": 2,
"entity_type": "Npc",
"distance": npc_dist,
"verbs":
[
{"kind": "Talk", "label": "Talk", "priority": 1, "available": true},
{
"kind": "ExamineNpc",
"label": "Observe",
"priority": 2,
"available": true
},
],
}
)
)
# v5: monologue on first tick (#414)
var monologue: Variant = null
@@ -114,11 +167,28 @@ func snapshot() -> Dictionary:
dialogue = {
"npc_name": "Kael",
"npc_entity_id": 2,
"speech": "Haven't seen you around the transit hub before. You new to Sova, or just passing through?",
"options": [
{"text": "Just arrived. Still getting my bearings.", "response_id": "kael_greet_01", "priority": 1, "confrontation": false},
{"text": "Passing through. Know where I can find work?", "response_id": "kael_greet_02", "priority": 2, "confrontation": false},
{"text": "I saw you near the cargo bay last night.", "response_id": "kael_confront_01", "priority": 3, "confrontation": true},
"speech":
"Haven't seen you around the transit hub before. You new to Sova, or just passing through?",
"options":
[
{
"text": "Just arrived. Still getting my bearings.",
"response_id": "kael_greet_01",
"priority": 1,
"confrontation": false
}, # gdlint:ignore = max-line-length
{
"text": "Passing through. Know where I can find work?",
"response_id": "kael_greet_02",
"priority": 2,
"confrontation": false
}, # gdlint:ignore = max-line-length
{
"text": "I saw you near the cargo bay last night.",
"response_id": "kael_confront_01",
"priority": 3,
"confrontation": true
}, # gdlint:ignore = max-line-length
],
}
@@ -128,26 +198,55 @@ func snapshot() -> Dictionary:
if cycle_pos < 6:
var total_delay := 6
var remaining := total_delay - cycle_pos
pending_recs.append({
"entity_id": 100,
"x": 13.5,
"y": 12.5,
"z": 0,
"remaining_ticks": remaining,
"total_delay_ticks": total_delay,
})
(
pending_recs
. append(
{
"entity_id": 100,
"x": 13.5,
"y": 12.5,
"z": 0,
"remaining_ticks": remaining,
"total_delay_ticks": total_delay,
}
)
)
# #535: Mock overheard NPC-NPC conversation (D-078)
var conv_events: Array = []
var conv_ended: Array = []
var conv_start := 3
var conv_lines := [
{"speaker": "Mira", "target": "Soren", "line": "The cargo manifests don't add up. Three containers unaccounted for."},
{"speaker": "Soren", "target": "Mira", "line": "Could be a logging error. Happens every... cycle."},
{"speaker": "Mira", "target": "Soren", "line": "Not like this. Someone moved them after... check."},
{"speaker": "Soren", "target": "Mira", "line": "You're reading too much into it. The docks are... these days."},
{"speaker": "Mira", "target": "Soren", "line": "Then explain the weight discrepancy. Two hundred kilos... just gone."},
{"speaker": "Soren", "target": "Mira", "line": "Fine. I'll pull the bay... tonight. But keep this between us."},
{
"speaker": "Mira",
"target": "Soren",
"line": "The cargo manifests don't add up. Three containers unaccounted for."
},
{
"speaker": "Soren",
"target": "Mira",
"line": "Could be a logging error. Happens every... cycle."
},
{
"speaker": "Mira",
"target": "Soren",
"line": "Not like this. Someone moved them after... check."
},
{
"speaker": "Soren",
"target": "Mira",
"line": "You're reading too much into it. The docks are... these days."
},
{
"speaker": "Mira",
"target": "Soren",
"line": "Then explain the weight discrepancy. Two hundred kilos... just gone."
}, # gdlint:ignore = max-line-length
{
"speaker": "Soren",
"target": "Mira",
"line": "Fine. I'll pull the bay... tonight. But keep this between us."
},
]
var conv_tick_interval := 5
var conv_total_ticks := conv_lines.size() * conv_tick_interval
@@ -156,20 +255,26 @@ func snapshot() -> Dictionary:
var within_tick := (tick - conv_start) % conv_tick_interval
if within_tick == 0 and conv_index < conv_lines.size():
var cl: Dictionary = conv_lines[conv_index]
conv_events.append({
"speaker_id": 10,
"target_id": 11,
"speaker_name": cl.speaker,
"target_name": cl.target,
"occluded_line": cl.line,
})
(
conv_events
. append(
{
"speaker_id": 10,
"target_id": 11,
"speaker_name": cl.speaker,
"target_name": cl.target,
"occluded_line": cl.line,
}
)
)
elif tick == conv_start + conv_total_ticks:
conv_ended.append({"speaker_id": 10, "target_id": 11})
return {
"tick": tick,
"version": Protocol.PROTOCOL_VERSION,
"game_time": {
"game_time":
{
"day": 0,
"time_of_day": tick * 10,
"day_phase": "Morning",
@@ -193,6 +298,7 @@ func snapshot() -> Dictionary:
# -- Map generation ------------------------------------------------------------
func _tiles() -> Array:
var tiles: Array = []
var room_x := 7
@@ -202,8 +308,9 @@ func _tiles() -> Array:
for x in range(room_x, room_x + room_w):
for y in range(room_y, room_y + room_h):
var is_edge := (x == room_x or x == room_x + room_w - 1
or y == room_y or y == room_y + room_h - 1)
var is_edge := (
x == room_x or x == room_x + room_w - 1 or y == room_y or y == room_y + room_h - 1
)
var tile_type: String
if is_edge:
if y == room_y + room_h - 1 and x == room_x + room_w / 2:
@@ -239,7 +346,9 @@ func _visible_tiles() -> Array:
if dist <= radius:
if x >= room_x and x < room_x + room_w and y >= room_y and y < room_y + room_h:
var sector: String = "Forward" if y <= py else "Peripheral"
vtiles.append({"x": x, "y": y, "z": 0, "visibility": sector, "type": _get_tile_type(x, y)})
vtiles.append(
{"x": x, "y": y, "z": 0, "visibility": sector, "type": _get_tile_type(x, y)}
)
return vtiles
@@ -248,8 +357,9 @@ func _get_tile_type(x: int, y: int) -> String:
var room_y := 7
var room_w := 8
var room_h := 8
var is_edge := (x == room_x or x == room_x + room_w - 1
or y == room_y or y == room_y + room_h - 1)
var is_edge := (
x == room_x or x == room_x + room_w - 1 or y == room_y or y == room_y + room_h - 1
)
if is_edge:
if y == room_y + room_h - 1 and x == room_x + room_w / 2:
return "door"
@@ -259,20 +369,6 @@ func _get_tile_type(x: int, y: int) -> String:
# -- Spatial helpers -----------------------------------------------------------
const _WALLS: Array = [
# Room walls (8x8 room from (7,7) to (14,14))
Vector2i(7,7), Vector2i(8,7), Vector2i(9,7), Vector2i(10,7),
Vector2i(11,7), Vector2i(12,7), Vector2i(13,7), Vector2i(14,7),
Vector2i(7,14), Vector2i(8,14), Vector2i(9,14), Vector2i(10,14),
Vector2i(11,14), Vector2i(12,14), Vector2i(13,14), Vector2i(14,14),
Vector2i(7,8), Vector2i(7,9), Vector2i(7,10), Vector2i(7,11),
Vector2i(7,12), Vector2i(7,13),
Vector2i(14,8), Vector2i(14,9), Vector2i(14,10), Vector2i(14,11),
Vector2i(14,12), Vector2i(14,13),
# Interior wall blocking NPC
Vector2i(12, 10),
]
func _is_walkable(pos: Vector2i) -> bool:
return not _WALLS.has(pos)
@@ -303,25 +399,43 @@ func has_los(from: Vector2i, to: Vector2i) -> bool:
static func action_to_delta(action_name: String) -> Vector2i:
match action_name:
"MoveNorth": return Vector2i(0, -1)
"MoveNortheast": return Vector2i(1, -1)
"MoveEast": return Vector2i(1, 0)
"MoveSoutheast": return Vector2i(1, 1)
"MoveSouth": return Vector2i(0, 1)
"MoveSouthwest": return Vector2i(-1, 1)
"MoveWest": return Vector2i(-1, 0)
"MoveNorthwest": return Vector2i(-1, -1)
_: return Vector2i.ZERO
"MoveNorth":
return Vector2i(0, -1)
"MoveNortheast":
return Vector2i(1, -1)
"MoveEast":
return Vector2i(1, 0)
"MoveSoutheast":
return Vector2i(1, 1)
"MoveSouth":
return Vector2i(0, 1)
"MoveSouthwest":
return Vector2i(-1, 1)
"MoveWest":
return Vector2i(-1, 0)
"MoveNorthwest":
return Vector2i(-1, -1)
_:
return Vector2i.ZERO
static func delta_to_facing(delta: Vector2i) -> String:
match delta:
Vector2i(0, -1): return "North"
Vector2i(1, -1): return "Northeast"
Vector2i(1, 0): return "East"
Vector2i(1, 1): return "Southeast"
Vector2i(0, 1): return "South"
Vector2i(-1, 1): return "Southwest"
Vector2i(-1, 0): return "West"
Vector2i(-1, -1): return "Northwest"
_: return "North"
Vector2i(0, -1):
return "North"
Vector2i(1, -1):
return "Northeast"
Vector2i(1, 0):
return "East"
Vector2i(1, 1):
return "Southeast"
Vector2i(0, 1):
return "South"
Vector2i(-1, 1):
return "Southwest"
Vector2i(-1, 0):
return "West"
Vector2i(-1, -1):
return "Northwest"
_:
return "North"
+63 -24
View File
@@ -40,12 +40,25 @@ const OUTLINE_SHADER_PATH := BASE_PATH + "shaders/outline.gdshader"
## All body segment names in assembly order. D-160: 14 base + 2 swappable torso + 2 face = 18.
## torso_upper is loaded and hidden by default; clothing coverage reveals it.
const ALL_SEGMENTS: Array[String] = [
"head", "neck", "torso_upper", "torso", "hips",
"arm_upper_l", "arm_upper_r", "arm_lower_l", "arm_lower_r",
"hand_l", "hand_r",
"leg_upper_l", "leg_upper_r", "leg_lower_l", "leg_lower_r",
"foot_l", "foot_r",
"eyes", "eyebrows",
"head",
"neck",
"torso_upper",
"torso",
"hips",
"arm_upper_l",
"arm_upper_r",
"arm_lower_l",
"arm_lower_r",
"hand_l",
"hand_r",
"leg_upper_l",
"leg_upper_r",
"leg_lower_l",
"leg_lower_r",
"foot_l",
"foot_r",
"eyes",
"eyebrows",
]
## Segments that do NOT receive the skin tone shader — preserve original embedded material.
@@ -107,14 +120,14 @@ var _overhead_attachment: BoneAttachment3D = null
# Inspectable state for tests
var _active_torso_variant: String = "full"
var _active_coverages: Dictionary = {} # item_id -> coverage dict
var _loaded_slots: Array[String] = [] # "hair", "facial_hair", etc.
var _active_coverages: Dictionary = {} # item_id -> coverage dict
var _loaded_slots: Array[String] = [] # "hair", "facial_hair", etc.
var _toon_shader: Shader = null
var _toon_masked_shader: Shader = null
var _outline_shader: Shader = null
var _white_mask: ImageTexture = null # 1x1 white pixel — forces full-body tinting
var _iris_mask: Texture2D = null # iris-only mask from T_Eye_Split.png
var _iris_mask: Texture2D = null # iris-only mask from T_Eye_Split.png
func _ready() -> void:
@@ -140,6 +153,7 @@ func _load_shaders() -> void:
# Public API
# =============================================================================
## Rebuild the full character from a CharacterVisualDescriptor.
func load_descriptor(descriptor: CharacterVisualDescriptor) -> void:
_clear()
@@ -168,8 +182,14 @@ func set_facing(direction: Variant) -> void:
rotation.y = -atan2((direction as Vector2).x, (direction as Vector2).y)
elif direction is String:
var angles: Dictionary = {
"south": 0.0, "southwest": 45.0, "west": 90.0, "northwest": 135.0,
"north": 180.0, "northeast": -135.0, "east": -90.0, "southeast": -45.0,
"south": 0.0,
"southwest": 45.0,
"west": 90.0,
"northwest": 135.0,
"north": 180.0,
"northeast": -135.0,
"east": -90.0,
"southeast": -45.0,
}
rotation_degrees.y = angles.get((direction as String).to_lower(), 0.0)
@@ -232,6 +252,7 @@ func get_overhead_anchor() -> Marker3D:
# Internal — teardown
# =============================================================================
func _clear() -> void:
# Outline nodes are duplicates of body/clothing meshes — must be freed FIRST,
# before the source meshes are removed. _rebuild_outlines() is not called here
@@ -287,6 +308,7 @@ func _clear() -> void:
# Internal — skeleton
# =============================================================================
func _load_skeleton() -> void:
if not ResourceLoader.exists(SKELETON_PATH):
push_error("CharacterVisual: skeleton not found at %s" % SKELETON_PATH)
@@ -317,7 +339,12 @@ func _validate_slot_bones() -> void:
for slot: String in SLOT_TO_BONE:
var bone_name: String = SLOT_TO_BONE[slot]
if _skeleton.find_bone(bone_name) == -1:
push_warning("CharacterVisual: SLOT_TO_BONE['%s'] = '%s' — bone not found in skeleton" % [slot, bone_name])
push_warning(
(
"CharacterVisual: SLOT_TO_BONE['%s'] = '%s' — bone not found in skeleton"
% [slot, bone_name]
)
)
## #712: Create a Marker3D anchored ~0.3m above the Head bone via BoneAttachment3D.
@@ -344,6 +371,7 @@ func _create_overhead_anchor() -> void:
# Internal — body segments (D-160)
# =============================================================================
func _load_body_segments(desc: CharacterVisualDescriptor) -> void:
var body_dir := BASE_PATH + "bodies/%s/" % desc.body_type_key()
var tone := SKIN_TONES[clampi(desc.skin_tone, 0, SKIN_TONES.size() - 1)]
@@ -420,6 +448,7 @@ func _apply_body_shader(mi: MeshInstance3D, seg_name: String, tone: Dictionary)
# Internal — head, hair, facial hair, eyebrows (BoneAttachment3D) (D-161)
# =============================================================================
func _load_head(desc: CharacterVisualDescriptor) -> void:
if desc.head_id.is_empty():
return
@@ -451,7 +480,9 @@ func _load_eyebrows(_desc: CharacterVisualDescriptor) -> void:
pass
func _attach_to_bone(path: String, bone_name: String, tint: Color = Color.WHITE, render_priority: int = 0) -> BoneAttachment3D:
func _attach_to_bone(
path: String, bone_name: String, tint: Color = Color.WHITE, _render_priority: int = 0
) -> BoneAttachment3D:
if _skeleton == null:
return null
if not ResourceLoader.exists(path):
@@ -502,14 +533,13 @@ func _attach_to_bone(path: String, bone_name: String, tint: Color = Color.WHITE,
_apply_tinted_shader(mi, tint, mask_tex)
inst.queue_free()
return null
else:
# Unskinned — rigid attachment via BoneAttachment3D
for mi in meshes:
mi.get_parent().remove_child(mi)
mi.owner = null
attachment.add_child(mi)
_apply_tinted_shader(mi, tint, mask_tex)
inst.queue_free()
# Unskinned — rigid attachment via BoneAttachment3D
for mi in meshes:
mi.get_parent().remove_child(mi)
mi.owner = null
attachment.add_child(mi)
_apply_tinted_shader(mi, tint, mask_tex)
inst.queue_free()
return attachment
@@ -517,6 +547,7 @@ func _attach_to_bone(path: String, bone_name: String, tint: Color = Color.WHITE,
# Internal — clothing (D-162): coverage.json → segment hiding + torso variant
# =============================================================================
func _load_clothing(desc: CharacterVisualDescriptor) -> void:
if _skeleton == null or desc.clothing_slots.is_empty():
return
@@ -566,7 +597,6 @@ func _load_clothing(desc: CharacterVisualDescriptor) -> void:
# Hiding is reserved for amputation/prosthetics via the debug tab or game logic.
func _read_coverage(path: String) -> Dictionary:
if not FileAccess.file_exists(path):
return {}
@@ -608,6 +638,7 @@ func _apply_clothing_shader(mi: MeshInstance3D, tints: Array, mask_tex: Texture2
# Internal — accessories (BoneAttachment3D per slot→bone)
# =============================================================================
func _load_accessories(desc: CharacterVisualDescriptor) -> void:
for slot: String in desc.accessory_slots:
var item_id: String = desc.accessory_slots[slot]
@@ -629,7 +660,10 @@ func _load_accessories(desc: CharacterVisualDescriptor) -> void:
# Internal — tinting (hair, accessories, bone-attached assets with tint)
# =============================================================================
func _apply_tinted_shader(mi: MeshInstance3D, tint: Color, mask_tex: Texture2D = null, render_priority: int = 0) -> void:
func _apply_tinted_shader(
mi: MeshInstance3D, tint: Color, mask_tex: Texture2D = null, _render_priority: int = 0
) -> void:
if mi.mesh == null:
return
for surf in range(mi.mesh.get_surface_count()):
@@ -656,6 +690,7 @@ func _apply_tinted_shader(mi: MeshInstance3D, tint: Color, mask_tex: Texture2D =
# Internal — outline pass (inverted hull, cull_front)
# =============================================================================
func _rebuild_outlines() -> void:
for node in _outline_nodes:
if is_instance_valid(node):
@@ -692,6 +727,7 @@ func _rebuild_outlines() -> void:
# Animation
# =============================================================================
func _load_animations() -> void:
if _skeleton == null:
return
@@ -763,6 +799,7 @@ func stop_animation() -> void:
# Static helpers
# =============================================================================
static func _find_skeleton(root: Node) -> Skeleton3D:
if root is Skeleton3D:
return root as Skeleton3D
@@ -790,7 +827,9 @@ static func _get_albedo_texture(mat: Material) -> Texture2D:
if mat is BaseMaterial3D:
return (mat as BaseMaterial3D).albedo_texture
if mat is ShaderMaterial:
for p: String in ["albedo_tex", "albedo_texture", "texture_albedo", "Hair_Texture", "BaseColor"]:
for p: String in [
"albedo_tex", "albedo_texture", "texture_albedo", "Hair_Texture", "BaseColor"
]:
var val: Variant = (mat as ShaderMaterial).get_shader_parameter(p)
if val is Texture2D:
return val as Texture2D
@@ -166,6 +166,7 @@ func to_dict() -> Dictionary:
# -- Color serialization helpers --
# Wire format: [r, g, b, a] float array (rmp_serde serializes Color as tuple).
static func _decode_color(value: Variant, fallback: Color) -> Color:
if value is Array and value.size() >= 3:
return Color(value[0], value[1], value[2], value[3] if value.size() >= 4 else 1.0)
@@ -198,5 +199,3 @@ static func _encode_tint_map(data: Dictionary) -> Dictionary:
encoded.append(_encode_color(c))
result[key] = encoded
return result
+98 -38
View File
@@ -1,23 +1,15 @@
class_name CursorRenderer
extends Node2D
extends GameplayRenderer
## Cursor state machine — 4 geometric states, 150ms linear transitions (D-056).
## Insert-styled cursor on z-layer 7 (UILayer CanvasLayer).
## Detects entity hover via world-space proximity to visible entities.
enum State { DEFAULT, ENTITY_HOVER, OBJECT_HOVER, WEAPON_AIM }
# --- Public ---
var current_state: State = State.DEFAULT
var hovered_entity_id: int = -1
var weapon_mode_active: bool = false
# OQ-07 (#522): when false, verb labels are suppressed (should_show_interactions → false).
# Cursor shape transitions still fire — the character's body still orients to targets.
var insert_active: bool = true
signal state_changed(new_state: State)
signal state_changed(new_state: int)
signal hovered_entity_changed(entity_id: int)
enum State { DEFAULT, ENTITY_HOVER, OBJECT_HOVER, WEAPON_AIM }
# D-056 colors
const COLOR_DEFAULT := Color("#c8d0e0")
const COLOR_OBJECT := Color("#8b8ba0")
@@ -31,6 +23,14 @@ const HOVER_RADIUS_PX := 16.0 # World pixels — ~half a tile
const BRACKET_HALF := 26.0
const BRACKET_ARM := 8.0
# --- Public ---
var current_state: State = State.DEFAULT
var hovered_entity_id: int = -1
var weapon_mode_active: bool = false
# OQ-07 (#522): when false, verb labels are suppressed (should_show_interactions → false).
# Cursor shape transitions still fire — the character's body still orients to targets.
var insert_active: bool = true
# --- Transition state ---
var _target: State = State.DEFAULT
var _t: float = 1.0
@@ -54,8 +54,9 @@ var _bracket_a: float = 0.0
var _alpha: float = 0.45
func _ready() -> void:
func _renderer_ready() -> void:
Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)
z_index = 100 # D-170: cursor must always render above all HUD/implant layers
_from = _snapshot()
@@ -68,7 +69,7 @@ func _notification(what: int) -> void:
visible = true
func _process(delta: float) -> void:
func _gameplay_process(delta: float) -> void:
if not _mouse_inside:
return
_time += delta
@@ -84,6 +85,7 @@ func _process(delta: float) -> void:
# --- Hover detection (automatic, from GameState.visible_entities) ---
func _detect_hover() -> void:
var prev_id := hovered_entity_id
@@ -115,7 +117,7 @@ func _find_nearest_entity() -> Dictionary:
var mouse_world: Vector2 = xform.affine_inverse() * mouse_screen
var best_dist := INF
var result := { id = -1, kind = "", color = COLOR_DEFAULT, offset = Vector2.ZERO }
var result := {id = -1, kind = "", color = COLOR_DEFAULT, offset = Vector2.ZERO}
for entity in GameState.visible_entities:
if not entity.has("entity_id") or not entity.has("x") or not entity.has("y"):
@@ -138,6 +140,7 @@ func _find_nearest_entity() -> Dictionary:
# --- State transitions ---
func _set_target(new_state: State) -> void:
if new_state == _target:
return
@@ -154,29 +157,75 @@ func _set_target(new_state: State) -> void:
func _snapshot() -> Dictionary:
return { gap = _gap, len = _len, rot = _rot, thick = _thick,
color = _color, bloom = _bloom, bracket_a = _bracket_a, alpha = _alpha }
return {
gap = _gap,
len = _len,
rot = _rot,
thick = _thick,
color = _color,
bloom = _bloom,
bracket_a = _bracket_a,
alpha = _alpha
}
func _params_for(state: State) -> Dictionary:
match state:
State.ENTITY_HOVER:
return { gap = 10.0, len = 6.0, rot = 0.0, thick = 1.0,
color = _hover_color, bloom = 0.5, bracket_a = 1.0, alpha = 1.0 }
return {
gap = 10.0,
len = 6.0,
rot = 0.0,
thick = 1.0,
color = _hover_color,
bloom = 0.5,
bracket_a = 1.0,
alpha = 1.0
}
State.OBJECT_HOVER:
return { gap = 4.0, len = 6.0, rot = PI / 4.0, thick = 1.0,
color = _hover_color, bloom = 0.3, bracket_a = 0.0, alpha = 0.8 }
return {
gap = 4.0,
len = 6.0,
rot = PI / 4.0,
thick = 1.0,
color = _hover_color,
bloom = 0.3,
bracket_a = 0.0,
alpha = 0.8
}
State.WEAPON_AIM:
return { gap = 12.0, len = 9.0, rot = 0.0, thick = 2.0,
color = COLOR_WEAPON, bloom = 0.0, bracket_a = 0.0, alpha = 1.0 }
return {
gap = 12.0,
len = 9.0,
rot = 0.0,
thick = 2.0,
color = COLOR_WEAPON,
bloom = 0.0,
bracket_a = 0.0,
alpha = 1.0
}
_:
return { gap = 4.0, len = 6.0, rot = 0.0, thick = 1.0,
color = COLOR_DEFAULT, bloom = 0.4, bracket_a = 0.0, alpha = 0.45 }
return {
gap = 4.0,
len = 6.0,
rot = 0.0,
thick = 1.0,
color = COLOR_DEFAULT,
bloom = 0.4,
bracket_a = 0.0,
alpha = 0.45
}
func _apply_params(p: Dictionary) -> void:
_gap = p.gap; _len = p.len; _rot = p.rot; _thick = p.thick
_color = p.color; _bloom = p.bloom; _bracket_a = p.bracket_a; _alpha = p.alpha
_gap = p.gap
_len = p.len
_rot = p.rot
_thick = p.thick
_color = p.color
_bloom = p.bloom
_bracket_a = p.bracket_a
_alpha = p.alpha
func _interpolate() -> void:
@@ -193,8 +242,9 @@ func _interpolate() -> void:
# --- Drawing ---
func _draw() -> void:
# _hover_offset is computed in _detect_hover() during _process(), not recalculated
func _gameplay_draw() -> void:
# _hover_offset is computed in _detect_hover() during _gameplay_process(), not recalculated
# here. This is safe because Camera2D (tree sibling, earlier in scene order) applies
# its smoothing transform before CursorRenderer._process() reads canvas_transform.
# Nothing modifies the canvas transform between _process() and _draw().
@@ -233,13 +283,19 @@ func _draw_brackets(offset: Vector2, color: Color) -> void:
# --- Test-friendly API (expected by test_cursor_states.gd) ---
func get_state() -> String:
match current_state:
State.DEFAULT: return "Default"
State.ENTITY_HOVER: return "EntityHover"
State.OBJECT_HOVER: return "ObjectHover"
State.WEAPON_AIM: return "WeaponAim"
_: return "Default"
State.DEFAULT:
return "Default"
State.ENTITY_HOVER:
return "EntityHover"
State.OBJECT_HOVER:
return "ObjectHover"
State.WEAPON_AIM:
return "WeaponAim"
_:
return "Default"
func set_hover_target(data: Dictionary) -> void:
@@ -252,10 +308,14 @@ func set_hover_target(data: Dictionary) -> void:
if kind == "Npc":
var rel: String = data.get("relationship", "Unknown")
match rel:
"Friendly": _hover_color = Constants.ENTITY_COLOR_FRIENDLY
"PersonOfInterest": _hover_color = Constants.ENTITY_COLOR_POI
"Hostile": _hover_color = Constants.ENTITY_COLOR_HOSTILE
_: _hover_color = Constants.ENTITY_COLOR_UNKNOWN
"Friendly":
_hover_color = Constants.ENTITY_COLOR_FRIENDLY
"PersonOfInterest":
_hover_color = Constants.ENTITY_COLOR_POI
"Hostile":
_hover_color = Constants.ENTITY_COLOR_HOSTILE
_:
_hover_color = Constants.ENTITY_COLOR_UNKNOWN
_target = State.ENTITY_HOVER
_t = 1.0
_apply_params(_params_for(State.ENTITY_HOVER))
+29 -18
View File
@@ -1,5 +1,5 @@
class_name EntityRenderer
extends Node2D
extends GameplayRenderer
# Entity renderer — manages entity sprites under the Entities node
# Creates/updates/removes Sprite2D children based on entity data
@@ -18,28 +18,28 @@ const TILE_SIZE: int = Constants.TILE_SIZE
# D-044: 24x32 entity footprint within 32x32 visual tile (64x64 source at 0.5 scale = 32px runtime)
const ENTITY_WIDTH: int = 24
const ENTITY_HEIGHT: int = 32
const ENTITY_OFFSET_X: float = 0.0 # sprite fills tile width at 0.5 scale
const ENTITY_OFFSET_X: float = 0.0 # sprite fills tile width at 0.5 scale
const ENTITY_OFFSET_Y: float = TILE_SIZE - ENTITY_HEIGHT # feet-anchored for correct y-sort with D-019 tilt
# Lerp speed — framerate-independent exponential smoothing.
# At 12.0: ~70% there after 0.1s, ~95% after 0.25s.
# Fast enough for Sprint snappiness, slow enough for Walk to show sliding.
const LERP_SPEED: float = 12.0
# #521: Color transition duration in seconds (D-033: "0.5s fade")
const COLOR_FADE_DURATION: float = 0.5
var entity_nodes: Dictionary = {} # entity_id -> Node2D
var _entity_targets: Dictionary = {} # entity_id -> Vector2 (target pixel position)
var entity_nodes: Dictionary = {} # entity_id -> Node2D
var _entity_targets: Dictionary = {} # entity_id -> Vector2 (target pixel position)
var _entity_relationships: Dictionary = {} # #521: entity_id -> String (last relationship)
var _entity_tweens: Dictionary = {} # #521: entity_id -> {from: Color, target: Color, elapsed: float}
var _entity_facing: Dictionary = {} # #540: entity_id -> String ("north"/"east"/"south"/"west")
# #521: Color transition duration in seconds (D-033: "0.5s fade")
const COLOR_FADE_DURATION: float = 0.5
func _ready() -> void:
func _renderer_ready() -> void:
print("EntityRenderer: Initialized")
func _process(delta: float) -> void:
func _gameplay_process(delta: float) -> void:
# Lerp all entity visual positions toward their targets each frame.
# Uses framerate-independent exponential smoothing.
var weight := 1.0 - exp(-LERP_SPEED * delta)
@@ -111,7 +111,12 @@ func _create_entity_node(entity_id: int, entity_data: Dictionary) -> void:
_entity_facing[entity_id] = direction
var tex := _load_sprite_texture(direction)
if tex == null:
push_error("EntityRenderer: no texture for entity %d direction '%s' — entity will be invisible" % [entity_id, direction])
push_error(
(
"EntityRenderer: no texture for entity %d direction '%s' — entity will be invisible"
% [entity_id, direction]
)
)
entity_node.texture = tex
# D-033: self_modulate for relationship tinting; modulate.a is reserved for D-015 dimming.
@@ -220,10 +225,14 @@ func _entity_direction(entity_id: int, _entity_data: Dictionary) -> String:
# N/NW → north, NE/E → east, SE/S → south, SW/W → west
static func _octant_to_direction(octant: String) -> String:
match octant:
"North", "Northwest": return "north"
"Northeast", "East": return "east"
"Southeast", "South": return "south"
"Southwest", "West": return "west"
"North", "Northwest":
return "north"
"Northeast", "East":
return "east"
"Southeast", "South":
return "south"
"Southwest", "West":
return "west"
_:
push_warning("EntityRenderer: unrecognised octant '%s' — defaulting to south" % octant)
return "south"
@@ -247,11 +256,13 @@ func _add_facing_indicator(parent_node: Node2D) -> void:
var s := Constants.FACING_INDICATOR_SIZE
var offset := Constants.FACING_INDICATOR_OFFSET
# Triangle pointing up (North), offset from center. Rotates around (0,0).
indicator.polygon = PackedVector2Array([
Vector2(0, -offset - s),
Vector2(-s * 0.6, -offset + s * 0.4),
Vector2(s * 0.6, -offset + s * 0.4),
])
indicator.polygon = PackedVector2Array(
[
Vector2(0, -offset - s),
Vector2(-s * 0.6, -offset + s * 0.4),
Vector2(s * 0.6, -offset + s * 0.4),
]
)
indicator.color = Constants.ENTITY_COLOR_PLAYER
# Sprite2D local space: 64px texture at scale 0.5 → center of visible sprite at (32,32).
# Indicator rotates around this point to track player facing direction.
+22 -24
View File
@@ -1,5 +1,5 @@
class_name FogEntities
extends Node2D
extends GameplayRenderer
## Fog entity visualization — renders entities undergoing cognitive delay recognition
## in the fog layer. Between FogOverlay (z:900) and InsertOverlay (CanvasLayer 10).
@@ -17,25 +17,25 @@ extends Node2D
const TILE_SIZE: int = Constants.TILE_SIZE
# D-059: Fog entity colors
const COLOR_UNRECOGNIZED := Color("#555566") # Neutral grey blob
const COLOR_UNRECOGNIZED := Color("#555566") # Neutral grey blob
# Intentionally matches Constants.INSERT_COLOR_TEXT / cursor default (#c8d0e0).
# Sonar pings are insert-generated — same visual language as cursor and HUD overlays.
const COLOR_PING := Color("#c8d0e0") # Insert white-blue (D-048/D-056)
const COLOR_PING := Color("#c8d0e0") # Insert white-blue (D-048/D-056)
# Animation timing
const PULSE_PERIOD: float = 0.8 # Breathing pulse cycle (seconds)
const PULSE_MIN_ALPHA: float = 0.4 # Min alpha during breathing
const PULSE_MAX_ALPHA: float = 0.8 # Max alpha during breathing
const PING_DURATION: float = 1.5 # Sound ping expand + fade (seconds)
const PING_MAX_RADIUS: float = 24.0 # Max ring expand radius (pixels)
const PING_RING_COUNT: int = 3 # Concentric rings per ping
const PING_RING_WIDTH: float = 1.5 # Ring line width (pixels)
const DRIFT_RANGE: float = 0.5 # ±0.5 tile position drift (D-059)
const DRIFT_PERIOD: float = 2.0 # Seconds per drift wander
const PULSE_PERIOD: float = 0.8 # Breathing pulse cycle (seconds)
const PULSE_MIN_ALPHA: float = 0.4 # Min alpha during breathing
const PULSE_MAX_ALPHA: float = 0.8 # Max alpha during breathing
const PING_DURATION: float = 1.5 # Sound ping expand + fade (seconds)
const PING_MAX_RADIUS: float = 24.0 # Max ring expand radius (pixels)
const PING_RING_COUNT: int = 3 # Concentric rings per ping
const PING_RING_WIDTH: float = 1.5 # Ring line width (pixels)
const DRIFT_RANGE: float = 0.5 # ±0.5 tile position drift (D-059)
const DRIFT_PERIOD: float = 2.0 # Seconds per drift wander
# Entity blob rendering
const BLOB_RADIUS: float = 10.0
const SILHOUETTE_SCALE: float = 1.3 # Silhouette slightly larger than blob
const SILHOUETTE_SCALE: float = 1.3 # Silhouette slightly larger than blob
# Transition thresholds: recognition progress mapped from remaining_ticks/total_delay_ticks.
# Color transition starts at 50% to compress the visual change into ~0.3s (D-060).
const COLOR_TRANSITION_START: float = 0.5
@@ -45,12 +45,12 @@ const SILHOUETTE_APPEAR_THRESHOLD: float = 0.3
const SILHOUETTE_SIZE := Vector2(6.0, 10.0)
# Internal state — no child nodes, pure data + _draw()
var _entities: Dictionary = {} # entity_id -> {pos, drift_offset, drift_target, drift_timer, progress}
var _pings: Array = [] # [{pos: Vector2, elapsed: float}]
var _entities: Dictionary = {} # entity_id -> {pos, drift_offset, drift_target, drift_timer, progress}
var _pings: Array = [] # [{pos: Vector2, elapsed: float}]
var _time: float = 0.0
func _process(delta: float) -> void:
func _gameplay_process(delta: float) -> void:
# Early return when idle — skip queue_redraw() when nothing to draw
if _entities.is_empty() and _pings.is_empty():
return
@@ -118,11 +118,10 @@ func update_from_state() -> void:
_entities.erase(eid)
func _draw() -> void:
func _gameplay_draw() -> void:
# Breathing pulse — shared across all entities
var pulse_t := fmod(_time, PULSE_PERIOD) / PULSE_PERIOD
var pulse_alpha := lerpf(PULSE_MIN_ALPHA, PULSE_MAX_ALPHA,
0.5 + 0.5 * sin(pulse_t * TAU))
var pulse_alpha := lerpf(PULSE_MIN_ALPHA, PULSE_MAX_ALPHA, 0.5 + 0.5 * sin(pulse_t * TAU))
# Draw entity blobs
for eid in _entities.keys():
@@ -132,7 +131,9 @@ func _draw() -> void:
# Color transition: grey → D-033 teal based on recognition progress
# Transition begins at 50% progress (D-060: ~0.3s visual transition within delay window)
var progress: float = e.progress
var color_t: float = clampf((progress - COLOR_TRANSITION_START) / (1.0 - COLOR_TRANSITION_START), 0.0, 1.0)
var color_t: float = clampf(
(progress - COLOR_TRANSITION_START) / (1.0 - COLOR_TRANSITION_START), 0.0, 1.0
)
var blob_color: Color = COLOR_UNRECOGNIZED.lerp(Constants.ENTITY_COLOR_UNKNOWN, color_t)
blob_color.a = pulse_alpha
@@ -172,7 +173,4 @@ func _draw() -> void:
func _random_drift() -> Vector2:
return Vector2(
randf_range(-DRIFT_RANGE, DRIFT_RANGE),
randf_range(-DRIFT_RANGE, DRIFT_RANGE)
)
return Vector2(randf_range(-DRIFT_RANGE, DRIFT_RANGE), randf_range(-DRIFT_RANGE, DRIFT_RANGE))
+11 -4
View File
@@ -5,13 +5,14 @@ extends Node2D
## Architecture: docs/architecture/fog-shader-spec.md
signal fog_noise_ready
const TILE_SIZE := float(Constants.TILE_SIZE)
var _noise_ready: bool = false
var _fog_rect: ColorRect
var _shader_mat: ShaderMaterial
const TILE_SIZE := float(Constants.TILE_SIZE)
func _ready() -> void:
# Create the fog overlay ColorRect — transparent fallback so a shader failure
@@ -40,7 +41,11 @@ func _ready() -> void:
noise_tex.width = 256
noise_tex.height = 256
noise_tex.seamless = true
noise_tex.changed.connect(func(): _noise_ready = true; fog_noise_ready.emit())
noise_tex.changed.connect(
func():
_noise_ready = true
fog_noise_ready.emit()
)
_shader_mat.set_shader_parameter("noise_tex", noise_tex)
_shader_mat.set_shader_parameter("tile_size", TILE_SIZE)
@@ -73,6 +78,8 @@ func update_fog() -> void:
_shader_mat.set_shader_parameter("rect_sz", _fog_rect.size)
_shader_mat.set_shader_parameter("map_offset", Vector2(FogState.map_bounds.position))
_shader_mat.set_shader_parameter("map_size", Vector2(FogState.map_bounds.size))
var t: float = FogState.override_time if FogState.override_time >= 0.0 else Time.get_ticks_msec() / 1000.0
var t: float = (
FogState.override_time if FogState.override_time >= 0.0 else Time.get_ticks_msec() / 1000.0
)
_shader_mat.set_shader_parameter("time", t)
_shader_mat.set_shader_parameter("debug_exploration", FogState.debug_exploration)
@@ -0,0 +1,53 @@
class_name GameplayRenderer
extends Node2D
## Base class for renderers that should pause when a fullscreen implant app
## covers the gameplay view (D-170).
##
## Subclasses override _gameplay_process(delta) and _gameplay_draw() instead
## of _process() and _draw(). These are only called when gameplay is visible.
##
## Usage:
## extends GameplayRenderer
## func _gameplay_process(delta: float) -> void: ...
## func _gameplay_draw() -> void: ...
var gameplay_occluded: bool = false
func _ready() -> void:
HudGroups.gameplay_occluded.connect(_on_gameplay_occluded)
_renderer_ready()
## Override this instead of _ready() in subclasses.
func _renderer_ready() -> void:
pass
func _on_gameplay_occluded(occluded: bool) -> void:
gameplay_occluded = occluded
if occluded:
# Force a blank redraw so stale frames don't linger
queue_redraw()
func _process(delta: float) -> void:
if gameplay_occluded:
return
_gameplay_process(delta)
func _draw() -> void:
if gameplay_occluded:
return
_gameplay_draw()
## Override in subclasses — called every frame when gameplay is visible.
func _gameplay_process(_delta: float) -> void:
pass
## Override in subclasses — called for draw when gameplay is visible.
func _gameplay_draw() -> void:
pass
@@ -1,5 +1,5 @@
class_name SoundIndicatorRenderer
extends Node2D
extends GameplayRenderer
## Medium-range sound indicators (#126, D-018).
## Renders directional arrows at the fog boundary for sounds outside LOS.
@@ -20,21 +20,22 @@ extends Node2D
const TILE_SIZE: int = Constants.TILE_SIZE
# Visual parameters
const INDICATOR_LIFETIME: float = 3.5 # Total seconds visible
const FADE_DURATION: float = 0.6 # Fade-out window at end
const EDGE_INSET: float = 20.0 # Pixels inward from viewport edge
const ARROW_HALF: float = 7.0 # Half-width of arrowhead base
const ARROW_LEN: float = 12.0 # Length from tip to base
const INDICATOR_LIFETIME: float = 3.5 # Total seconds visible
const FADE_DURATION: float = 0.6 # Fade-out window at end
const EDGE_INSET: float = 20.0 # Pixels inward from viewport edge
const ARROW_HALF: float = 7.0 # Half-width of arrowhead base
const ARROW_LEN: float = 12.0 # Length from tip to base
# D-018/D-069 colors — sourced from Constants to prevent palette drift
const COLOR_NEUTRAL: Color = Constants.INSERT_COLOR_TEXT # Generic / footstep
const COLOR_VOICE: Color = Constants.ENTITY_COLOR_POI # Speech / conversation
const COLOR_NEUTRAL: Color = Constants.INSERT_COLOR_TEXT # Generic / footstep
const COLOR_VOICE: Color = Constants.ENTITY_COLOR_POI # Speech / conversation
const COLOR_DANGER: Color = Constants.ENTITY_COLOR_HOSTILE # Alert / threat / gunshot
# Indicators: [{x, y, event_type, elapsed}]
var _indicators: Array = []
func _process(delta: float) -> void:
func _gameplay_process(delta: float) -> void:
if _indicators.is_empty():
return
@@ -68,17 +69,22 @@ func update_sound_events(events: Array) -> void:
found = true
break
if not found:
_indicators.append({
"x": ex,
"y": ey,
"event_type": evt.get("event_type", ""),
"elapsed": 0.0,
})
(
_indicators
. append(
{
"x": ex,
"y": ey,
"event_type": evt.get("event_type", ""),
"elapsed": 0.0,
}
)
)
if not _indicators.is_empty():
queue_redraw()
func _draw() -> void:
func _gameplay_draw() -> void:
if _indicators.is_empty():
return
@@ -144,9 +150,19 @@ func _draw_arrow(pos: Vector2, dir: Vector2, color: Color) -> void:
## Map event type string → D-018 color category.
func color_for_type(event_type: String) -> Color:
var et := event_type.to_lower()
if et.contains("voice") or et.contains("speech") or et.contains("convers") or et.contains("talk"):
if (
et.contains("voice")
or et.contains("speech")
or et.contains("convers")
or et.contains("talk")
):
return COLOR_VOICE
if et.contains("danger") or et.contains("gunshot") or et.contains("explosion") \
or et.contains("alert") or et.contains("threat"):
if (
et.contains("danger")
or et.contains("gunshot")
or et.contains("explosion")
or et.contains("alert")
or et.contains("threat")
):
return COLOR_DANGER
return COLOR_NEUTRAL
+13 -4
View File
@@ -11,11 +11,11 @@ extends TileMapLayer
# (3,0) = object — teal
# (4,0) = reset_plate — amber (#502)
enum TileType { FLOOR = 0, WALL = 1, DOOR = 2, OBJECT = 3, RESET_PLATE = 4 }
const TILE_SIZE: int = Constants.TILE_SIZE
const GROUND_FLOOR: int = 0 # Server floor level for ground — filter target in update_tiles()
enum TileType { FLOOR = 0, WALL = 1, DOOR = 2, OBJECT = 3, RESET_PLATE = 4 }
# Wire-format string to TileType mapping
const TILE_TYPE_MAP: Dictionary = {
"floor": TileType.FLOOR,
@@ -27,11 +27,13 @@ const TILE_TYPE_MAP: Dictionary = {
var _initialized: bool = false
func _ready() -> void:
_setup_tileset()
_initialized = true
print("TileRenderer: Initialized")
# Build a programmatic TileSet with colored placeholder tiles
func _setup_tileset() -> void:
var ts := TileSet.new()
@@ -63,6 +65,7 @@ func _setup_tileset() -> void:
var source_id := ts.add_source(source)
tile_set = ts
# Update tiles from snapshot data
# tiles: Array of {x: int, y: int, z: int, type: String, visibility: String (optional)}
# z here is the server-side FLOOR LEVEL (0 = ground, 1 = first floor, etc.),
@@ -93,19 +96,25 @@ func update_tiles(tiles: Array) -> void:
var tile_type_str: String = tile_data.type
if not TILE_TYPE_MAP.has(tile_type_str):
push_warning("TileRenderer: unknown tile type '%s' at (%d, %d)" % [
tile_type_str, tile_data.x, tile_data.y])
push_warning(
(
"TileRenderer: unknown tile type '%s' at (%d, %d)"
% [tile_type_str, tile_data.x, tile_data.y]
)
)
continue
var atlas_x: int = TILE_TYPE_MAP[tile_type_str]
var coords := Vector2i(tile_data.x, tile_data.y)
set_cell(coords, 0, Vector2i(atlas_x, 0))
# Fill a tile region with a solid color
func _fill_tile(img: Image, tile_index: int, color: Color) -> void:
var rect := Rect2i(tile_index * TILE_SIZE, 0, TILE_SIZE, TILE_SIZE)
img.fill_rect(rect, color)
# Fill a tile region with a color and a 1px border
func _fill_tile_with_border(img: Image, tile_index: int, fill: Color, border: Color) -> void:
var x_offset := tile_index * TILE_SIZE
+7 -3
View File
@@ -1,4 +1,4 @@
extends Node2D
extends GameplayRenderer
# World renderer — manages all visual representation from GameState
# Attached to the World node in main.tscn
@@ -13,19 +13,23 @@ extends Node2D
# Overhead (Node2D) — z:300 ceiling/upper structure (placeholder)
# FogOverlay (Node2D) — z:900 fog shader (OUTSIDE FogGroup)
var _last_tick: int = -1
@onready var tile_renderer = $FogGroup/FloorTiles
@onready var fog_renderer = $FogOverlay
@onready var entity_renderer = $FogGroup/YSortGroup/Entities
@onready var sound_indicator_renderer = $SoundIndicators # #126 D-018 medium-range indicators
var _last_tick: int = -1
func _ready() -> void:
func _renderer_ready() -> void:
print("WorldRenderer: Initialized (D-049 z-stack)")
# Called each frame to update visuals from game state.
# Uses tick-based invalidation — re-renders all layers when a new snapshot arrives.
func update_from_state() -> void:
if gameplay_occluded:
return # D-170: skip rendering while fullscreen implant app is active
var tick := GameState.current_tick
if tick == _last_tick:
return
+193
View File
@@ -0,0 +1,193 @@
class_name SnapshotConsumers
## Non-dialogue snapshot consumers and event handlers extracted from main.gd (#775).
##
## Registered with SnapshotEventRouter; reads from GameState directly.
## UI node references passed via init(). All methods are zero-argument
## callables compatible with SnapshotEventRouter.
const LISTENING_FOCUS_TICKS: int = 30 # D-071: stationary ticks before ListeningFocus boost
var monologue_display: Node = null
var dialogue_box: Node = null
var examine_display: Node = null
var loading_screen: Node = null
var debug_console: Node = null
var cursor_renderer: Node = null
var interaction_list: Node = null
var interaction_prompt: Node = null
var minimap: Node = null
var star_map: Node = null
var _screen_flash_fn: Callable # Callable(color: Color, duration: float)
var _last_monologue_tick: int = -1
var _known_recognition_ids: Dictionary = {}
var _known_triangle_ids: Dictionary = {}
var _current_zone: String = ""
func init(refs: Dictionary, screen_flash: Callable) -> SnapshotConsumers:
monologue_display = refs.get("monologue_display")
dialogue_box = refs.get("dialogue_box")
examine_display = refs.get("examine_display")
loading_screen = refs.get("loading_screen")
debug_console = refs.get("debug_console")
cursor_renderer = refs.get("cursor_renderer")
interaction_list = refs.get("interaction_list")
interaction_prompt = refs.get("interaction_prompt")
minimap = refs.get("minimap")
star_map = refs.get("star_map")
_screen_flash_fn = screen_flash
return self
# OQ-07 (#522): Propagate insert state to all z-layer-6 display nodes.
func propagate_insert_state() -> void:
var insert_state := GameState.insert_active
if cursor_renderer:
cursor_renderer.set_insert_active(insert_state)
if interaction_list:
interaction_list.set_insert_active(insert_state)
if interaction_prompt:
interaction_prompt.set_insert_active(insert_state)
if minimap:
minimap.set_insert_active(insert_state)
if star_map:
star_map.set_insert_active(insert_state)
# D-057: Update interaction list from game state.
# Suppress during dialogue — player is in conversation, verb list is noise.
func update_interaction_list() -> void:
if not interaction_list:
return
if dialogue_box and dialogue_box.is_dialogue_active():
if interaction_list.is_showing():
interaction_list.hide_list()
else:
interaction_list.update_from_state()
# D-018 #125: Play close-range sound events — fired once per snapshot tick.
func play_close_sound_events() -> void:
for evt in GameState.close_sound_events:
if not evt is Dictionary or not evt.has("x") or not evt.has("y"):
continue
AudioManager.play_sound_event(
evt.get("event_type", ""), Vector2(float(evt.x), float(evt.y))
)
GameState.close_sound_events = []
# D-067: Recognition chime — fires sfx_monologue_chime when a fog entity
# enters the cognitive delay recognition queue for the first time.
func play_recognition_chimes() -> void:
for rec in GameState.pending_recognitions:
if not rec is Dictionary or not rec.has("entity_id"):
continue
var eid: int = rec.entity_id
if not _known_recognition_ids.has(eid):
_known_recognition_ids[eid] = true
AudioManager.play(AudioManager.CHIME_RECOGNITION)
# #590 D-072/D-089: Triangle activation consumer.
func handle_triangle_crisis_events() -> void:
var events: Array = GameState.current_snapshot.get("triangle_crisis_events", [])
for ev in events:
if not ev is Dictionary or not ev.has("triangle_id"):
continue
var tid: int = ev.triangle_id
if not _known_triangle_ids.has(tid):
_known_triangle_ids[tid] = true
AudioManager.play(AudioManager.CHIME_ACTIVATION, AudioManager.BUS_UI_SOUNDS)
# D-073 (#529): Zone ambient crossfade.
func update_zone() -> void:
var zone := GameState.current_zone_id
if zone != _current_zone:
_current_zone = zone
AudioManager.set_zone(zone)
# D-071 (#530): ListeningFocus boost — World SFX +2.5dB when stationary 30+ ticks.
func update_listening_focus() -> void:
var current_dip := AudioManager.get_active_dip()
var threshold_met := GameState.stationary_ticks >= LISTENING_FOCUS_TICKS
if threshold_met and current_dip == "":
AudioManager.apply_dip("listening_focus")
elif not threshold_met and current_dip == "listening_focus":
AudioManager.clear_dip()
# Consume-once per tick: show monologue text, then clear.
func consume_monologue() -> void:
if GameState.current_monologue == null or not monologue_display:
return
if GameState.current_tick == _last_monologue_tick:
return
_last_monologue_tick = GameState.current_tick
var mono: Dictionary = GameState.current_monologue
monologue_display.show_monologue(
mono.get("text", ""),
mono.get("duration_seconds", 5.0),
mono.get("priority", 2),
mono.get("is_urgent", false)
)
# #502: Amber flash on room reset
var mono_id: String = mono.get("id", "")
if mono_id.begins_with("room_reset"):
_screen_flash_fn.call(Constants.ENTITY_COLOR_POI, 0.15)
GameState.current_monologue = null
# #554/#257: Show save/load result notification; hide loading screen on load complete.
func consume_save_result() -> void:
if GameState.save_result == null:
return
var result: Dictionary = GameState.save_result
GameState.save_result = null
if loading_screen:
loading_screen.hide_loading()
var msg: String
if result.get("success", false):
if result.get("kind", "") == "save":
msg = UIStrings.get_text("notifications.save_complete")
else:
msg = UIStrings.get_text("notifications.load_complete")
else:
if result.get("kind", "") == "save":
msg = UIStrings.get_text("notifications.save_failed")
else:
msg = UIStrings.get_text("notifications.load_failed")
if monologue_display:
monologue_display.show_notification(msg)
# #581: Forward debug_response from server to the debug console.
func consume_debug_response() -> void:
if GameState.debug_response == null or not debug_console:
return
debug_console.append_response(GameState.debug_response)
GameState.debug_response = null
# #174: Consume examine result — show overlay when server sends character-filtered observation.
func consume_examine_result() -> void:
if GameState.current_examine_result == null or not examine_display:
return
var result: Dictionary = GameState.current_examine_result
if dialogue_box and dialogue_box.is_dialogue_active():
if examine_display.has_method("dismiss"):
examine_display.dismiss()
else:
if examine_display.has_method("show_result"):
examine_display.show_result(result)
GameState.current_examine_result = null
## Clear session-scoped recognition state (call on teleport / room change).
func clear_recognition_state() -> void:
_known_recognition_ids.clear()
_known_triangle_ids.clear()
+277
View File
@@ -0,0 +1,277 @@
class_name SnapshotHandler
## Applies ObserverSnapshot data to GameState fields (D-020).
##
## Extracted from game_state.gd to separate snapshot parsing from state storage.
## All methods are static — no instance state required.
## Called via GameState.apply_snapshot() which delegates here.
# DEPRECATED: Client-side stationary_ticks fallback. Remove when server sends
# "stationary_ticks" in ObserverSnapshot (D-020 violation).
static var _prev_player_position: Vector2 = Vector2(-1e9, -1e9)
static func apply(snapshot: Dictionary) -> void:
GameState.current_snapshot = snapshot
if snapshot.has("tick"):
GameState.current_tick = snapshot.tick
if snapshot.has("entities"):
GameState.visible_entities = snapshot.entities
var found_player := false
for entity in GameState.visible_entities:
if (
entity.has("kind")
and entity.kind is Dictionary
and entity.kind.get("variant") == "Player"
):
GameState.player_position = Vector2(entity.x, entity.y)
if entity.has("entity_id"):
GameState.player_entity_id = entity.entity_id
found_player = true
break
if not found_player and GameState.visible_entities.size() > 0:
push_warning(
(
"GameState: no Player entity found in %d entities"
% [GameState.visible_entities.size()]
)
)
# D-020/D-071 (#530): Server-authoritative stationary_ticks for ListeningFocus boost.
if snapshot.has("stationary_ticks") and snapshot.stationary_ticks is int:
GameState.stationary_ticks = snapshot.stationary_ticks
else:
# DEPRECATED fallback — client-side accumulation. Remove when server sends field.
if GameState.player_position == _prev_player_position:
GameState.stationary_ticks += 1
else:
GameState.stationary_ticks = 0
_prev_player_position = GameState.player_position
# Tiles for rendering: test mode sends "tiles", live server sends "visible_tiles"
if snapshot.has("tiles"):
GameState.visible_tiles = snapshot.tiles
elif (
snapshot.has("visible_tiles")
and snapshot.visible_tiles is Array
and snapshot.visible_tiles.size() > 0
):
var has_type := false
if snapshot.visible_tiles.size() > 0 and snapshot.visible_tiles[0] is Dictionary:
has_type = snapshot.visible_tiles[0].has("type")
if has_type:
GameState.visible_tiles = snapshot.visible_tiles
if snapshot.has("visible_positions"):
GameState.visible_positions.clear()
for pos in snapshot.visible_positions:
GameState.visible_positions[Vector2i(pos.x, pos.y)] = true
# v2: game_time (D-031)
if snapshot.has("game_time") and snapshot.game_time is Dictionary:
GameState.game_time = snapshot.game_time
# v2: player_facing (D-015)
if snapshot.has("player_facing") and snapshot.player_facing is String:
GameState.player_facing = snapshot.player_facing
# v4: nearby_interactions (#404/#405)
if snapshot.has("nearby_interactions") and snapshot.nearby_interactions is Array:
GameState.nearby_interactions = snapshot.nearby_interactions
else:
GameState.nearby_interactions = []
# v5: current_monologue (#414)
if snapshot.has("current_monologue") and snapshot.current_monologue is Dictionary:
GameState.current_monologue = snapshot.current_monologue
else:
GameState.current_monologue = null
# #122: lattice_profile
if snapshot.has("lattice_profile") and snapshot.lattice_profile is String:
GameState.lattice_profile = snapshot.lattice_profile
# v6: player_stance (#449, D-053)
if snapshot.has("player_stance") and snapshot.player_stance is String:
GameState.player_stance = snapshot.player_stance
# v6: player_inventory (#449, D-065)
if snapshot.has("player_inventory") and snapshot.player_inventory is Array:
GameState.player_inventory = snapshot.player_inventory
else:
GameState.player_inventory = []
# v7: current_dialogue (#434, D-061)
if snapshot.has("current_dialogue") and snapshot.current_dialogue is Dictionary:
GameState.current_dialogue = snapshot.current_dialogue
else:
GameState.current_dialogue = null
# v7: pending_recognitions (#431, D-059/D-060)
if snapshot.has("pending_recognitions") and snapshot.pending_recognitions is Array:
GameState.pending_recognitions = snapshot.pending_recognitions
else:
GameState.pending_recognitions = []
# v9: conversation_events (#535, D-078)
if snapshot.has("conversation_events") and snapshot.conversation_events is Array:
GameState.conversation_events = snapshot.conversation_events
else:
GameState.conversation_events = []
# v9: conversation_ended (#535, D-078)
if snapshot.has("conversation_ended") and snapshot.conversation_ended is Array:
GameState.conversation_ended = snapshot.conversation_ended
else:
GameState.conversation_ended = []
# v8: dialogue_response (#305, D-028)
if snapshot.has("dialogue_response") and snapshot.dialogue_response is Dictionary:
GameState.dialogue_response = snapshot.dialogue_response
else:
GameState.dialogue_response = null
# v8: gauntlet mode (#496)
if snapshot.has("gauntlet_mode") and snapshot.gauntlet_mode == true:
GameState.gauntlet_mode = true
else:
GameState.gauntlet_mode = false
if snapshot.has("room_id") and snapshot.room_id is String:
GameState.room_id = snapshot.room_id
else:
GameState.room_id = null
# OQ-07 (#522): insert_active
if snapshot.has("insert_active") and snapshot.insert_active is bool:
GameState.insert_active = snapshot.insert_active
else:
GameState.insert_active = true
# #507: rng_seed
if snapshot.has("rng_seed"):
GameState.rng_seed = snapshot.rng_seed
else:
GameState.rng_seed = null
# D-018: Sound events — partition by range_category.
if snapshot.has("sound_events") and snapshot.sound_events is Array:
GameState.medium_sound_events = []
GameState.close_sound_events = []
for se in snapshot.sound_events:
if not se is Dictionary:
continue
var rc: String = se.get("range_category", "")
if rc == "Medium":
GameState.medium_sound_events.append(se)
elif rc == "Close":
GameState.close_sound_events.append(se)
else:
GameState.medium_sound_events = []
GameState.close_sound_events = []
# v10: discovered_pois (#151, D-013)
if snapshot.has("discovered_pois") and snapshot.discovered_pois is Array:
GameState.discovered_pois = snapshot.discovered_pois
elif snapshot.has("poi_list") and snapshot.poi_list is Array:
GameState.discovered_pois = snapshot.poi_list
# v14: examine_result (#174, #242)
if snapshot.has("examine_result") and snapshot.examine_result is Dictionary:
GameState.current_examine_result = snapshot.examine_result
else:
GameState.current_examine_result = null
# v15: save_result (#554, D-085)
if snapshot.has("save_result") and snapshot.save_result is Dictionary:
GameState.save_result = snapshot.save_result
else:
GameState.save_result = null
# v18: debug_response (#580)
if snapshot.has("debug_response") and snapshot.debug_response is Dictionary:
GameState.debug_response = snapshot.debug_response
else:
GameState.debug_response = null
# v20: settings_response (#627, D-138)
if snapshot.has("settings_response") and snapshot.settings_response is Dictionary:
GameState.settings_response = snapshot.settings_response
var sr: Dictionary = snapshot.settings_response
if sr.get("kind") == "full":
var sr_settings: Variant = sr.get("settings")
if sr_settings is Array:
for entry in sr_settings:
if not entry is Dictionary:
continue
if entry.get("key") == "ai_dialogue.enabled":
var val: Variant = entry.get("value")
if val != null:
GameState.ai_enhanced_dialogue_enabled = _extract_bool_setting(
"ai_dialogue.enabled", val
)
else:
GameState.settings_response = null
# #718: character_visual_descriptor — restored from server snapshot on save/load.
if (
snapshot.has("character_visual_descriptor")
and snapshot.character_visual_descriptor is Dictionary
):
var CVD := load("res://scripts/rendering/character_visual_descriptor.gd")
if CVD != null:
var restored = CVD.from_dict(snapshot.character_visual_descriptor)
if restored != null:
GameState.character_visual_descriptor = restored
# v14: player_knowledge (#264, D-041)
if snapshot.has("player_knowledge") and snapshot.player_knowledge is Dictionary:
GameState.player_knowledge = snapshot.player_knowledge
# D-020/D-073 (#529): Server-authoritative zone_id for zone ambient crossfade.
if snapshot.has("zone_id") and snapshot.zone_id is String:
GameState.current_zone_id = snapshot.zone_id
else:
# DEPRECATED fallback — client-side tile lookup. Remove when server sends top-level "zone_id".
var tile_by_coord: Dictionary = {}
for vtile in GameState.visible_tiles:
if vtile is Dictionary and vtile.has("x") and vtile.has("y"):
tile_by_coord[Vector2i(vtile.x, vtile.y)] = vtile
var player_pos_key := Vector2i(
int(GameState.player_position.x), int(GameState.player_position.y)
)
var player_tile = tile_by_coord.get(player_pos_key, null)
GameState.current_zone_id = player_tile.get("zone_id", "") if player_tile else ""
# v2: visible_tiles with visibility sectors
if (
snapshot.has("visible_tiles")
and snapshot.visible_tiles is Array
and snapshot.visible_tiles.size() > 0
):
GameState.visibility_sectors.clear()
var has_explicit_positions := snapshot.has("visible_positions")
if not has_explicit_positions:
GameState.visible_positions.clear()
GameState.boundary_positions.clear()
for vtile in snapshot.visible_tiles:
if not vtile is Dictionary or not vtile.has("x") or not vtile.has("y"):
continue
var pos := Vector2i(vtile.x, vtile.y)
var vis_sector: String = vtile.get("visibility", "")
if vtile.has("visibility"):
GameState.visibility_sectors[pos] = vis_sector
if vis_sector == "BoundaryWall":
GameState.boundary_positions[pos] = true
elif not has_explicit_positions:
GameState.visible_positions[pos] = true
## Extract a bool from a tagged-union {"Bool": true} or plain bool value.
static func _extract_bool_setting(key: String, val: Variant) -> bool:
if val is bool:
return val
if val is Dictionary and val.has("Bool"):
return bool(val["Bool"])
push_warning("GameState: unexpected type for setting '%s': %s" % [key, str(val)])
return false
+10 -8
View File
@@ -19,9 +19,9 @@ static func parse(text: String) -> Dictionary:
# Stack: [{indent: int, key: String}] — path of open section headers
var stack: Array = []
# Array state
var current_array: Variant = null # Array being built, or null
var current_item: Variant = null # Dict being built for current array item, or null
var array_parent_indent: int = -1 # indent of the "key:" line that owns the array
var current_array: Variant = null # Array being built, or null
var current_item: Variant = null # Dict being built for current array item, or null
var array_parent_indent: int = -1 # indent of the "key:" line that owns the array
for raw_line in text.split("\n"):
var stripped := raw_line.strip_edges(false, true)
@@ -126,19 +126,21 @@ static func _parse_value(val: String) -> Variant:
if val.is_empty():
return ""
# Strip inline comment outside quotes
if not val.begins_with("\""):
if not val.begins_with('"'):
var comment_pos: int = val.find(" #")
if comment_pos >= 0:
val = val.substr(0, comment_pos).strip_edges()
# Quoted string — extract content between quotes
if val.begins_with("\""):
var end_quote: int = val.find("\"", 1)
if val.begins_with('"'):
var end_quote: int = val.find('"', 1)
if end_quote > 0:
return val.substr(1, end_quote - 1)
return val.substr(1)
# Boolean
if val == "true": return true
if val == "false": return false
if val == "true":
return true
if val == "false":
return false
# Float (must have decimal point)
if val.contains(".") and val.is_valid_float():
return val.to_float()
+10
View File
@@ -0,0 +1,10 @@
shader_type canvas_item;
// D-086: Runtime icon tint — replaces color channel with tint_color, preserves alpha mask.
// Applied to SVG-sourced TextureRect nodes so stance/status icons can be color-coded at runtime.
// Default: #c8d0e0 (insert chrome) — identical to the SVG's authored stroke color.
uniform vec4 tint_color : source_color = vec4(0.784, 0.816, 0.878, 1.0);
void fragment() {
float a = texture(TEXTURE, UV).a;
COLOR = vec4(tint_color.rgb, a * tint_color.a);
}
+4 -4
View File
@@ -10,7 +10,7 @@
## run before the project's class_name registry is fully populated.
extends SceneTree
var _Msgpack: GDScript
var _msgpack: GDScript
var _count := 0
var _errors := 0
var _output_dir: String
@@ -21,7 +21,7 @@ func _init():
func _run():
_Msgpack = load("res://addons/messagepack/messagepack.gd")
_msgpack = load("res://addons/messagepack/messagepack.gd")
# Resolve repo root from Godot project root (client/).
# Assumes client/ is one level below repo root — validated below.
@@ -81,7 +81,7 @@ func _encode_input(tick: int, action_name: String, action_data: Variant = null)
else:
action = action_name
var result = _Msgpack.encode({"tick": tick, "action": action})
var result = _msgpack.encode({"tick": tick, "action": action})
if result.status != null:
push_error("Encode failed: %s" % result.status)
return PackedByteArray()
@@ -104,7 +104,7 @@ func _encode_inputs(inputs: Array) -> PackedByteArray:
action = action_name
wire_inputs.append({"tick": input["tick"], "action": action})
var result = _Msgpack.encode(wire_inputs)
var result = _msgpack.encode(wire_inputs)
if result.status != null:
push_error("Batch encode failed: %s" % result.status)
return PackedByteArray()
+16 -15
View File
@@ -10,6 +10,7 @@
class_name TestAiDialogueSprint26
extends GdUnitTestSuite
const SETTINGS_DIALOG_SCENE = preload("res://ui/settings_dialog.tscn")
var _original_ai_enabled: bool = true
@@ -345,7 +346,7 @@ func test_hardware_classify_degradation_ok_at_exact_40_percent() -> void:
func test_settings_dialog_exposes_ai_dialogue_label_text_method() -> void:
# settings_dialog needs a testable API — hardcoded UI strings are easy to drift.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -359,7 +360,7 @@ func test_settings_dialog_exposes_ai_dialogue_label_text_method() -> void:
func test_settings_dialog_ai_dialogue_label_is_correct() -> void:
# D-138: label must be exactly "AI-Enhanced Dialogue" (Jeroen's wording).
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -377,7 +378,7 @@ func test_settings_dialog_ai_dialogue_label_is_correct() -> void:
func test_settings_dialog_toggle_disabled_when_hardware_fails() -> void:
# D-138 §8: RAM < 1.6 GB → feature disabled, toggle greyed out.
# Player receives message but cannot enable the feature.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -396,7 +397,7 @@ func test_settings_dialog_toggle_disabled_when_hardware_fails() -> void:
func test_settings_dialog_toggle_enabled_when_hardware_passes() -> void:
# "pass" → toggle available to interact with.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -415,7 +416,7 @@ func test_settings_dialog_toggle_enabled_when_hardware_passes() -> void:
func test_settings_dialog_toggle_enabled_when_hardware_marginal() -> void:
# D-138 §8: "marginal" → warn but let player proceed. Never force-disable.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -439,8 +440,8 @@ func test_hardware_detector_benchmark_cache_path_is_correct() -> void:
var det := _get_detector()
if det == null:
return
assert_str(det.BENCHMARK_CACHE_PATH).override_failure_message(
"BENCHMARK_CACHE_PATH must be 'user://ai-dialogue-config.json' (D-138 §8)"
assert_str(det.benchmark_cache_path).override_failure_message(
"benchmark_cache_path must be 'user://ai-dialogue-config.json' (D-138 §8)"
).is_equal("user://ai-dialogue-config.json")
@@ -766,7 +767,7 @@ func test_hardware_detector_battery_suspend_preserves_player_pref_false() -> voi
func test_settings_dialog_inference_suspended_state_defaults_false() -> void:
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -779,7 +780,7 @@ func test_settings_dialog_inference_suspended_state_defaults_false() -> void:
func test_settings_dialog_set_inference_suspended_true() -> void:
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -794,7 +795,7 @@ func test_settings_dialog_set_inference_suspended_true() -> void:
func test_settings_dialog_resume_clears_suspended_state() -> void:
# D-138 §8: resume when plugged in — suspended state clears.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -813,7 +814,7 @@ func test_settings_dialog_toggle_remains_enabled_when_battery_suspended() -> voi
# Battery suspend auto-pauses inference but must NOT grey the toggle —
# the player can click it to override the suspension.
# Only hardware "fail" (RAM < 1.6 GB) may disable the toggle.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -829,7 +830,7 @@ func test_settings_dialog_toggle_remains_enabled_when_battery_suspended() -> voi
func test_settings_dialog_toggle_enabled_after_resume() -> void:
# After resume (plug-in), toggle must be enabled again.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -847,7 +848,7 @@ func test_settings_dialog_toggle_enabled_after_resume() -> void:
func test_settings_dialog_toggle_disabled_by_hardware_fail_even_when_suspended() -> void:
# Hardware "fail" disables the toggle regardless of battery state.
# RAM < 1.6 GB is the only hard disable — battery suspend is not.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -864,7 +865,7 @@ func test_settings_dialog_toggle_disabled_by_hardware_fail_even_when_suspended()
func test_settings_dialog_warning_label_shown_when_battery_suspended() -> void:
# When inference is battery-suspended, a warning label must be visible
# so the player knows why inference isn't running (even though toggle is enabled).
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
@@ -882,7 +883,7 @@ func test_settings_dialog_warning_label_shown_when_battery_suspended() -> void:
func test_settings_dialog_warning_label_hidden_when_not_suspended() -> void:
# Warning label must not show when plugged in — no battery message needed.
var scene := load("res://ui/settings_dialog.tscn") as PackedScene
var scene := SETTINGS_DIALOG_SCENE
if scene == null:
push_warning("TestAiDialogueSprint26: settings_dialog.tscn not found — skipped")
return
+6 -5
View File
@@ -12,10 +12,11 @@
class_name TestAntiTedium
extends GdUnitTestSuite
const MAIN_SCENE = preload("res://scenes/main.tscn")
var _instance: Node = null
var GauntletHUDScript = load("res://ui/gauntlet_hud.gd")
var BugReportDialogScript = load("res://ui/bug_report_dialog.gd")
var _instance: Node = null
func before_test() -> void:
@@ -106,7 +107,7 @@ func _make_bug_report_dialog() -> Control:
func test_bug_report_dialog_exists_in_scene() -> void:
# Verify the BugReportDialog node is present and hidden by default.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -125,7 +126,7 @@ func test_bug_report_dialog_exists_in_scene() -> void:
func test_bug_report_activates_on_action() -> void:
# Inject BUG_REPORT action directly into the queue and verify main.gd
# triggers the dialog. This tests the full main._process() handling path.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -170,7 +171,7 @@ func test_bug_report_activates_on_action() -> void:
func test_no_gauntlet_ui_visible_in_default_mode() -> void:
# Load main scene — represents non-Gauntlet (default) play mode
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -224,7 +225,7 @@ func test_snapshot_without_room_id_shows_no_gauntlet_ui() -> void:
func test_gauntlet_ui_stays_hidden_after_multiple_snapshots() -> void:
# Simulate several ticks of normal play — gauntlet UI must never appear.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
+2 -2
View File
@@ -18,13 +18,13 @@ func before_test() -> void:
for bus in AudioManager.BUSES:
AudioManager.set_volume(bus, 0.0)
GameState.stationary_ticks = 0
GameState._prev_player_position = Vector2(-1e9, -1e9)
SnapshotHandler._prev_player_position = Vector2(-1e9, -1e9)
func after_test() -> void:
AudioManager.clear_dip()
GameState.stationary_ticks = 0
GameState._prev_player_position = Vector2(-1e9, -1e9)
SnapshotHandler._prev_player_position = Vector2(-1e9, -1e9)
# ==============================================================================
+2 -2
View File
@@ -480,7 +480,7 @@ func test_d067_onset_is_when_remaining_equals_total_delay_ticks() -> void:
"tick": 1,
"pending_recognitions": [
{"entity_id": 99, "x": 10.0, "y": 10.0, "z": 0,
"remaining_ticks": 6, "total_delay_ticks": 6},
"remaining_ticks": 6, "total_delay_ticks": 6},
],
})
assert_that(GameState.pending_recognitions.size()).is_equal(1)
@@ -497,7 +497,7 @@ func test_d067_completion_is_when_entity_absent_from_pending() -> void:
"tick": 1,
"pending_recognitions": [
{"entity_id": 99, "x": 10.0, "y": 10.0, "z": 0,
"remaining_ticks": 1, "total_delay_ticks": 6},
"remaining_ticks": 1, "total_delay_ticks": 6},
],
})
assert_that(GameState.pending_recognitions.size()).is_equal(1)
+2 -3
View File
@@ -11,12 +11,11 @@
class_name TestBugReportRingBuffer
extends GdUnitTestSuite
var BugReportDialogScript = load("res://ui/bug_report_dialog.gd")
# Expected ring buffer capacity per spec.
const EXPECTED_CAPACITY := 60
var BugReportDialogScript = load("res://ui/bug_report_dialog.gd")
func after_each() -> void:
# Reset GameState fields mutated by tests to prevent cross-test leakage.
+7 -6
View File
@@ -9,6 +9,7 @@ extends GdUnitTestSuite
const EXPECTED_PLAYER_POS := Vector2(10, 10)
const EXPECTED_CAMERA_POS := Vector2(320, 320) # 10 * 32, 10 * 32
const MAIN_SCENE = preload("res://scenes/main.tscn")
var _instance: Node = null
@@ -67,7 +68,7 @@ func test_apply_snapshot_sets_player_position() -> void:
# --- Camera anchor after _ready() ---
func test_camera_position_after_ready() -> void:
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -77,7 +78,7 @@ func test_camera_position_after_ready() -> void:
func test_camera_anchored_flag_after_ready() -> void:
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -88,7 +89,7 @@ func test_camera_anchored_flag_after_ready() -> void:
func test_camera_smoothing_off_after_ready() -> void:
# Camera smoothing must be disabled during init to prevent lerp from (0,0).
# If this test fails, the camera will visibly drift from origin to player.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -100,7 +101,7 @@ func test_camera_smoothing_off_after_ready() -> void:
func test_camera_smoothing_stays_off_with_manual_lerp() -> void:
# #117: Manual lerp approach — Godot's built-in smoothing must stay OFF always.
# CAMERA_SMOOTHING_SPEED is used as the lerp weight, not Godot's position_smoothing_speed.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -114,7 +115,7 @@ func test_camera_smoothing_stays_off_with_manual_lerp() -> void:
# --- Camera behavior across frames ---
func test_camera_tracks_player_after_process() -> void:
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -130,7 +131,7 @@ func test_camera_tracks_player_after_process() -> void:
func test_camera_lerps_toward_player_movement() -> void:
# #117: With manual lerp, camera moves TOWARD player position (not snapping).
# After one 16ms frame the camera should be partway between old and new position.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -161,7 +161,8 @@ func test_reload_descriptor_clears_previous_nodes() -> void:
# Second load must produce exactly the same child count — no more, no less.
# _clear() frees and rebuilds; any deviation indicates stale nodes accumulating.
assert_int(count_after_second).override_failure_message(
"load_descriptor must produce identical child count on reload — stale nodes detected if higher, missing cleanup if lower"
"load_descriptor must produce identical child count on reload" +
" — stale nodes detected if higher, missing cleanup if lower"
).is_equal(count_after_first)
@@ -305,7 +306,8 @@ func test_torso_hidden_when_full_coverage_clothing_worn() -> void:
desc.clothing_slots = {"torso": "coveralls_basic"}
node.load_descriptor(desc)
var coverage: Dictionary = node.get_active_coverage("coveralls_basic") if node.has_method("get_active_coverage") else {}
var coverage: Dictionary = node.get_active_coverage("coveralls_basic") \
if node.has_method("get_active_coverage") else {}
if coverage.is_empty():
push_warning("TestCharacterVisualSprint28: coveralls_basic/coverage.json not found — stub")
return
+7 -3
View File
@@ -57,7 +57,8 @@ func test_parse_top_level_quoted_string() -> void:
func test_parse_single_condition() -> void:
var yaml := "conditions:\n - id: test-1\n description: \"Test condition\"\n condition_type: player_near\n x: 10\n y: 20\n radius: 3.0"
var yaml := ("conditions:\n - id: test-1\n description: \"Test condition\"\n" +
" condition_type: player_near\n x: 10\n y: 20\n radius: 3.0")
var result: Dictionary = ChecklistEvaluatorScript.parse_checklist_yaml(yaml)
assert_that(result.has("conditions")).is_true()
var conditions: Array = result["conditions"]
@@ -70,7 +71,9 @@ func test_parse_single_condition() -> void:
func test_parse_multiple_conditions() -> void:
var yaml := "conditions:\n - id: cond-a\n condition_type: player_near\n x: 1\n y: 2\n radius: 1.0\n\n - id: cond-b\n condition_type: player_facing\n direction: East"
var yaml := ("conditions:\n - id: cond-a\n condition_type: player_near\n" +
" x: 1\n y: 2\n radius: 1.0\n\n" +
" - id: cond-b\n condition_type: player_facing\n direction: East")
var result: Dictionary = ChecklistEvaluatorScript.parse_checklist_yaml(yaml)
var conditions: Array = result["conditions"]
assert_that(conditions.size()).is_equal(2)
@@ -80,7 +83,8 @@ func test_parse_multiple_conditions() -> void:
func test_parse_comments_ignored() -> void:
var yaml := "# This is a comment\nroom_id: test\n# Another comment\nconditions:\n - id: c1\n condition_type: entity_present\n entity_id: 5"
var yaml := ("# This is a comment\nroom_id: test\n# Another comment\n" +
"conditions:\n - id: c1\n condition_type: entity_present\n entity_id: 5")
var result: Dictionary = ChecklistEvaluatorScript.parse_checklist_yaml(yaml)
assert_that(result.get("room_id")).is_equal("test")
var conditions: Array = result["conditions"]
-1
View File
@@ -352,7 +352,6 @@ func test_fog_overlay_z_layer() -> void:
return
# This test needs the scene tree to be set up
# Verify via scene file inspection rather than runtime
pass
# -- Noise animation cycles (D-059) -------------------------------------------
+7 -3
View File
@@ -19,7 +19,7 @@ func before_each() -> void:
GameState.player_stance = "Walk"
GameState.player_inventory = []
GameState.stationary_ticks = 0
GameState._prev_player_position = Vector2(-1e9, -1e9)
SnapshotHandler._prev_player_position = Vector2(-1e9, -1e9)
GameState.current_zone_id = ""
GameState.insert_active = true
@@ -67,7 +67,8 @@ func test_apply_snapshot_player_facing_missing_keeps_default() -> void:
func test_apply_snapshot_sets_nearby_interactions() -> void:
var interactions := [
{"entity_id": 5, "entity_type": "Npc", "distance": 1.2, "verbs": [{"kind": "Talk", "label": "Talk", "priority": 1, "available": true}]},
{"entity_id": 5, "entity_type": "Npc", "distance": 1.2,
"verbs": [{"kind": "Talk", "label": "Talk", "priority": 1, "available": true}]},
]
GameState.apply_snapshot({"tick": 1, "entities": [], "nearby_interactions": interactions})
assert_that(GameState.nearby_interactions.size()).is_equal(1)
@@ -83,7 +84,10 @@ func test_apply_snapshot_nearby_interactions_absent_clears_list() -> void:
# -- v5: current_monologue (#414) -----------------------------------------
func test_apply_snapshot_sets_monologue() -> void:
var monologue := {"id": "m1", "text": "Something is off here.", "duration_seconds": 4.0, "priority": 1, "is_urgent": false}
var monologue := {
"id": "m1", "text": "Something is off here.",
"duration_seconds": 4.0, "priority": 1, "is_urgent": false,
}
GameState.apply_snapshot({"tick": 1, "entities": [], "current_monologue": monologue})
assert_that(GameState.current_monologue).is_not_null()
assert_that(GameState.current_monologue.get("text")).is_equal("Something is off here.")
+1 -1
View File
@@ -14,7 +14,7 @@ extends GdUnitTestSuite
func before_each() -> void:
GameState.stationary_ticks = 0
GameState._prev_player_position = Vector2(-1e9, -1e9)
SnapshotHandler._prev_player_position = Vector2(-1e9, -1e9)
GameState.current_zone_id = ""
GameState.player_position = Vector2.ZERO
GameState.visible_tiles = []
+2 -2
View File
@@ -8,6 +8,8 @@
class_name TestHubTeleport
extends GdUnitTestSuite
const _THRESHOLD: float = 5.0 # Mirror of main.gd TELEPORT_DISTANCE_THRESHOLD
# -- Fixtures ------------------------------------------------------------------
@@ -178,8 +180,6 @@ func test_test_mode_teleport_clears_dialogue() -> void:
# Threshold constant lives on the main scene node (TELEPORT_DISTANCE_THRESHOLD = 5.0).
# These tests verify the distance math against that threshold.
const _THRESHOLD: float = 5.0 # Mirror of main.gd TELEPORT_DISTANCE_THRESHOLD
func test_detect_teleport_large_jump() -> void:
# Position jump > threshold should be detected as teleport
var old_pos := Vector2(10.0, 10.0)
+1 -1
View File
@@ -44,7 +44,7 @@ func _make_cursor_or_skip() -> Node:
func _make_interaction_list() -> Node:
for path in ["res://ui/interaction_list.tscn", "res://ui/entity_interaction_list.tscn",
"res://scenes/interaction_list.tscn"]:
"res://scenes/interaction_list.tscn"]:
if ResourceLoader.exists(path):
var scene = load(path)
var node = scene.instantiate()
+2 -2
View File
@@ -12,7 +12,7 @@ extends GdUnitTestSuite
func _interaction_list_exists() -> bool:
for path in ["res://ui/interaction_list.tscn", "res://ui/entity_interaction_list.tscn",
"res://scenes/interaction_list.tscn"]:
"res://scenes/interaction_list.tscn"]:
if ResourceLoader.exists(path):
return true
return false
@@ -20,7 +20,7 @@ func _interaction_list_exists() -> bool:
func _make_interaction_list() -> Node:
for path in ["res://ui/interaction_list.tscn", "res://ui/entity_interaction_list.tscn",
"res://scenes/interaction_list.tscn"]:
"res://scenes/interaction_list.tscn"]:
if ResourceLoader.exists(path):
var scene = load(path)
var node = scene.instantiate()
+7 -13
View File
@@ -14,7 +14,7 @@ func test_protocol_decode_v4_with_nearby_interactions() -> void:
"version": Protocol.PROTOCOL_VERSION,
"entities": [
{"entity_id": 1, "x": 5.0, "y": 5.0, "z": 0, "kind": "Player",
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
],
"nearby_interactions": [{
"entity_id": 2,
@@ -93,7 +93,7 @@ func test_protocol_decode_v4_entity_relationship() -> void:
"version": Protocol.PROTOCOL_VERSION,
"entities": [
{"entity_id": 1, "x": 5.0, "y": 5.0, "z": 0, "kind": "Npc",
"visibility": "Forward", "relationship": "Friendly", "observation": "Visible"},
"visibility": "Forward", "relationship": "Friendly", "observation": "Visible"},
],
}
var encoded = Messagepack.encode(raw)
@@ -222,15 +222,9 @@ func test_interact_with_data_encodes_as_data_variant() -> void:
# -- Helpers --
func _make_prompt() -> PanelContainer:
func _make_prompt() -> Control:
var PromptScript = load("res://ui/interaction_prompt.gd")
var panel = PanelContainer.new()
panel.set_script(PromptScript)
var margin = MarginContainer.new()
margin.name = "MarginContainer"
panel.add_child(margin)
var label = Label.new()
label.name = "PromptLabel"
margin.add_child(label)
add_child(panel)
return panel
var ctrl = Control.new()
ctrl.set_script(PromptScript)
add_child(ctrl) # triggers _ready() which creates ImplantPanel + ImplantDataRow
return ctrl
+2 -1
View File
@@ -1,5 +1,6 @@
## Smoke tests for main scene initialization
## Run with: godot4 --headless --path . -s res://addons/gdUnit4/bin/GdUnitCmdTool.gd --ignoreHeadlessMode -a res://tests/
## Run with: godot4 --headless --path . -s res://addons/gdUnit4/bin/GdUnitCmdTool.gd
## --ignoreHeadlessMode -a res://tests/
class_name TestMainScene
extends GdUnitTestSuite
+3 -2
View File
@@ -16,6 +16,7 @@ extends GdUnitTestSuite
# ---------------------------------------------------------------------------
const MINIMAP_SCENE_PATH: String = "res://ui/minimap.tscn"
const MAIN_SCENE = preload("res://scenes/main.tscn")
func _make_minimap() -> Control:
if not ResourceLoader.exists(MINIMAP_SCENE_PATH):
@@ -199,7 +200,7 @@ func test_minimap_in_main_scene_on_insert_overlay() -> void:
if not ResourceLoader.exists("res://scenes/main.tscn"):
push_warning("TestMinimapSprint18: main.tscn not found — scene tree test skipped")
return
var scene: Node = load("res://scenes/main.tscn").instantiate()
var scene: Node = MAIN_SCENE.instantiate()
auto_free(scene)
add_child(scene)
@@ -226,7 +227,7 @@ func test_insert_overlay_is_canvas_layer_10() -> void:
if not ResourceLoader.exists("res://scenes/main.tscn"):
push_warning("TestMinimapSprint18: main.tscn not found — canvas layer test skipped")
return
var scene: Node = load("res://scenes/main.tscn").instantiate()
var scene: Node = MAIN_SCENE.instantiate()
auto_free(scene)
add_child(scene)
+4 -2
View File
@@ -11,6 +11,8 @@ class_name TestP0Regressions
extends GdUnitTestSuite
const MAIN_SCENE = preload("res://scenes/main.tscn")
var _instance: Node = null
@@ -174,7 +176,7 @@ func test_monologue_carry_forward_preserves_newest() -> void:
func test_camera_static_during_pause() -> void:
# 1. Instantiate main scene — camera anchors at test mode player position
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -204,7 +206,7 @@ func test_camera_static_during_pause() -> void:
func test_camera_anchored_after_pause_unpause() -> void:
# Verify camera stays properly anchored through a pause → unpause cycle.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
+1 -1
View File
@@ -346,7 +346,7 @@ func test_full_v6_snapshot_decode() -> void:
],
"entities": [
{"entity_id": 1, "x": 10.0, "y": 10.0, "z": 0, "kind": "Player",
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
],
"visible_tiles": [
{"x": 10, "y": 10, "z": 0, "visibility": "Forward", "tile_kind": "Floor"},
+1 -1
View File
@@ -339,7 +339,7 @@ func test_full_v7_snapshot_decode() -> void:
"player_inventory": [{"item_id": 100, "name": "Access Token", "slot": 0}],
"entities": [
{"entity_id": 1, "x": 10.0, "y": 10.0, "z": 0, "kind": "Player",
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
],
"visible_tiles": [],
"nearby_interactions": [],
+2 -1
View File
@@ -281,7 +281,8 @@ func test_entity_renderer_npc_uses_unknown_teal() -> void:
func test_entity_renderer_object_uses_grey() -> void:
var renderer := _make_entity_renderer()
var obj := [{"entity_id": 3, "x": 1.0, "y": 1.0, "z": 0, "kind": {"variant": "Object", "data": null}, "visibility": "Forward"}]
var obj := [{"entity_id": 3, "x": 1.0, "y": 1.0, "z": 0,
"kind": {"variant": "Object", "data": null}, "visibility": "Forward"}]
renderer.update_entities(obj)
var node = renderer.entity_nodes[3] as Sprite2D
assert_that(node.self_modulate).is_equal(Constants.ENTITY_COLOR_OBJECT)
@@ -4,6 +4,8 @@
class_name TestSessionManagerSprint19
extends GdUnitTestSuite
const MAIN_MENU_SCENE = preload("res://scenes/main_menu.tscn")
# Game IDs created during the current test — deleted in after_test().
var _created_ids: Array = []
@@ -166,7 +168,7 @@ func test_main_menu_instantiates_without_crash() -> void:
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
push_warning("TestSessionManagerSprint19: main_menu.tscn not found — skip")
return
var scene: Node = load("res://scenes/main_menu.tscn").instantiate()
var scene: Node = MAIN_MENU_SCENE.instantiate()
auto_free(scene)
add_child(scene)
assert_that(scene).is_not_null()
@@ -175,7 +177,7 @@ func test_main_menu_instantiates_without_crash() -> void:
func test_main_menu_has_new_game_button() -> void:
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
return
var scene: Node = load("res://scenes/main_menu.tscn").instantiate()
var scene: Node = MAIN_MENU_SCENE.instantiate()
auto_free(scene)
add_child(scene)
var btn := scene.get_node_or_null("VBox/NewGameBtn")
@@ -187,7 +189,7 @@ func test_main_menu_has_new_game_button() -> void:
func test_main_menu_has_continue_button() -> void:
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
return
var scene: Node = load("res://scenes/main_menu.tscn").instantiate()
var scene: Node = MAIN_MENU_SCENE.instantiate()
auto_free(scene)
add_child(scene)
var btn := scene.get_node_or_null("VBox/ContinueBtn")
+5 -3
View File
@@ -10,6 +10,8 @@
class_name TestSignalSprint24
extends GdUnitTestSuite
const NEWS_TICKER_SCENE = preload("res://ui/news_ticker.tscn")
# -- #588: Character archetype field ------------------------------------------
@@ -204,7 +206,7 @@ func test_protocol_decode_current_ticker_null_when_absent() -> void:
func test_news_ticker_hidden_when_snapshot_has_no_ticker() -> void:
# update_from_state() must hide ticker when current_ticker is null.
var ticker_scene := load("res://ui/news_ticker.tscn") as PackedScene
var ticker_scene := NEWS_TICKER_SCENE
assert_that(ticker_scene).is_not_null()
var ticker := ticker_scene.instantiate()
auto_free(ticker)
@@ -224,7 +226,7 @@ func test_news_ticker_hidden_when_snapshot_has_no_ticker() -> void:
func test_news_ticker_visible_when_snapshot_has_ticker() -> void:
# update_from_state() must show ticker when current_ticker has text.
var ticker_scene := load("res://ui/news_ticker.tscn") as PackedScene
var ticker_scene := NEWS_TICKER_SCENE
assert_that(ticker_scene).is_not_null()
var ticker := ticker_scene.instantiate()
auto_free(ticker)
@@ -244,7 +246,7 @@ func test_news_ticker_visible_when_snapshot_has_ticker() -> void:
func test_news_ticker_hides_when_ticker_becomes_null() -> void:
# Ticker shown then hidden: update_from_state() with null current_ticker hides it.
var ticker_scene := load("res://ui/news_ticker.tscn") as PackedScene
var ticker_scene := NEWS_TICKER_SCENE
assert_that(ticker_scene).is_not_null()
var ticker := ticker_scene.instantiate()
auto_free(ticker)
+11 -9
View File
@@ -4,6 +4,8 @@
class_name TestSmoothCameraSprint15
extends GdUnitTestSuite
const MAIN_SCENE = preload("res://scenes/main.tscn")
var _instance: Node = null
@@ -42,7 +44,7 @@ func test_camera_smoothing_speed_constant_reasonable() -> void:
func test_godot_smoothing_disabled_at_ready() -> void:
# #117: Godot's built-in Camera2D smoothing must be OFF (manual lerp replaces it).
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -53,7 +55,7 @@ func test_godot_smoothing_disabled_at_ready() -> void:
func test_godot_smoothing_stays_off_after_frames() -> void:
# #117: Smoothing must NOT be re-enabled at any point — manual lerp only.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -70,7 +72,7 @@ func test_godot_smoothing_stays_off_after_frames() -> void:
func test_camera_lerps_not_snaps_on_player_move() -> void:
# #117: When player moves, camera should lerp (not snap) to new position.
# After 1 frame at ~60fps, camera should be partway there — not at target.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -90,7 +92,7 @@ func test_camera_lerps_not_snaps_on_player_move() -> void:
func test_camera_converges_to_player_over_multiple_frames() -> void:
# #117: After enough frames the camera should be within 1px of target.
# At LERP_SPEED=8: ~95% convergence in 0.25s, >99% in 0.5s.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -111,7 +113,7 @@ func test_camera_converges_to_player_over_multiple_frames() -> void:
func test_camera_stationary_player_no_drift() -> void:
# #117: When player is stationary, camera should not drift (lerp to same point).
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -133,7 +135,7 @@ func test_camera_stationary_player_no_drift() -> void:
func test_teleport_snaps_camera_immediately() -> void:
# #117: _teleport_in_progress causes camera to snap (not lerp) in the same frame.
# Manually displace camera, set the flag, call _process — camera should snap to target.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -155,7 +157,7 @@ func test_teleport_snaps_camera_immediately() -> void:
func test_teleport_flag_cleared_after_snap() -> void:
# #117: _teleport_in_progress must be false after the snap frame.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -170,7 +172,7 @@ func test_teleport_flag_cleared_after_snap() -> void:
func test_camera_resumes_lerp_after_teleport() -> void:
# #117: Frame after teleport snap must resume lerp (not continue snapping).
# After teleport flag clears, any position delta produces lerp movement.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)
@@ -200,7 +202,7 @@ func test_camera_resumes_lerp_after_teleport() -> void:
func test_camera_no_rotation() -> void:
# D-015: Camera must be fixed-north in v0.1 — no rotation regardless of facing.
var scene := load("res://scenes/main.tscn")
var scene := MAIN_SCENE
_instance = scene.instantiate()
auto_free(_instance)
add_child(_instance)

Some files were not shown because too many files have changed in this diff Show More