29 Commits

Author SHA1 Message Date
a93f7c3897 Arena round 6: revert railgun_m damage, correct playtest record
Arena re-run after the playtest-1 adjustments:

- spam-cruiser arena landed at par (default +9%) - the range buff alone
  priced out the small-gun-spam meta, so revert railgun_m damage 16 -> 14
  (range stays 80). The buff had regressed drone-swarm-vs-cruisers to
  +47%, largely via a hit-count breakpoint (60 HP drone: 5 hits at
  14 dmg, 4 at 16).
- battleship +30% / dreadnought +29% vs pure railgun_s fleets accepted
  as reach-doctrine texture (the l gun's 130 m standoff working as
  intended); repair kept at 4 HP/s (below par in-fight is the correct
  price for free between-wave sustain).

Also corrects the playtest-1 record: it was two FULL playthroughs won in
~40 min each with cruisers only (not two pushes) - a 2.5-3x run-length
gap. Pacing knobs deliberately deferred to playtest 2, since those runs
predate the repair nerf and the l-gun siege range.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-06 22:10:06 +02:00
f8028a6ca2 Adjust combat stats after playtest 1
Playtest 1 (first two pushes, ~40 min game time — pacing on target)
found the railgun_s-spam-cruiser meta and confirmed the repair tool as
overpowered (second signal after the persistent arena escort margin):

- repair_tool 9 -> 4 HP/s: the arena only prices in-fight sustain; real
  runs add free between-wave top-offs across the whole swarm
- railgun_l range 100 -> 130: now outranges stations (120), buying the
  siege role the capital ladder promises
- railgun_m 14 -> 16 dmg, range 70 -> 80: concentration tax softened so
  the ladder reads "pay some DPS efficiency for reach", not
  "strictly worse"
- new tracked arena: railgun_s-spam cruisers vs default cruisers

Module costs untouched, so all threat values stay valid. Docs updated
(derived.md, history.md playtest record, README status).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-06 22:00:34 +02:00
b4fa3e6dff Restructure balancing docs into docs/balancing/
Split the cluttered progression_design.md and content_design.md into
separated documents by role:

- docs/balancing/rules.md    - design rules and principles (moved from
                               progression_design.md, which is removed)
- docs/balancing/targets.md  - the chosen base numbers: run shape,
                               factory curve, threat ladder (achieved
                               values adopted), combat anchors, pacing
                               anchors
- docs/balancing/derived.md  - current tuned state of all derived
                               numbers, mirroring the configs
- docs/balancing/process.md  - pass order, tuning discipline learned in
                               arena rounds 1-5, tools, next-round
                               checklist
- docs/balancing/history.md  - chronological record: decisions, numbers
                               pass, calculator bugs, arena rounds,
                               pacing pass
- docs/balancing/README.md   - index, status, open action items (moved
                               from progression_design.md)

content_design.md slims back down to actual content: footprint gating,
hull grids, gating matrix (module names updated to railguns), and the
production tree structure with its fiction - numbers, anchors, arena
logs, and pacing all moved to docs/balancing/. Stale references in the
config comments updated to the new locations.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-06 17:15:08 +02:00
dcc6af123f implement cost formula for asteroid expansion 2026-07-04 19:59:29 +02:00
f62b7bb78e Pacing pass: unlock ladder, threat rate, economy values
Replace the everything-at--1 test setup with the real progression:
starting set is exactly drone/frigate/railgun_s/salvager; the ladder
runs destroyer+repair+armor at level 0, supports at 1, the quartz gate
(cruiser, railgun_m, afterburner, chip/hardened shortcuts) at 2,
battlecruiser at 4, battleship+railgun_l at 6, dreadnought at 8,
carrier+drone_hangar at 9, with unlock_requires edges cruiser ->
battlecruiser -> battleship -> dreadnought/carrier and railgun_m ->
railgun_l.

world.toml: threat_rate_formula 2*x + 0.15*x*x (below the player's
achievable military output early, crossing at the late boundary,
overwhelming by cycle ~24), starting_building_blocks 1000 -> 200,
expansion cost 200 -> 400 flat (placeholder until action item 4),
artifact_win_count 3 -> 5 (winning means choosing the artifact over a
schematic five times across ~7 cumulative offers).

Bug fix found during the pass: the building_block recipe carried no
unlock_at_station_level, and since building blocks appear in no
schematic's materials, implicit unlocking could never reach it - the
recipe was silently locked at game start. Now explicitly -1.

All values and derivations documented in content_design.md, "Pacing
pass - first values".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 12:49:35 +02:00
27c3a7b65b Combat stats round 6: combat pass converged
Round 5 (with fight durations): TTK anchor validated - mirrors run
22.7/71.2/94.6 s (drone/cruiser/battleship), most fights within
22-72 s, destroyers-vs-dreadnought the accepted 214 s outlier. All
matchups converged: mirrors 5-10%, swarm vs cruisers +15%, frigates
vs battleship +13% (dropped on its own, confirming the noise floor),
dreadnought +3%, glass vs armored +10%, two-to-one 78%, stations 44%.

Two two-round signals actioned per the convergence policy:
battlecruiser hull 2200 -> 2400 (mixed fleet won +20%/+18% twice) and
repair_amount 12 -> 9 (~0.7 HP/s per threat; escorted team held +24%
twice with all frigates surviving). Everything else frozen; further
refinement moves to real-game playtests. Removed the arena
end-condition action item (fixed upstream).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 12:43:05 +02:00
9ddd622870 fix but where balancing matches did not finish until enemy hq was destroyed 2026-07-04 09:29:13 +02:00
df9f0d5ccd show total time in balancing target arenas 2026-07-04 09:17:32 +02:00
db7a03dc1f Combat stats round 5: final nudges and convergence policy
Round 4: mirrors 0-3%, swarm vs cruisers +7%, glass vs armored
resolved at +3% for armored (armor 1200 confirmed). Noise floor
established at ~+/-10% per single run (battleship margin ignored a
-10% EHP cut; repair drifted 14->24% with no repair changes).

Round-5 nudges for the armor-coupling overshoots: battlecruiser hull
2000 -> 2200, dreadnought/carrier 22500 -> 24000 (two-round
persistent deficit vs destroyers). The battleship's +23% over a pure
frigate fleet is accepted as doctrine texture rather than chased: the
edge is mechanical (range) and the fair anti-capital answer is the
mixed fleet, whose arena is balanced. Convergence policy documented:
act only on two-round signals, +/-20% counts as converged for v1.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 07:56:52 +02:00
67054f432f Combat stats round 4 from arena round 3 margins
Round 3 (narrow lanes; arena geometry is part of the fixture from
here): dreadnought closed to -11%, battleship improved to +22%, the
drone swarm flipped to +14% over cruisers under full engagement, glass
beat armored for the third consecutive round, mirrors/repair/
two-to-one healthy, stations cracked at 51% by the 3x swarm under the
new geometry (watch, not touched).

Round-4 knobs: armor_plates 1000 -> 1200 (~37 HP/threat; persistent
glass signal, also lifts armor-carrying cruiser/BC/destroyer/DN
loadouts), battlecruiser hull 2500 -> 2000 (net -300 EHP after its
armor gain), battleship 7000 -> 6300 (loadout has no armor, clean
-10%), dreadnought/carrier 19000 -> 22500 (opposing destroyers gain
armor too, so the larger step). Anchors doc notes the emerging shape:
the arena prices capitals as tanks with taxed guns.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 07:50:50 +02:00
7a9a7a35ad make arenas more narrow to avoid fleets passing each other 2026-07-04 07:47:08 +02:00
f822047b4e Combat stats round 3 from arena round 2 margins
Round 2 (with the new EHP-margin logging): mirrors healthy and the
round-1 side bias was noise; drones-vs-cruisers (10%) and
mixed-vs-battlecruisers (14%) near parity; battleship over at +33%
while dreadnought under at -37%; glass-vs-armored narrowed to 11%
(watch); repair escort fair at 11%; two-to-one decisive; the 3x swarm
now cracks the station set at 13%.

Round-3 knobs: weapon_stabilizer range multiplier 1.5 -> 1.3 (range is
the strongest stat under the orbit AI, and the stabilized battleship
was the one loadout still overperforming), plus per-hull HP trims with
the 15 HP/threat anchor demoted to a prior and per-hull HP documented
as the empirical trim knob: battlecruiser 2700 -> 2500, battleship
7500 -> 7000, dreadnought/carrier 15500 -> 19000.

Action items: mirror-bias and EHP-logging items resolved (the latter
implemented upstream); new item to verify the arena end condition seen
idling in round 1 with all ships dead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 07:34:47 +02:00
d9e7dd0fe8 show team EHP in balancing target 2026-07-04 07:27:11 +02:00
4d5b218fec implement logging of arena states 2026-07-04 07:27:11 +02:00
97bafc95c3 Combat stats round 2 from arena round 1 findings
Round 1 findings: concentrated fleets won all four equal-threat
cross-tier matchups flawlessly; glass destroyers beat armored; repair
escort beat raw numbers flawlessly; two stations annihilated a 3x
threat swarm through 200 m approach fire; team 1 won all three mirror
matches (possible sim bias, recorded as action item 6, plus action
item 7 for HP-margin logging).

Knob changes, deliberately few for clean attribution: concentration
tax on m/l gun DPS (railgun_m damage 17 -> 14, railgun_l 70 -> 52),
armor_plates 640 -> 1000 HP (~31 HP/threat: killing removes enemy DPS
while surviving merely delays, so HP must be cheaper than DPS), repair
25 -> 12 HP per cycle (~1 HP/s per threat: in-combat sustain removes
enemy DPS and must be priced like DPS), station range 200 -> 120. Gun
ranges untouched; if concentration still wins flawlessly in round 2,
the range ladder is the next suspect. Anchors and findings documented
in content_design.md; fitted threat values are unaffected by stat
changes, so the arena suite counts stay valid.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-04 06:55:43 +02:00
5aa0544cf2 Combat stats pass: anchor-derived stats and canonical arena suite
Derive all combat stats from documented anchors (content_design.md,
'Combat stat anchors'): weapon DPS ~0.6 per threat with a mild size
discount traded for range (railgun m/l damage 17/70), hull HP at 15
per hull threat (drone 60 up to capitals 15500), armor at a 20/threat
premium (armor_plates 640 HP), repair at ~2 HP/s per threat (25 HP per
cycle), salvager range fixed to 60 m with cargo 20, and a monotone
mobility ladder (the placeholder drone was the least agile ship).
Stations anchored to 'a fresh station holds one early parity wave';
enemy level 0 matches the player station and scales per push. HQ 5000
HP. scrap_despawn_seconds 30 -> 120 so capital-sized scrap drops are
collectable.

Rewrite balancing.toml as the canonical 12-arena suite: class mirrors,
equal-threat cross-tier matchups with counts from the verified threat
values, a two-to-one decisiveness check, armored-vs-glass and
repair-escort doctrine matchups, and station assault. The carrier
arena is expected to lose until drone launching exists (hangar is dead
threat) - documented, not stat-compensated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 20:19:24 +02:00
38fd2e4e89 Fix ThreatCostCalculator: per-unit division, scrap fallback, fixpoint, staggered-recipe max (action items 6-9)
Four algorithm fixes to bring ThreatCostCalculator.cpp into agreement with
tools/threat_report.py and the newly amended REQ-THREAT-ITEM semantics:

6. Scrap-consuming recipes as threat fallback only. Non-reprocessing recipes
   that take scrap as an input are excluded from an item's threat computation
   whenever at least one scrap-free recipe (miner/smelter/assembler) produces
   that item. Previously the scrap_smelting recipe (1 scrap → 1 iron_ingot)
   would have inflated iron_ingot's threat via the max rule.

7. Per-unit item threat. computeRecipeThreatPerUnit() now divides by the
   recipe's output amount, so multi-output recipes price each unit correctly.
   Example: copper_wire (1 copper_ingot, 1 s, output 2) is now 1.5, not 3.

8. Fixpoint resolution. The resolution loop now alternates the non-reprocessing
   pass and the reprocessing pass until neither makes progress, rather than
   running the reprocessing pass once at the end. Items downstream of
   reprocessing-only items (voidsteel_plate, capital_core, capital hulls,
   drone_hangar_module) now resolve correctly.

9. Max rule across staggered recipes. An item is committed only once every
   eligible recipe producing it is computable, so a shallow shortcut recipe
   (e.g. shortcut_steel_plate: 3 iron_ore → 1 steel_plate, resolvable one
   iteration earlier) cannot undercut the expensive base path. A deadlock
   fallback (require_all_recipes=False) handles potential recipe cycles.

docs/requirements.md: REQ-THREAT-ITEM amended for per-unit division, the
scrap-fallback rule, and order-independence via fixpoint.

docs/progression_design.md: action items 6-9 removed (completed); remaining
items 1-5 renumbered unchanged.

tools/threat_report.py: NOTE updated — C++ now matches Python semantics.

bin/test/data/config/recipes.toml: four minimal test recipes added (one per
fix: scrap_iron, dual_wire, downstream_product, staggered_item_{cheap,expensive}).

src/test/ThreatCostCalculatorTest.cpp: four new TEST_CASEs covering each fix.

Expected values with the live config (bin/app/data/config) verified by
threat_report.py: iron_ingot 2, copper_wire 1.5, steel_plate 7, control_chip
12, voidsteel_plate 141, capital_core 240; fitted ships 10.5/47/99/233.5/
354.5/722.5/1491.5/1436.5. All 378 test cases pass.
2026-07-03 18:45:39 +02:00
d889b79658 Write the v2 production tree into the config files
recipes.toml: full v2 rewrite - iron/copper/quartz mining, smelting
incl. the value-losing scrap sink, reprocessing (4 scrap / 4 s,
voidsteel at 20% of the full pool), tiered intermediates, hulls,
module prefabs, and the three drop-only shortcut recipes.

modules.toml: lasers renamed to railguns (implementation unchanged),
prefab materials and numbers-pass production times; combat stats stay
placeholders for the arena pass.

ships.toml: hull-item materials, numbers-pass base production times,
and geometry-validated default_modules loadouts for every ship (waves
now spawn armed).

visuals.toml: item entries for the new palette (quartz, silicon,
copper_coil, control_chip, capacitor_bank, hardened_steel,
ceramic_plate, voidsteel, voidsteel_plate, railgun modules); retired
titanium/alloy/laser items removed.

world.toml: scrap_per_threat = 0.25 per the numbers pass.

threat_report.py: commit an item's threat only once every eligible
recipe is computable - the previous first-resolved-wins behavior let
shortcut recipes underprice items (same flaw exists in
ThreatCostCalculator, recorded as action item 9). Verified: all
default_modules placements valid, verify_recipes and verify_layouts
pass, and the report reproduces the numbers-pass tables exactly
(fitted: 10.5/47/99/233.5/354.5/722.5/1491.5/1436.5). Doc tables
updated for the three geometry-corrected loadouts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 17:05:19 +02:00
b9e70ba83a Add tools/threat_report.py (action item 7)
Reads recipes/ships/modules/world.toml and reports per-item threat
values, module contributions, hull-only and fitted ship threats
(default_modules), producer:consumer ratio tables, and belt
feasibility against the single-belt cap.

Implements the agreed design semantics: per-unit threat (recipe threat
divided by output amount), the scrap-fallback rule, and fixpoint
resolution through reprocessing-only items. Running it against the
current configs surfaced two ThreatCostCalculator deviations, recorded
as new action items: multi-output recipes are double-priced (no
per-unit division), and items downstream of reprocessing-only items
never resolve, underestimating capital hull threat.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 16:47:40 +02:00
3aefc05118 Scrap-consuming recipes as threat fallback, not excluded
Refine the REQ-THREAT-ITEM fix per review: recipes taking scrap as
input participate in an item threat computation only when no
scrap-free recipe produces that item, mirroring the existing
reprocessing-path rule instead of a blanket exclusion.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 16:34:06 +02:00
fe7703d5c3 Add first numbers pass for the v2 production tree
content_design.md: full recipe quantities and durations computed with
a recursive threat calculator - economy constants (scrap_per_threat
0.25, reprocessing 4 scrap / 4 s, voidsteel at threat 100), per-item
threat values, module contributions, and fitted ship threats vs the
ladder (96-124%, smooth ~x2-per-class curve). Checks recorded: ratio
curve realized (t1 1:1, t2 2:3, t3 strange), belt feasibility under
the single-belt cap, block at 4 threat implying ~18 blocks average
building cost for the 4-minute doubling target, and a small-end
deviation note recommending ladder adjustment over chain thinning.

progression_design.md: two new action items - amend REQ-THREAT-ITEM to
exclude scrap-consuming recipes from item threat (the max rule would
otherwise inflate basic materials via the scrap smelting recipe), and
port the calculator to tools/threat_report.py.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 15:05:40 +02:00
72b38df0dd Draft the v2 production tree structure
Add the tree structure draft to the v2 decisions section: mined and
smelted items, reprocessing pool, intermediates per tier with ratio
classes and archetypes, hull and module recipes as input lists, the
resolved m+ hull gate (hardened_steel plus control_chip), shortcut
recipe candidates, and a refactorability spot-check. Quantities and
durations are deferred to the numbers pass against the threat ladder.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 14:26:29 +02:00
c7a168f4a9 Record production tree v2 decisions and resource deposit rules
progression_design.md: rewrite the resource phases around the four
decided inputs (two mined everywhere, one deposit-gated mid resource,
one scrap-only late input), add the Resource deposits rule set
(freedom first / geography later, deposits only in expansions, patch
area as throughput cap, deterministic content, binary mining), note
the dual gating of the mid resource, and add the deposit-layer action
item.

content_design.md: mark the first-pass tree as superseded and record
the v2 decisions — iron/copper/quartz/voidsteel with their fiction
(M-type asteroid, quartz geodes, battle-forged voidsteel), titanium
dropped with its gating role moved to electronics and possibly a
quality-steel step, the material palette fingerprints, and the
laser-to-railgun rename with lasers reserved as a future weapon type.
Update the balancing target phase boundaries accordingly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 13:54:24 +02:00
a6451f2bdf Add balancing targets section to content_design.md
Record the six root numbers for the balancing pass: run length (win
within ~2 h game time, cycle 20-24), phase boundaries, factory size
curve, fitted threat-cost ladder, swarm fleet size (~25 ships), and
block economy roots (bootstrap, doubling time, expansion cadence).
Derived values are always re-derived from these roots, never patched
directly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 11:30:43 +02:00
493208d230 Add growth curve rules to the building block economy
Diagnose that player output equals building count, so the growth
curve must be shaped by the block and space economy: escalating
expansion costs (formula of expansions purchased) as the long-run
curve, a designed doubling time for the block feedback loop, and an
explicit rule that growth is limited by economy, never by
construction waiting. Note the HQ intake ceiling and add the
condensed-building-block idea to future work, plus an action item
for the expansion cost formula.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 10:50:42 +02:00
4098e40c8c Sync progression_design.md with implemented action items
Prune completed action items 1-4 and 8 (scrap-from-threat, schematic
upgrade and ship level removal, balancing tool cleanup, unlock
prerequisites), renumber the remaining three, and update stale
cross-references: cite REQ-LOCK-PREREQ and unlock_requires, reflect
that REQ-THREAT-SCRAP is now the 1/scrap_per_threat constant, and
drop the obsolete level-up wording from the artifact rule.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 09:44:53 +02:00
730cd3bdf3 refinement 2026-07-03 08:36:33 +02:00
437ac97355 Rewrite progression_design.md as rules/principles document
Turn the rough draft into structured rules for the production tree,
progression pacing, and balancing: resource phases, ratio curve,
shortcut recipes, refactorability, cost archetypes, threat model,
drop pacing, scrap/block economies, and numeric guardrails.

Includes agreed decisions: ship scrap derived from threat via a
scrap_per_threat key, no duplicate schematic drops (Mk2 upgrade
recipes deferred to future work), removal of ship levels, and an
action-item list for the follow-up requirements/code changes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyCu8vwChKMbLJQ3xosYEN
2026-07-03 08:36:33 +02:00
41081620f0 add first draft 2026-07-03 08:36:33 +02:00
158 changed files with 2599 additions and 8749 deletions

View File

@@ -4,27 +4,17 @@ message(STATUS "Using CMake ${CMAKE_VERSION}")
include(cmake/add_files.cmake)
include(cmake/create_source_groups.cmake)
include(cmake/version.cmake)
# Project ----------------------------------------------------------------------
# Product identity — anything that depends on the product/project name is defined
# here so it lives in a single place and can change in the future. These values
# feed the build targets in src/CMakeLists.txt and the Windows version resource
# (see cmake/version.rc.in).
set(PRODUCT_NAME "DotaFactory") # internal name and executable base name
set(PRODUCT_DISPLAY_NAME "Dota Factory") # human-readable product / file description
set(PRODUCT_COMPANY "TODO: company") # placeholder
set(PRODUCT_COPYRIGHT "TODO: copyright") # placeholder
project(${PRODUCT_NAME})
project(DotaFactory)
set(CMAKE_BUILD_TYPE_INIT "Release")
# Qt ---------------------------------------------------------------------------
find_package(Qt5 COMPONENTS Widgets Network Multimedia Charts Svg REQUIRED)
find_package(Qt5 COMPONENTS Widgets Network Multimedia Charts REQUIRED)
if(Qt5Widgets_FOUND)
message(STATUS "Found Qt ${Qt5Widgets_VERSION_STRING}")
@@ -64,7 +54,6 @@ function(COPY_QT_BINARIES TARGET_DIR IS_DEBUG)
configure_file("${QT_BINARY_DIR}/Qt5Network${SUFFIX}.dll" "${TARGET_DIR}/Qt5Network${SUFFIX}.dll" COPYONLY)
configure_file("${QT_BINARY_DIR}/Qt5Widgets${SUFFIX}.dll" "${TARGET_DIR}/Qt5Widgets${SUFFIX}.dll" COPYONLY)
configure_file("${QT_BINARY_DIR}/Qt5Multimedia${SUFFIX}.dll" "${TARGET_DIR}/Qt5Multimedia${SUFFIX}.dll" COPYONLY)
configure_file("${QT_BINARY_DIR}/Qt5Svg${SUFFIX}.dll" "${TARGET_DIR}/Qt5Svg${SUFFIX}.dll" COPYONLY)
endfunction(COPY_QT_BINARIES)

View File

@@ -1,6 +1,5 @@
[[building]]
id = "belt"
tooltip = "Transports items one tile at a time in the direction it faces."
cost = 2
player_placeable = true
construction_time_seconds = 0.2
@@ -8,7 +7,6 @@ surface_mask = ["A>"]
[[building]]
id = "splitter"
tooltip = "Splits an incoming item stream between two outputs, with optional per-output filters."
cost = 3
player_placeable = true
construction_time_seconds = 0.5
@@ -16,7 +14,6 @@ surface_mask = ["<A>"]
[[building]]
id = "tunnel_entry"
tooltip = "Sends items underground so belts can cross. Places an entry, or an exit when it would connect to a matching entry under the cursor."
cost = 5
player_placeable = true
construction_time_seconds = 0.5
@@ -24,7 +21,6 @@ surface_mask = ["A>"]
[[building]]
id = "tunnel_exit"
tooltip = "Receives items from a matching tunnel entry and pushes them onward."
cost = 5
player_placeable = true
construction_time_seconds = 0.5
@@ -32,7 +28,6 @@ surface_mask = ["A>"]
[[building]]
id = "miner"
tooltip = "Extracts a selected ore from the asteroid; every tile yields any ore."
cost = 15
player_placeable = true
construction_time_seconds = 1
@@ -42,7 +37,6 @@ surface_mask = [
[[building]]
id = "smelter"
tooltip = "Melts ore or scrap into basic materials. No recipe selection needed."
cost = 20
player_placeable = true
construction_time_seconds = 1
@@ -53,7 +47,6 @@ surface_mask = [
[[building]]
id = "assembler"
tooltip = "Crafts a selected recipe from the production tree into intermediate or final parts."
cost = 35
player_placeable = true
construction_time_seconds = 1
@@ -64,7 +57,6 @@ surface_mask = [
[[building]]
id = "reprocessing_plant"
tooltip = "Consumes scrap and yields one random higher-tier product per cycle."
cost = 40
player_placeable = true
construction_time_seconds = 1
@@ -76,7 +68,6 @@ surface_mask = [
[[building]]
id = "shipyard"
tooltip = "Builds autonomous combat ships from a selected schematic and module layout."
cost = 60
player_placeable = true
construction_time_seconds = 1
@@ -87,12 +78,10 @@ surface_mask = [
[[building]]
id = "salvage_bay"
tooltip = "Drop-off point where salvage ships unload collected scrap onto belts."
cost = 25
player_placeable = true
construction_time_seconds = 1
output_buffer_capacity = 20
surface_mask = [
"<AAS",
" AAS",
"SAA",
"SAA>",
]

View File

@@ -7,9 +7,10 @@
# Combat stats are placeholders until the arena balancing pass;
# production_time_seconds values come from the numbers pass.
#
# Unlock gating is defined in unlocks.toml, not here (REQ-LOCK-EXPLICIT): a
# module id granted by an unlock group starts locked and is awarded via a
# defence station drop; ids absent from unlocks.toml (railgun_s) start unlocked.
# Unlock progression is mostly disabled (unlock_at_station_level = -1) pending
# the pacing pass. The railguns are the exception: railgun_m is gated to
# station level 1, and railgun_l requires railgun_m to be unlocked first
# (unlock_requires) — a demonstration of the prerequisite chain.
#
# Surface mask footprint ladder — footprints gate which hulls can mount a
# module, purely through geometry (see ships.toml for the matching hull
@@ -31,7 +32,7 @@
[[module]]
id = "railgun_s"
tooltip = "Small railgun. Fast-firing, short range, low damage; fits any hull."
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "railgun_s_module", amount = 1}]
production_time_seconds = 1
@@ -46,7 +47,7 @@ attack_rate_hz = 2.0
[[module]]
id = "railgun_m"
tooltip = "Medium railgun. Higher damage at longer range; needs a 2x2 slot."
unlock_at_station_level = 2
surface_mask = [
"OO",
"OO"]
@@ -55,15 +56,19 @@ production_time_seconds = 3
fill_color = "#FF8040"
glyph = "Rm"
# damage 14 keeps a 60 HP drone at 5 hits — 15+ crosses a breakpoint that
# silently adds ~25% effective DPS vs drones (docs/balancing/history.md,
# round 6).
[module.weapon]
damage = 14
attack_range_m = 70
attack_range_m = 80
attack_rate_hz = 1.5
[[module]]
id = "railgun_l"
tooltip = "Large railgun. Heavy damage at long range; needs a 3x3 slot."
unlock_at_station_level = 6
unlock_requires = ["railgun_m"]
surface_mask = [
"OOO",
"OOO",
@@ -73,9 +78,12 @@ production_time_seconds = 4
fill_color = "#FF8040"
glyph = "Rl"
# attack_range_m 130 deliberately exceeds the station range of 120
# (stations.toml) — the l gun is the only weapon that can besiege stations
# without tanking their fire (docs/balancing/history.md, playtest 1).
[module.weapon]
damage = 52
attack_range_m = 100
attack_range_m = 130
attack_rate_hz = 0.8
# -----------------------------------------------------------------------------
@@ -84,7 +92,7 @@ attack_rate_hz = 0.8
[[module]]
id = "salvager"
tooltip = "Collects scrap from wrecks and stores it in the ship's cargo hold."
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "salvager_module", amount = 1}]
production_time_seconds = 1
@@ -99,7 +107,7 @@ collection_rate_hz = 0.5
[[module]]
id = "repair_tool"
tooltip = "Repairs damaged friendly ships and defence stations within range."
unlock_at_station_level = 0
surface_mask = ["O"]
materials = [{item = "repair_tool_module", amount = 1}]
production_time_seconds = 1
@@ -117,7 +125,7 @@ repair_range_m = 80
[[module]]
id = "afterburner"
tooltip = "Greatly boosts top speed and forward acceleration."
unlock_at_station_level = 2
surface_mask = ["OOO"]
materials = [{item = "afterburner_module", amount = 1}]
production_time_seconds = 1
@@ -131,7 +139,7 @@ added_main_acceleration_mpss = 60
[[module]]
id = "maneuvering_thrusters"
tooltip = "Improves top speed and lateral/braking acceleration."
unlock_at_station_level = 1
surface_mask = ["OO"]
materials = [{item = "maneuvering_thrusters_module", amount = 1}]
production_time_seconds = 1
@@ -148,7 +156,7 @@ added_maneuvering_acceleration_mpss = 10
[[module]]
id = "armor_plates"
tooltip = "Adds a large flat bonus to the ship's hit points."
unlock_at_station_level = 0
surface_mask = ["OO"]
materials = [{item = "armor_plates_module", amount = 1}]
production_time_seconds = 1
@@ -161,7 +169,7 @@ added_hp = 1200
[[module]]
id = "sensor_booster"
tooltip = "Extends the ship's sensor range."
unlock_at_station_level = 1
surface_mask = ["OO"]
materials = [{item = "sensor_booster_module", amount = 1}]
production_time_seconds = 1
@@ -177,7 +185,7 @@ added_sensor_range_m = 50
[[module]]
id = "weapon_upgrade"
tooltip = "Increases the damage of all weapons on the ship."
unlock_at_station_level = 4
surface_mask = [
"OO",
"OX",
@@ -193,7 +201,7 @@ multiplied_damage = 1.2
[[module]]
id = "weapon_primer"
tooltip = "Increases the fire rate of all weapons on the ship."
unlock_at_station_level = 4
surface_mask = [
"OO",
"OX",
@@ -209,7 +217,7 @@ multiplied_attack_rate_hz = 1.2
[[module]]
id = "weapon_stabilizer"
tooltip = "Extends weapon range at the cost of some fire rate."
unlock_at_station_level = 3
surface_mask = [
"OO",
"OX",
@@ -232,7 +240,7 @@ multiplied_attack_rate_hz = 0.8
[[module]]
id = "drone_bay"
tooltip = "Drone launch bay (capability not yet implemented)."
unlock_at_station_level = 5
surface_mask = [
"OO",
"OO"]
@@ -244,7 +252,7 @@ glyph = "Db"
[[module]]
id = "drone_hangar"
tooltip = "Large drone hangar (capability not yet implemented)."
unlock_at_station_level = 9
surface_mask = [
"OOOOOO",
"OOOOOO"]

View File

@@ -142,12 +142,12 @@ duration_seconds = 1.5
# Depth-3 chain (ore -> ingot -> plate -> block) is the factory's
# doubling-time knob; see the block economy rules in docs/balancing/rules.md.
# unlocked_at_start: building blocks appear in no schematic's materials, so the
# implicit item graph can never reach this recipe (REQ-LOCK-IMPLICIT).
# Explicitly unlocked at start (-1): building blocks appear in no
# schematic's materials, so implicit unlocking can never reach this recipe.
[[recipe]]
id = "building_block"
unlock_at_station_level = -1
building = "assembler"
unlocked_at_start = true
inputs = [{item = "steel_plate", amount = 2}]
outputs = [{item = "building_block", amount = 4}]
duration_seconds = 2.0
@@ -220,14 +220,15 @@ outputs = [{item = "capital_core", amount = 1}]
duration_seconds = 10.0
# -----------------------------------------------------------------------------
# Shortcut recipes — drop-only assembler recipes, gated by unlock groups in
# unlocks.toml (REQ-LOCK-EXPLICIT). Pure rewards: item threat stays defined by
# Shortcut recipes — drop-only assembler recipe schematics
# (unlock_at_station_level >= 0). Pure rewards: item threat stays defined by
# the base (expensive) path via the max rule, so shortcuts give real factory
# efficiency without shifting any balance.
# -----------------------------------------------------------------------------
[[recipe]]
id = "shortcut_steel_plate"
unlock_at_station_level = 1
building = "assembler"
inputs = [{item = "iron_ore", amount = 3}]
outputs = [{item = "steel_plate", amount = 1}]
@@ -235,6 +236,7 @@ duration_seconds = 2.0
[[recipe]]
id = "shortcut_control_chip"
unlock_at_station_level = 2
building = "assembler"
inputs = [{item = "quartz", amount = 2}]
outputs = [{item = "control_chip", amount = 1}]
@@ -242,6 +244,7 @@ duration_seconds = 4.0
[[recipe]]
id = "shortcut_hardened_steel"
unlock_at_station_level = 2
building = "assembler"
inputs = [{item = "iron_ingot", amount = 4}]
outputs = [{item = "hardened_steel", amount = 1}]

View File

@@ -4,9 +4,10 @@
# content; stats, materials, and production times are placeholders until the
# recipe and balancing passes.
#
# Unlock gating is defined in unlocks.toml, not here (REQ-LOCK-EXPLICIT): a ship
# id granted by an unlock group starts locked and is awarded via a defence
# station drop; ids absent from unlocks.toml (drone, frigate) start unlocked.
# Unlock progression is mostly disabled (unlock_at_station_level = -1) pending
# the balancing pass. The capital hulls are the exception: battleship is gated
# to station level 1, and dreadnought (level 2) requires battleship to be
# unlocked first (unlock_requires) — a demonstration of the prerequisite chain.
#
# Size classes:
# xs drone 1 cell — exactly one 1x1 module
@@ -21,6 +22,7 @@
[[ship]]
id = "drone"
unlock_at_station_level = -1
layout = ["O"]
default_modules = [{type = "railgun_s", x = 0, y = 0, rotation = "east"}]
@@ -47,6 +49,7 @@ sensor_range_m = 150
# L-shaped weapon modifier, or an afterburner spanning the full center line.
[[ship]]
id = "frigate"
unlock_at_station_level = -1
layout = [
"XOX",
"OOO",
@@ -81,6 +84,7 @@ sensor_range_m = 200
# mount medium hardware.
[[ship]]
id = "destroyer"
unlock_at_station_level = 0
layout = [
"OXOXO",
"OOOOO",
@@ -116,6 +120,7 @@ sensor_range_m = 220
# supports; no 3x3 area exists for an l gun.
[[ship]]
id = "cruiser"
unlock_at_station_level = 2
layout = [
"XOOX",
"OOOO",
@@ -153,6 +158,8 @@ sensor_range_m = 250
# stern leave no 3x3 area for an l gun and no 2x6 area for a drone hangar.
[[ship]]
id = "battlecruiser"
unlock_at_station_level = 4
unlock_requires = ["cruiser"]
layout = [
"OOXXOO",
"OOOOOO",
@@ -194,6 +201,8 @@ sensor_range_m = 260
# so no 2x6 drone hangar fits.
[[ship]]
id = "battleship"
unlock_at_station_level = 6
unlock_requires = ["battlecruiser"]
layout = [
"XOOOOX",
"OOOOOO",
@@ -235,6 +244,8 @@ sensor_range_m = 280
# stay the only hangar hull. Bow and stern strips hold supports.
[[ship]]
id = "dreadnought"
unlock_at_station_level = 8
unlock_requires = ["battleship"]
layout = [
"XXXOOOOOXXX",
"OOOXOOOXOOO",
@@ -277,6 +288,8 @@ sensor_range_m = 300
# the lower decks hold supports and 2x2 point-defense m guns.
[[ship]]
id = "carrier"
unlock_at_station_level = 9
unlock_requires = ["battleship"]
layout = [
"XOOOOOOOOX",
"OOOOOOOOOO",

View File

@@ -1,140 +0,0 @@
# Unlock groups (REQ-LOCK-EXPLICIT, REQ-DEF-SCHEMATIC-DROP).
#
# Each [[unlock]] is a group of ships/modules/buildings/recipes awarded together
# from a single defence station drop. Anything NOT granted by any group is
# available from game start. `station_level` gates when a group becomes eligible;
# `requires` lists prerequisite unlock-group ids (REQ-LOCK-PREREQ).
#
# Most entries below are single-item groups that reproduce the previous per-item
# progression. The salvage_operations and reprocessing groups are the grouped
# unlocks: they lock the salvager module + salvage bay, and the reprocessing
# plant, from game start.
# --- Grouped unlocks -------------------------------------------------------
[[unlock]]
id = "salvage_operations"
station_level = 1
modules = ["salvager"]
buildings = ["salvage_bay"]
[[unlock]]
id = "reprocessing"
station_level = 2
buildings = ["reprocessing_plant"]
# --- Ships -----------------------------------------------------------------
[[unlock]]
id = "destroyer"
station_level = 0
ships = ["destroyer"]
[[unlock]]
id = "cruiser"
station_level = 2
ships = ["cruiser"]
[[unlock]]
id = "battlecruiser"
station_level = 4
requires = ["cruiser"]
ships = ["battlecruiser"]
[[unlock]]
id = "battleship"
station_level = 6
requires = ["battlecruiser"]
ships = ["battleship"]
[[unlock]]
id = "dreadnought"
station_level = 8
requires = ["battleship"]
ships = ["dreadnought"]
[[unlock]]
id = "carrier"
station_level = 9
requires = ["battleship"]
ships = ["carrier"]
# --- Modules ---------------------------------------------------------------
[[unlock]]
id = "repair_tool"
station_level = 0
modules = ["repair_tool"]
[[unlock]]
id = "armor_plates"
station_level = 0
modules = ["armor_plates"]
[[unlock]]
id = "maneuvering_thrusters"
station_level = 1
modules = ["maneuvering_thrusters"]
[[unlock]]
id = "sensor_booster"
station_level = 1
modules = ["sensor_booster"]
[[unlock]]
id = "railgun_m"
station_level = 2
modules = ["railgun_m"]
[[unlock]]
id = "afterburner"
station_level = 2
modules = ["afterburner"]
[[unlock]]
id = "weapon_stabilizer"
station_level = 3
modules = ["weapon_stabilizer"]
[[unlock]]
id = "weapon_upgrade"
station_level = 4
modules = ["weapon_upgrade"]
[[unlock]]
id = "weapon_primer"
station_level = 4
modules = ["weapon_primer"]
[[unlock]]
id = "drone_bay"
station_level = 5
modules = ["drone_bay"]
[[unlock]]
id = "railgun_l"
station_level = 6
requires = ["railgun_m"]
modules = ["railgun_l"]
[[unlock]]
id = "drone_hangar"
station_level = 9
modules = ["drone_hangar"]
# --- Assembler recipes -----------------------------------------------------
[[unlock]]
id = "shortcut_steel_plate"
station_level = 1
recipes = ["shortcut_steel_plate"]
[[unlock]]
id = "shortcut_control_chip"
station_level = 2
recipes = ["shortcut_control_chip"]
[[unlock]]
id = "shortcut_hardened_steel"
station_level = 2
recipes = ["shortcut_hardened_steel"]

View File

@@ -335,7 +335,7 @@ salvage_color = "#33ccff"
width_px = 2
# -----------------------------------------------------------------------------
# Build / deconstruct / selection overlays
# Build / demolish / selection overlays
#
# All overlay colors carry an alpha channel so they composite over the
# underlying scene.
@@ -344,14 +344,10 @@ width_px = 2
[overlays]
ghost_valid = "#ffffff44" # builder-mode ghost, placement allowed (REQ-BLD-GHOST)
ghost_invalid = "#ff000044" # builder-mode ghost, placement invalid (REQ-BLD-PLACE-VALID)
deconstruct_tint = "#ff000033" # deconstruct-mode hover tint
demolish_tint = "#ff000033" # demolish-mode hover tint
selection_rect = "#00ff00" # box-drag selection rectangle (REQ-UI-MULTI-SELECT)
tile_highlight = "#ffffff22" # tile under cursor
selected_outline = "#ffff00" # outline drawn around currently-selected building(s)
copy_config = "#33ccff66" # copy-settings eligible-target tint + copy/paste flash (REQ-BLD-COPY-CONFIG-FEEDBACK)
locked_asteroid = "#0000007f" # tint over the asteroid left of the buildable edge (not yet unlocked by expansion)
modal_dim = "#00000099" # semi-transparent black dim behind modal dialogs/menus (REQ-UI-MODAL-DIM)
tunnel_preview = "#00ff0055" # tunnel connection preview: matched end + tiles between (REQ-BLD-TUNNEL-MODE)
# -----------------------------------------------------------------------------
# Schematic-drop toasts (REQ-UI-SCHEMATIC-TOAST)
@@ -361,17 +357,3 @@ tunnel_preview = "#00ff0055" # tunnel connection preview: matched end + tiles
bg = "#000000cc"
fg = "#ffffff"
font_size = 14
# -----------------------------------------------------------------------------
# Building status light (REQ-UI-STATUS-LIGHT)
#
# Fill color per production state, drawn as a small circle in the building's
# upper-right corner, plus the constant outline color.
# -----------------------------------------------------------------------------
[status_light]
grey = "#808080" # no recipe/schematic selected
green = "#33cc33" # producing (Salvage Bay: holding scrap)
red = "#cc3333" # idle, input missing (Salvage Bay: empty)
yellow = "#e6c619" # idle, output buffer full
outline = "#000000"

View File

@@ -1,7 +1,6 @@
[world]
height_tiles = 40
refund_percentage = 100
deconstruction_time_seconds = 0.1
starting_building_blocks = 200
scrap_despawn_seconds = 120
scrap_per_threat = 0.25
@@ -11,8 +10,6 @@ tunnel_max_distance_tiles = 10
departure_interval_seconds = 20
orbit_factor = 0.8
rally_orbit_radius_tiles = 5.0
building_blocks_tooltip = "Building blocks are the currency for construction. Spend them to place buildings and to expand the asteroid. Produce building blocks in your assemblers and deliver them to the HQ on a belt to grow your stock."
artifact_tooltip = "Artifacts are the key to victory. Earn one by choosing the artifact reward when you destroy a set of enemy defence stations. Collect enough of them to win the game."
[regions]
asteroid_width_tiles = 60
@@ -20,13 +17,6 @@ player_buffer_width_tiles = 20
contest_zone_width_tiles = 60
enemy_buffer_width_tiles = 20
[scroll]
# View pan speed (REQ-UI-SCROLL-SPEED): slow near the asteroid, fast across the
# contest zone, with a linear ramp of the given width straddling each boundary.
pan_speed_slow_tiles_per_second = 16.0
pan_speed_fast_tiles_per_second = 32.0
pan_ramp_band_width_tiles = 16
[expansion]
columns_per_expansion_tiles = 10
# x = expansions already purchased; ~1 per cycle mid-game, decelerating

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#3a6fa8"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="16" cy="16" r="6.2"/><circle cx="16" cy="16" r="2.2"/><path d="M16 5.5v3M16 23.5v3M5.5 16h3M23.5 16h3M8.6 8.6 10.7 10.7M23.4 8.6 21.3 10.7M8.6 23.4 10.7 21.3M23.4 23.4 21.3 21.3"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 499 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#6a6a6a"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="4" y="10" width="24" height="12" rx="3"/><path d="M9 13 12.5 16 9 19"/><path d="M14.5 13 18 16 14.5 19"/><path d="M20 13 23.5 16 20 19"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 453 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#cc3333"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M7 10h18"/><path d="M9.5 10 11 26h10l1.5-16"/><path d="M13 10V6.5h6V10"/><path d="M13.5 14v8M18.5 14v8"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 421 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#6b4a2c"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="9" y="5" width="14" height="8" rx="1.5"/><path d="M11 13 16 26 21 13"/><path d="M13 17.5h6"/><path d="M14.5 21.5h3"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 433 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#6a3a8a"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="18" r="4"/><circle cx="20" cy="18" r="4"/><path d="M10.6 16.6 13.4 19.4M13.4 16.6 10.6 19.4M18.6 16.6 21.4 19.4M21.4 16.6 18.6 19.4"/><path d="M16 4v8"/><path d="M13 9 16 12 19 9"/><path d="M16 24v4"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 528 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#b8a23a"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M7 13h18l-2 13H9z"/><path d="M16 3v7"/><path d="M12 7 16 11 20 7"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 383 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#3f6580"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M16 4c2 3 2.6 6 2.6 9.5V16h-5.2v-2.5C13.4 10 14 7 16 4z"/><circle cx="16" cy="10" r="1.3"/><path d="M13.4 15 11 18h2.4z"/><path d="M18.6 15 21 18h-2.4z"/><path d="M14.7 17 16 21 17.3 17"/><path d="M9 25h14"/><path d="M12 25v-2M20 25v-2"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 554 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#b85a1e"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 9h14l-2.5 8h-9z"/><path d="M8 9h16"/><path d="M11 26c-1-1.8.4-3 .4-4 .9 1 1.6 2.2 1.6 4"/><path d="M16 26c-1-2 .4-3.4.4-4.4 .9 1 1.6 2.6 1.6 4.4"/><path d="M21 26c-1-1.8.4-3 .4-4 .9 1 1.6 2.2 1.6 4"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 519 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#7a7a5a"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M5 16h11"/><path d="M16 8v16"/><path d="M13.5 10.5 16 8 18.5 10.5"/><path d="M13.5 21.5 16 24 18.5 21.5"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 422 B

View File

@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<rect width="100" height="100" rx="22" fill="#4f7562"/>
<g transform="translate(13,13) scale(2.3125)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 9h24"/><path d="M8 9C8 24 24 24 24 9"/><path d="M14.5 18.5 17.5 20 14.5 21.5"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 398 B

View File

@@ -4,7 +4,8 @@
# using the verified fitted threat values from tools/threat_report.py:
# drone 10.5, frigate 47, destroyer 99, cruiser 233.5,
# battlecruiser 354.5, battleship 722.5, dreadnought 1491.5,
# carrier 1436.5, glass destroyer (8 small guns) 92, repair drone 17.
# carrier 1436.5, glass destroyer (8 small guns) 92, repair drone 17,
# railgun_s-spam cruiser (12 small guns) 178.
# Module arrays mirror the ships' default_modules loadouts unless a
# doctrine variant is the point of the arena.
#
@@ -348,6 +349,50 @@ enemy_buffer_width_tiles = 10
{type = "railgun_s", x = 4, y = 1, rotation = "east"},
]
[[arena]]
name = "Railgun_s-spam cruisers vs default cruisers (1424 vs 1401)"
# Tracks the playtest-1 meta: cruiser hulls filled with 12 small guns
# (max DPS/threat, no armor, range 50) against the default m-gun fit.
# The concentration tax means the spam side SHOULD win a brawl somewhat;
# this arena bounds its margin — a blowout here means the small-gun
# premium or the m-gun range edge needs retuning.
height_tiles = 10
player_buffer_width_tiles = 10
contest_zone_width_tiles = 50
enemy_buffer_width_tiles = 10
[[arena.team]]
name = "Spam"
[[arena.team.ship]]
schematic = "cruiser"
count = 8
modules = [
{type = "railgun_s", x = 1, y = 0, rotation = "east"},
{type = "railgun_s", x = 2, y = 0, rotation = "east"},
{type = "railgun_s", x = 0, y = 1, rotation = "east"},
{type = "railgun_s", x = 1, y = 1, rotation = "east"},
{type = "railgun_s", x = 2, y = 1, rotation = "east"},
{type = "railgun_s", x = 3, y = 1, rotation = "east"},
{type = "railgun_s", x = 0, y = 2, rotation = "east"},
{type = "railgun_s", x = 1, y = 2, rotation = "east"},
{type = "railgun_s", x = 2, y = 2, rotation = "east"},
{type = "railgun_s", x = 3, y = 2, rotation = "east"},
{type = "railgun_s", x = 1, y = 3, rotation = "east"},
{type = "railgun_s", x = 2, y = 3, rotation = "east"},
]
[[arena.team]]
name = "Default"
[[arena.team.ship]]
schematic = "cruiser"
count = 6
modules = [
{type = "railgun_m", x = 0, y = 1, rotation = "east"},
{type = "railgun_m", x = 2, y = 1, rotation = "east"},
{type = "armor_plates", x = 1, y = 0, rotation = "east"},
{type = "maneuvering_thrusters", x = 1, y = 3, rotation = "east"},
]
[[arena]]
name = "Repair escort vs raw numbers (444 vs 444)"
height_tiles = 10

View File

@@ -83,8 +83,6 @@ id = "salvage_bay"
cost = 25
player_placeable = true
construction_time_seconds = 15
output_buffer_capacity = 20
tooltip = "Drop-off point for salvage ships."
surface_mask = [
"SAA",
"SAA>",

View File

@@ -1,6 +1,6 @@
[[module]]
id = "armor_plate"
tooltip = "Adds a large flat bonus to hit points."
unlock_at_station_level = -1
surface_mask = ["OO"]
materials = [{item = "iron_ingot", amount = 2}]
production_time_seconds = 3
@@ -12,6 +12,7 @@ multiplied_hp = 1.5
[[module]]
id = "sensor_booster"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "circuit_board", amount = 1}]
production_time_seconds = 2
@@ -23,6 +24,7 @@ added_sensor_range_m = 100
[[module]]
id = "weapon_upgrade"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}, {item = "circuit_board", amount = 1}]
production_time_seconds = 4
@@ -34,6 +36,7 @@ multiplied_damage = 1.2
[[module]]
id = "laser_cannon"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}]
production_time_seconds = 5
@@ -47,6 +50,7 @@ attack_rate_hz = 2.0
[[module]]
id = "salvager"
unlock_at_station_level = -1
surface_mask = ["OO"]
materials = [{item = "iron_ingot", amount = 2}]
production_time_seconds = 5
@@ -60,6 +64,7 @@ collection_rate_hz = 0.5
[[module]]
id = "repair_tool"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "circuit_board", amount = 2}]
production_time_seconds = 5
@@ -73,6 +78,7 @@ repair_range_m = 800
[[module]]
id = "weapon_primer"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}]
production_time_seconds = 4
@@ -84,6 +90,7 @@ multiplied_attack_rate_hz = 1.2
[[module]]
id = "weapon_stabilizer"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}]
production_time_seconds = 4
@@ -96,6 +103,7 @@ multiplied_attack_rate_hz = 0.8
[[module]]
id = "afterburner"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}]
production_time_seconds = 2
@@ -108,6 +116,7 @@ added_main_acceleration_mpss = 60
[[module]]
id = "maneuvering_thrusters"
unlock_at_station_level = -1
surface_mask = ["O"]
materials = [{item = "iron_ingot", amount = 1}]
production_time_seconds = 2

View File

@@ -43,7 +43,7 @@ duration_seconds = 4.0
[[recipe]]
id = "premium_circuit"
building = "assembler"
unlocked_at_start = true
unlock_at_station_level = -1
inputs = [{item = "circuit_board", amount = 1}]
outputs = [{item = "premium_circuit", amount = 1}]
duration_seconds = 8.0
@@ -51,6 +51,7 @@ duration_seconds = 8.0
[[recipe]]
id = "quick_circuit"
building = "assembler"
unlock_at_station_level = 0
inputs = [{item = "copper_ingot", amount = 3}]
outputs = [{item = "circuit_board", amount = 1}]
duration_seconds = 3.0
@@ -58,6 +59,7 @@ duration_seconds = 3.0
[[recipe]]
id = "advanced_circuit"
building = "assembler"
unlock_at_station_level = 1
inputs = [{item = "iron_ingot", amount = 5}]
outputs = [{item = "circuit_board", amount = 1}]
duration_seconds = 6.0
@@ -65,6 +67,7 @@ duration_seconds = 6.0
[[recipe]]
id = "exotic_alloy"
building = "assembler"
unlock_at_station_level = 0
inputs = [{item = "exotic_ore", amount = 2}]
outputs = [{item = "exotic_alloy", amount = 1}]
duration_seconds = 10.0

View File

@@ -1,5 +1,6 @@
[[ship]]
id = "interceptor"
unlock_at_station_level = -1
layout = ["XOX", "OOO", "XOX"]
default_modules = [{type = "laser_cannon", x = 1, y = 1, rotation = "east"}]
@@ -23,6 +24,7 @@ sensor_range_m = 2000
[[ship]]
id = "destroyer"
unlock_at_station_level = -1
layout = ["XOOX", "OOOO", "XOOX"]
default_modules = [{type = "laser_cannon", x = 1, y = 1, rotation = "east"}]
@@ -46,6 +48,7 @@ sensor_range_m = 3000
[[ship]]
id = "salvage_ship"
unlock_at_station_level = -1
layout = ["OOO", "OOO"]
[ship.schematic]
@@ -68,6 +71,7 @@ sensor_range_m = 2500
[[ship]]
id = "repair_ship"
unlock_at_station_level = 0
layout = ["XOX", "OOO", "XOX"]
[ship.schematic]

View File

@@ -1,21 +0,0 @@
# Unlock groups for the test config (REQ-LOCK-EXPLICIT). Mirrors the previous
# per-item gating: repair_ship, quick_circuit, advanced_circuit start locked and
# are awarded via defence station drops. exotic_alloy is intentionally NOT here:
# it stays implicitly gated (its output/inputs are unreachable), so it is never
# unlocked. premium_circuit uses unlocked_at_start in recipes.toml. Everything
# else (interceptor, destroyer, salvage_ship, all modules) starts unlocked.
[[unlock]]
id = "repair_ship"
station_level = 0
ships = ["repair_ship"]
[[unlock]]
id = "quick_circuit"
station_level = 0
recipes = ["quick_circuit"]
[[unlock]]
id = "advanced_circuit"
station_level = 1
recipes = ["advanced_circuit"]

View File

@@ -1,7 +1,6 @@
[world]
height_tiles = 60
refund_percentage = 75
deconstruction_time_seconds = 0.1
starting_building_blocks = 100
scrap_despawn_seconds = 30
scrap_per_threat = 1.0
@@ -11,8 +10,6 @@ tunnel_max_distance_tiles = 10
departure_interval_seconds = 20
orbit_factor = 0.8
rally_orbit_radius_tiles = 5.0
building_blocks_tooltip = "Spend building blocks to build; deliver them to the HQ to gain more."
artifact_tooltip = "Choose the artifact reward when destroying enemy stations; collect enough to win."
[regions]
asteroid_width_tiles = 40
@@ -20,11 +17,6 @@ player_buffer_width_tiles = 10
contest_zone_width_tiles = 30
enemy_buffer_width_tiles = 15
[scroll]
pan_speed_slow_tiles_per_second = 8.0
pan_speed_fast_tiles_per_second = 24.0
pan_ramp_band_width_tiles = 16
[expansion]
columns_per_expansion_tiles = 10
cost_building_blocks_formula = "400 * 2^x"

View File

@@ -1,60 +0,0 @@
# simple check for a git repo
if(EXISTS "${CMAKE_SOURCE_DIR}/.git")
find_package(Git)
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(
COMMAND ${GIT_EXECUTABLE} log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(
COMMAND ${GIT_EXECUTABLE} log -1 --format=%ci
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_TIME
OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(
COMMAND ${GIT_EXECUTABLE} describe --long --match "[0-9]*" HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_VERSION_NUMBER
OUTPUT_STRIP_TRAILING_WHITESPACE
)
string(REGEX REPLACE "^([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_VERSION_NUMBER}")
string(REGEX REPLACE "^[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_VERSION_NUMBER}")
string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_VERSION_NUMBER}")
string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.[0-9]+-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_VERSION_NUMBER}")
else(EXISTS "${CMAKE_SOURCE_DIR}/.git")
set(GIT_BRANCH "")
set(GIT_COMMIT_HASH "")
set(GIT_VERSION_NUMBER "")
set(VERSION_MAJOR "0")
set(VERSION_MINOR "0")
set(VERSION_PATCH "0")
set(VERSION_COMMIT "0")
set(BUILD_TYPE "")
endif(EXISTS "${CMAKE_SOURCE_DIR}/.git")
set(VERSION_STRING "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")
message(STATUS "Version: ${VERSION_STRING}")
# message(STATUS "Git current branch: ${GIT_BRANCH}")
# message(STATUS "Git version number: " ${GIT_VERSION_NUMBER} )
# message(STATUS "Git commit hash: ${GIT_COMMIT_HASH}")
# message(STATUS "Git commit time: ${GIT_COMMIT_TIME}")
# message(STATUS "Version major: ${VERSION_MAJOR}")
# message(STATUS "Version minor: ${VERSION_MINOR}")
# message(STATUS "Version patch: ${VERSION_PATCH}")
# message(STATUS "Version commit: ${VERSION_COMMIT}")

View File

@@ -1,35 +0,0 @@
// Windows version resource. Generated by CMake via configure_file() from this
// template; @VAR@ placeholders are filled from cmake/version.cmake (version
// numbers) and the product identity variables in the top-level CMakeLists.txt.
// Shows up on the executable's Details tab (right-click -> Properties).
#include <windows.h>
VS_VERSION_INFO VERSIONINFO
FILEVERSION @VERSION_MAJOR@,@VERSION_MINOR@,@VERSION_PATCH@,@VERSION_COMMIT@
PRODUCTVERSION @VERSION_MAJOR@,@VERSION_MINOR@,@VERSION_PATCH@,@VERSION_COMMIT@
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS 0x0L
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0" // US English (0x0409), Unicode (0x04b0)
BEGIN
VALUE "CompanyName", "@PRODUCT_COMPANY@"
VALUE "FileDescription", "@PRODUCT_DISPLAY_NAME@"
VALUE "FileVersion", "@VERSION_STRING@"
VALUE "InternalName", "@PRODUCT_NAME@"
VALUE "OriginalFilename", "@PRODUCT_NAME@.exe"
VALUE "ProductName", "@PRODUCT_DISPLAY_NAME@"
VALUE "ProductVersion", "@VERSION_STRING@"
VALUE "LegalCopyright", "@PRODUCT_COPYRIGHT@"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200 // 0x409 = en-US, 1200 = Unicode code page
END
END

View File

@@ -15,7 +15,7 @@ This document captures the architectural decisions for the project. It is a comp
A strict separation between the game simulation and the Qt Widgets UI.
- The **simulation** is a pure C++ library that depends only on Qt Core and Qt Gui (QPoint, QVector2D, QRect, etc., as required by the coding guidelines), toml++, and tinyexpr. It contains no QtWidgets, no painting, and no QApplication. Note: in Qt 5, vector math types such as QVector2D live in Qt::Gui rather than Qt::Core, so the lib links both.
- The **UI** reads simulation state and renders it. It owns all widgets, painting, and input handling, and drives the simulation via a small command interface (place building, deconstruct, clear belt tiles, change recipe, set game speed, etc.).
- The **UI** reads simulation state and renders it. It owns all widgets, painting, and input handling, and drives the simulation via a small command interface (place building, demolish, clear belt tiles, change recipe, set game speed, etc.).
This split is enforced at the CMake target level (see below). Tests link only against the simulation library and run without a display server.
@@ -93,16 +93,10 @@ Schematic drops: when an enemy station set is destroyed, the simulation generate
### UI Events
All UI interactions — building selection, builder/blueprint mode transitions, speed changes, deconstruct mode, escape menu, layout dialog requests — are communicated via EventManager events rather than Qt signals/slots. Each event is a small struct inheriting `Event` (e.g., `SelectionChangedEvent`, `BuildingTypeSelectedEvent`, `SpeedChangeRequestedEvent`). Widgets register as `CombinedEventHandler` for the events they care about and emit events via `EventManager::sendEventImmediately()`.
All UI interactions — building selection, builder/blueprint mode transitions, speed changes, demolish mode, escape menu, layout dialog requests — are communicated via EventManager events rather than Qt signals/slots. Each event is a small struct inheriting `Event` (e.g., `SelectionChangedEvent`, `BuildingTypeSelectedEvent`, `SpeedChangeRequestedEvent`). Widgets register as `CombinedEventHandler` for the events they care about and emit events via `EventManager::sendEventImmediately()`.
Bidirectional interactions use separate request/notification event types to avoid infinite recursion (e.g., `ExitBuilderModeRequestedEvent` from `BuildButtonGrid``GameWorldView`, vs. `BuilderModeExitedEvent` from `GameWorldView``BuildButtonGrid`).
### Reading Simulation State
The simulation is the single source of truth for every game value (building block stock, expansion cost, threat level, tick, etc.). A UI widget that needs such a value holds the `Simulation*` it was constructed with and **pulls the value on demand** via the corresponding getter (e.g., `m_sim->getBuildingBlocksStock()`), rather than caching its own copy.
State-change events (e.g., `BuildingBlocksChangedEvent`) are treated as *refresh signals*, not as carriers of truth: a widget subscribes to the event to learn *when* the value changed and then re-reads it from the simulation to learn *what* it now is. The value carried in the event payload is not authoritative and should not be stored. This keeps a single copy of each value and avoids stale-cache bugs (a widget acting on a value that has since moved on because nothing refreshed its local copy).
## Tick Order
Within a single simulation tick, subsystems run in this fixed order. The order is load-bearing for determinism and for avoiding one-tick-delay artifacts (e.g., items landing on a belt but not advancing in the same tick).
@@ -325,7 +319,7 @@ Sim and UI run on the same thread for v1. `paintEvent` reads sim state directly
4. **Scrap** — glyphs at world positions.
5. **Ships** — colored arrows oriented by velocity; color keyed to role (player combat / salvage / repair / enemy).
6. **Laser beams** — lines derived from live `BeamFiredEvent`s kept by the renderer for 0.3 s, colored per `BeamKind` (weapon/repair/salvage) (REQ-SHP-FIRING-BEAM).
7. **Build overlays** — ghost in builder mode (REQ-BLD-GHOST), deconstruct-mode tint, tile highlight under cursor, box-drag selection rectangle.
7. **Build overlays** — ghost in builder mode (REQ-BLD-GHOST), demolish-mode tint, tile highlight under cursor, box-drag selection rectangle.
8. **Screen-space UI** — screen-anchored elements, drawn after resetting the world-space transform.
### Coordinates and Scrolling
@@ -372,7 +366,7 @@ width_px = 2
[overlays]
ghost_valid = "#ffffff44"
ghost_invalid = "#ff000044"
deconstruct_tint = "#ff000033"
demolish_tint = "#ff000033"
selection_rect = "#00ff00"
[toast]

View File

@@ -21,8 +21,12 @@ REQ-* ids in [../requirements.md](../requirements.md).
First full balancing round complete (2026-07-06): targets → tree →
numbers → threat-calculator parity → combat stats (arena-converged) →
pacing. Next step: full-game playtests against the run-shape targets in
`targets.md`.
pacing. Playtesting in progress: playtest 1 (two full ~40-min wins,
cruisers only) found the railgun_s-spam-cruiser meta, confirmed repair
as overpowered, and exposed a 2.53× run-length gap; combat stats
adjusted and re-checked in arena round 6 (see `history.md`). Next:
playtest 2 with the new stats — pacing knobs (station scaling, threat
rate, win pacing) wait for its result.
## Open action items

View File

@@ -94,10 +94,16 @@ geometry-validated against the hull grids)
## Combat stats
(arena-converged, 2026-07; see `history.md` rounds 15)
(arena-converged 2026-07, rounds 15; playtest-1 adjustments 2026-07-06 —
see `history.md`)
**Weapons:** railgun_s 2 dmg × 2.0 Hz (4.0 DPS), range 50 m;
railgun_m 14 × 1.5 (21), range 70; railgun_l 52 × 0.8 (41.6), range 100.
railgun_m 14 × 1.5 (21), range 80; railgun_l 52 × 0.8 (41.6), range 130.
DPS per threat: s 0.62, m 0.48, l 0.41 — the concentration tax stands;
reach is the bigger guns' compensation (ranges raised after playtest 1,
which alone priced out the small-gun-spam meta). railgun_l deliberately
outranges stations (120 m) to buy the siege role. railgun_m damage is
breakpoint-sensitive: 15+ drops a 60 HP drone from 5 hits to 4.
**Hull HP** (15/threat prior + empirical trims): drone 60, frigate 300,
destroyer 550, cruiser 1500, battlecruiser 2400, battleship 6300,
@@ -109,8 +115,9 @@ destroyer 30|35|18|6|3, cruiser 24|25|12|4|2, battlecruiser 20|20|10|3|1.5,
battleship 15|14|7|2|1, dreadnought/carrier 10|8|4|1|0.5.
Sensors: 150/200/220/250/260/280/300/350 m.
**Other modules:** armor_plates +1200 HP; repair_tool 9 HP × 1 Hz,
range 80; salvager range 60, cargo 20, 0.5 collections/s; afterburner
**Other modules:** armor_plates +1200 HP; repair_tool 4 HP × 1 Hz,
range 80 (halved after playtest 1 — free between-wave top-offs were never
priced by the arena escort test); salvager range 60, cargo 20, 0.5 collections/s; afterburner
×1.6 speed +60 accel; maneuvering_thrusters ×1.2 speed +10 maneuvering;
sensor_booster +50 m; weapon_upgrade ×1.2 damage; weapon_primer ×1.2
rate; weapon_stabilizer ×1.3 range ×0.8 rate.

View File

@@ -94,3 +94,68 @@ range 200).
— ~1 expansion per cycle mid-game, 23 cycles apart late.
- **First full balancing round complete.** Next: full-game playtests
against the run-shape targets.
## 2026-07-06 — playtest 1 (two full playthroughs)
Two complete runs, WON in ~40 min each with cruiser fleets only — never
needing capitals. (Initially misread as "two pushes in 40 min, pacing on
target"; corrected in round 6.) That is roughly cycle 8 against the
win-cycle target of 2024: a 2.53× pacing gap. Pacing knobs deliberately
untouched this round — the runs rode 9 HP/s repair and stations nothing
outranged, both nerfed below; playtest 2 measures the remaining gap.
- **Meta finding: cruisers filled with 12× railgun_s dominate.** Predicted
by the numbers in hindsight: the concentration tax makes railgun_s the
best DPS/threat (0.62 vs m 0.48, l 0.41), range is the big guns' only
mechanical edge (armor is added HP, not damage reduction — no anti-swarm
mechanic), repair sustain covers the closing distance, and stations
outranged every ship gun (120 vs railgun_l's 100), so even capitals had
to tank-and-brawl. The cruiser compounds it: first hull with a large
1×1 canvas (12 cells) and a nearly quartz-free chain.
- **Repair tool confirmed overpowered** (second signal after the
persistent +24% arena escort margin): the arena only prices in-fight
sustain; real runs add free full top-offs in every 1545 s wave gap
across the whole swarm. The 0.7 HP/s-per-threat prior is wrong for
wave defence.
- **Changes:** repair_tool 9→4 HP/s; railgun_l range 100→130 (now
outranges stations — buys the siege role the capital ladder promises);
railgun_m 14→16 dmg and range 70→80 (tax softened: m sits at 0.55
DPS/threat, between s and l). Module threats unchanged (costs
untouched), so no ladder recalculation needed.
- New tracked arena added: railgun_s-spam cruisers (8× 178) vs default
cruisers (6× 233.5) — the spam side should win a brawl somewhat, but a
blowout means the small-gun premium needs retuning.
- **Open:** re-run the arena suite to check the range/damage changes
against the round 15 results; next playtest should verify big guns now
feel worth climbing to and repair is merely good.
## 2026-07-06 — arena round 6 (checking the playtest-1 adjustments)
Mirrors healthy (58% margins, durations 24/66/91 s). Results:
- **Spam-cruiser arena: default cruisers +9% — the meta is priced out**,
and the range buff alone did the work.
- **Regression: drone swarm vs cruisers +47% for cruisers** (was +14%
swarm in round 3). Besides the wider range gap, the damage buff crossed
a breakpoint: 14 dmg kills a 60 HP drone in 5 hits, 16 in 4 — a hidden
~25% effective-DPS gain vs drones. Change: **railgun_m damage 16→14**
(range stays 80); the tax stands, reach is the compensation.
- Battleship +30% and dreadnought +29% vs pure railgun_s fleets:
**accepted as reach-doctrine texture** (BS was already accepted at
+23%) — the l gun's 130 m standoff is exactly what the range buff
bought; the counter is your own reach or 2:1 numbers, not equal-threat
small guns. Watch, don't tune.
- Repair escort flipped to raw +16%: **kept at 4 HP/s deliberately**
the arena cannot price the free between-wave top-offs, so slightly
below par in-fight is the correct price for a module whose run-value
includes them. Playtest 2 decides; 6 is the fallback if repair feels
dead.
- Station assault: the 3× swarm cracked the fortified position keeping
45% EHP. No knob this round touched it; together with playtest 1's
trivially easy pushes it flags **station strength as the first pacing
lever** for the next pass.
**Pacing deferred:** playtest 1's 40-min wins predate the repair nerf
and the l-gun siege range. If playtest 2 still wins by ~cycle 10, the
levers are enemy station scaling (`3000 + 1500*x` likely too shallow),
the threat rate, and possibly `artifact_win_count`.

View File

@@ -55,7 +55,7 @@ data, not the UI gesture. Example: placing a miner records
One command per sim-mutating operation (the complete mutation surface):
- `PlaceBuilding`
- `Deconstruct`
- `Demolish`
- `RotateInPlace`
- `SetRecipe`
- `SetShipLayout`
@@ -125,7 +125,7 @@ the only way production code can reach them is `apply(command)`.
> `BeltSystem` directly, and every production `buildings()`/`belts()` call is a const query.
> So:
>
> - `Simulation::tryPlaceBuilding`, `deconstruct`, and `applySchematicChoice` are **private**.
> - `Simulation::tryPlaceBuilding`, `demolish`, and `applySchematicChoice` are **private**.
> - The mutable subsystem accessors are private and renamed `buildingsMutable()` /
> `beltsMutable()`; only `const BuildingSystem& buildings() const` / `belts() const` are
> public (queries). UI query sites bind to the const overload unchanged.
@@ -377,7 +377,7 @@ The whole feature rests on a deterministic sim, so prove that before building on
Reshape mutations to flow through one path; behaviour unchanged.
- Defined `Command` base + derived types (`PlaceBuilding`, `Deconstruct`, `RotateInPlace`,
- Defined `Command` base + derived types (`PlaceBuilding`, `Demolish`, `RotateInPlace`,
`SetRecipe`, `SetShipLayout`, `SetSiteSplitterFilters`, `SetSplitterFilters`,
`ClearBeltTiles`, `ApplySchematicChoice`, `Reset`) in `lib`, each with a `playerId` (always 0
now). `PlaceBuilding` is atomic (carries optional config — see the refinement note above).

View File

@@ -4,14 +4,13 @@
Config files use the TOML format. The following config files drive game parameters:
- **world.toml** — world dimensions, region widths, expansion amounts, building refund percentage, building deconstruction time, wave timing, boss wave timing, belt speed, starting building blocks, departure interval, ship orbit factor, rally orbit radius, scrap-per-threat conversion, combat target-selection parameters (target score formula, overclaim penalty formula, target hysteresis), artifact chance formula, artifact win count, view pan speeds (slow and fast horizontal pan speed and pan ramp band width), an optional building blocks tooltip string (shown as the header bar's building blocks stock hover tooltip, REQ-UI-BLOCKS-TOOLTIP; omitted when unset), and an optional artifact tooltip string (shown as the header bar's artifact count hover tooltip, REQ-UI-ARTIFACTS-TOOLTIP; omitted when unset).
- **buildings.toml** — building block cost and construction time per building type, plus an optional tooltip description string per building type (shown as the build button's hover tooltip, REQ-UI-BUILD-TOOLTIP; omitted when unset). Whether a building type is available from game start or must be unlocked during play is not defined here but in **unlocks.toml** (REQ-LOCK-EXPLICIT): a building type granted by an unlock group starts locked and is hidden from the build menu until its group is awarded (REQ-LOCK-BUILDING).
- **recipes.toml** — crafting recipes: inputs, outputs, quantities, durations, and reprocessing plant probabilities. Assembler recipe entries may optionally define `unlocked_at_start` (boolean, default false): when true the recipe is available from game start regardless of the implicit item graph — used for base recipes that no schematic's materials reach (such as building blocks; see REQ-LOCK-IMPLICIT). Which assembler recipes must instead be awarded during play (explicitly gated) is defined in **unlocks.toml**, not here (REQ-LOCK-EXPLICIT); every remaining assembler recipe is implicitly unlocked through the item graph (REQ-LOCK-IMPLICIT).
- **ships.toml** — per schematic: a human-readable display name (used in the UI), hull stats (HP, max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, max rotation speed) as plain values, required build materials, a layout grid defining the ship's module slots, and a `default_modules` list used for enemy wave ships (see REQ-WAV-DEFAULT-MODULES). Whether a ship schematic is available from game start or must be unlocked during play is defined in **unlocks.toml** (REQ-LOCK-EXPLICIT), not here.
- **modules.toml** — per module type: id, surface mask, materials list, production time, fill color, glyph, an optional tooltip description string (shown as the module selection button's hover tooltip, REQ-MOD-UI-MODULE-TOOLTIP; omitted when unset), and an optional capability section and/or stat modifier formulas. Whether a module schematic is available from game start or must be unlocked during play is defined in **unlocks.toml** (REQ-LOCK-EXPLICIT), not here. A module with a capability section (`[module.weapon]`, `[module.salvage]`, or `[module.repair]`) containing base stat formulas is a **capability module** that grants the ship a weapon, salvage bay, or repair tool per instance (see REQ-MOD-CONFIG for the full list of formulas per capability type). A module with only `added_*`/`multiplied_*` formulas is a **passive module** that modifies stats on the ship or on capability module instances (see REQ-MOD-STAT-CALC).
- **unlocks.toml** — unlock groups: each `[[unlock]]` entry names a group of ship schematics, module schematics, building types, and/or assembler recipes that are awarded together from a single defence station drop (see Unlock Group Format, REQ-LOCK-EXPLICIT, REQ-DEF-SCHEMATIC-DROP). Anything not granted by any unlock group is available from game start.
- **world.toml** — world dimensions, region widths, expansion amounts, building refund percentage, wave timing, boss wave timing, belt speed, starting building blocks, departure interval, ship orbit factor, rally orbit radius, scrap-per-threat conversion, combat target-selection parameters (target score formula, overclaim penalty formula, target hysteresis), artifact chance formula, and artifact win count.
- **buildings.toml** — building block cost and construction time per building type.
- **recipes.toml** — crafting recipes: inputs, outputs, quantities, durations, and reprocessing plant probabilities. Assembler recipe entries may optionally define `unlock_at_station_level` (integer): -1 means the recipe is explicitly unlocked at game start; a value ≥ 0 means the recipe starts locked and a schematic for it can be awarded via defence station destruction (see REQ-LOCK-EXPLICIT, REQ-DEF-SCHEMATIC-DROP). An assembler recipe schematic entry may also define an optional `unlock_requires` list of prerequisite schematic ids (REQ-LOCK-PREREQ).
- **ships.toml** — per schematic: a human-readable display name (used in the UI), hull stats (HP, max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, max rotation speed) as plain values, required build materials, the station level at which the schematic becomes available for unlock (`unlock_at_station_level`; -1 means the player starts with the schematic already unlocked), an optional `unlock_requires` prerequisite list (REQ-LOCK-PREREQ), a layout grid defining the ship's module slots, and a `default_modules` list used for enemy wave ships (see REQ-WAV-DEFAULT-MODULES).
- **modules.toml** — per module type: id, surface mask, materials list, production time, fill color, glyph, the station level at which the schematic becomes available for unlock (`unlock_at_station_level`; -1 means the player starts with the module schematic already unlocked), an optional `unlock_requires` prerequisite list (REQ-LOCK-PREREQ), and an optional capability section and/or stat modifier formulas. A module with a capability section (`[module.weapon]`, `[module.salvage]`, or `[module.repair]`) containing base stat formulas is a **capability module** that grants the ship a weapon, salvage bay, or repair tool per instance (see REQ-MOD-CONFIG for the full list of formulas per capability type). A module with only `added_*`/`multiplied_*` formulas is a **passive module** that modifies stats on the ship or on capability module instances (see REQ-MOD-STAT-CALC).
- **stations.toml** — HP, damage, range, fire rate, and scrap drop for player and enemy defence stations, defined as formulas of station level.
- **visuals.toml** — rendering-only config (not game parameters): fill and outline colors and glyphs for every building type, item type, ship schematic, and station type; a distinct beam color per tool type (weapon, repair, salvage) and beam width; overlay and toast colors; and building status light colors (grey, green, red, and yellow fills plus the outline color, REQ-UI-STATUS-LIGHT). Loaded by the UI at startup; the simulation does not read it.
- **visuals.toml** — rendering-only config (not game parameters): fill and outline colors and glyphs for every building type, item type, ship schematic, and station type; a distinct beam color per tool type (weapon, repair, salvage) and beam width; overlay and toast colors. Loaded by the UI at startup; the simulation does not read it.
- **ship_layouts.toml** — named layout blueprints per ship type; written and read by the application to persist the layout blueprint panel (REQ-MOD-UI-BLUEPRINT-PANEL through REQ-MOD-UI-BLUEPRINT-FILE-LOAD). Not a game parameter file; the simulation does not read it.
- REQ-CFG-RELOAD: When the player triggers a Restart (REQ-UI-GAME-MENU), all config files are reloaded from disk before the simulation is reset to its initial state. Formula strings are recompiled at that point. This allows config edits made while the application is running to take effect without a full application restart.
@@ -66,32 +65,10 @@ Modules in `modules.toml` define a `surface_mask` — a list of strings that des
- `O` — module cell: must be placed on an unoccupied buildable cell (`O`) of the ship's layout.
- `X` — ignored cell: may overlap any cell (non-buildable, unoccupied buildable, or occupied buildable) or extend outside the layout grid entirely.
### Unlock Group Format
Unlock groups in `unlocks.toml` define what the player can be awarded from defence station drops (REQ-DEF-SCHEMATIC-DROP); by their absence they also define what is available from game start (REQ-LOCK-EXPLICIT). Each entry:
```toml
[[unlock]]
id = "salvage_operations" # unique unlock-group id
station_level = 2 # eligible once a destroyed station set's level >= this
requires = [] # prerequisite unlock-group ids (REQ-LOCK-PREREQ); default empty
ships = [] # ship schematic ids granted (from ships.toml)
modules = ["salvager"] # module schematic ids granted (from modules.toml)
buildings = ["salvage_bay"] # building type ids granted (from buildings.toml)
recipes = [] # assembler recipe ids granted (from recipes.toml)
```
- `id` — unique identifier of the unlock group; referenced by other groups' `requires`. Its display name in the schematic choice dialog is derived from the id (same convention as building, module, and recipe ids); there is no separate name field for now.
- `station_level` — the minimum destroyed enemy defence station level at which this group becomes eligible to drop (REQ-DEF-SCHEMATIC-DROP).
- `requires` — optional list of prerequisite unlock-group ids that must already have been awarded before this group can drop (REQ-LOCK-PREREQ). Defaults to empty.
- `ships`, `modules`, `buildings`, `recipes` — the ids granted when this group is awarded. Each list defaults to empty, but a group must grant at least one item overall. Every id must resolve to a definition in the corresponding config file, and `recipes` ids must name **assembler** recipes. Each grantable id (ship, module, building, or assembler recipe) may be granted by **at most one** unlock group; violations fail config load (REQ-LOCK-EXPLICIT).
Any ship, module, building, or assembler recipe id that appears in no unlock group's grant lists is available from game start (REQ-LOCK-EXPLICIT).
## Game World
- REQ-GW-COORDS: Tile coordinates are integer `(x, y)`. The origin `(0, 0)` is the first column of space — the tile immediately to the right of the asteroid's right edge at game start, at the top of the world. X grows right; Y grows down. All asteroid tiles have `x < 0`; asteroid left-expansions add tiles at increasingly negative X. The origin never shifts.
- REQ-GW-TILE-SIZE: Tiles are square. The tile size in pixels is derived automatically so that the world height (in tiles) exactly fills the game world view's height in pixels. Items on belts are rendered at half-tile size; when multiple items occupy the same tile they are spaced quarter-tile apart along the direction of travel and overlap, rendered in ascending order of progress — the least-progressed item is drawn first (bottom) and the furthest-progressed item is drawn last (on top). Items emerging from a building's output port are rendered by these same rules on that port's output belt (REQ-MAT-OUTPUT-EMERGE).
- REQ-GW-TILE-SIZE: Tiles are square. The tile size in pixels is derived automatically so that the world height (in tiles) exactly fills the game world view's height in pixels. Items on belts are rendered at half-tile size; when multiple items occupy the same tile they are spaced quarter-tile apart along the direction of travel and overlap, rendered in ascending order of progress — the least-progressed item is drawn first (bottom) and the furthest-progressed item is drawn last (on top).
- REQ-GW-BELT-CAPACITY: Belt tiles and tunnel entry/exit tiles each hold up to four items simultaneously, queued one behind the other in the direction of travel. Splitter tiles hold up to four items: two unassigned items (progress < 0.5, not yet routed to an output) and one item per output slot (progress ≥ 0.5, committed to a specific output direction). Output-slot items are rendered on top of unassigned items; when both output slots are occupied, their rendering order follows the clockwise port order starting from East.
- REQ-GW-BELT-SPEED: Items on belts move at `world.toml [world].belt_speed_tiles_per_second` tiles per second (default 2).
- REQ-GW-HEIGHT: The world height (in tiles) is read from `world.toml [world].height_tiles`.
@@ -123,36 +100,16 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-BLD-COST: The player places buildings from a build menu. Placement costs building blocks from the global stock. The cost per building type is read from `buildings.toml [[building]].cost`.
- REQ-BLD-QUEUE: Placed buildings enter a construction queue and are built one at a time. Each building takes a duration defined in `buildings.toml [[building]].construction_time_seconds` to construct.
- REQ-BLD-ASTEROID-ONLY: Buildings can only be placed on asteroid tiles (per surface_mask; tiles marked `S` may extend into space).
- REQ-BLD-BUILDER-MODE: Clicking a build button activates builder mode for that building type. Builder mode is exited by right-clicking in the game world or clicking the same build button again. (Exception: while a belt drag placement is in progress, right-clicking cancels that drag instead of exiting, and builder mode stays active — REQ-BLD-BELT-DRAG.)
- REQ-BLD-BUILDER-MODE: Clicking a build button activates builder mode for that building type. Builder mode is exited by right-clicking in the game world or clicking the same build button again.
- REQ-BLD-GHOST: While in builder mode, a ghost of the building is rendered at the tile under the cursor, showing where it would be placed. The ghost is drawn semi-transparently in the building type's own visuals — its `fill` and `outline` colors and `glyph` from `visuals.toml` — so that different building types are visually distinguishable in builder mode rather than all looking alike. When the current cursor position is invalid, the ghost instead uses the distinct "invalid" color (REQ-BLD-PLACE-VALID), which overrides the per-building coloring.
- REQ-BLD-ROTATE: While in builder mode, pressing Shift+R rotates the ghost 90° clockwise and R rotates it 90° counter-clockwise. Rotation affects the direction of the output port.
- REQ-BLD-PLACE: Clicking a valid tile in builder mode places a construction site and adds it to the build queue, consuming building blocks from the global stock. (For belts, placement is instead deferred to a drag gesture and happens on mouse release — REQ-BLD-BELT-DRAG.)
- REQ-BLD-PLACE: Clicking a valid tile in builder mode places a construction site and adds it to the build queue, consuming building blocks from the global stock.
- REQ-BLD-PLACE-VALID: A placement position is valid only if (a) every footprint cell in the rotated `surface_mask` is satisfied by the underlying terrain — `A` cells coincide with asteroid tiles, `S` cells coincide with space tiles — (b) no footprint cell overlaps an existing placed building or construction site, except as allowed by REQ-BLD-ROTATE-IN-PLACE, and (c) the player has enough building blocks to afford the building. The ghost (REQ-BLD-GHOST) is rendered in a distinct "invalid" color — overriding its per-building coloring (REQ-BLD-GHOST) — when the current cursor position fails any of these conditions.
- REQ-BLD-ROTATE-IN-PLACE: If the ghost's footprint exactly coincides with the footprint of an existing placed building or construction site of the same building type, clicking places no new construction site and consumes no building blocks. Instead, the existing building or site is rotated to match the ghost's rotation. If the target is a construction site, its construction progress is preserved. **Exception:** Tunnel Entries and Tunnel Exits are never rotated in place — re-orienting a tunnel requires deconstructing and re-placing it (REQ-BLD-TUNNEL-MODE). A tunnel ghost whose footprint coincides with an existing tunnel is therefore treated as an ordinary occupied-tile placement (invalid in normal builder mode; skipped in blueprint placement mode). This applies in both normal builder mode and blueprint placement mode; in blueprint placement mode it is evaluated per building in the blueprint independently — buildings in the blueprint whose footprint coincides with an existing same-type building or site are rotated in place, while the remaining buildings in the blueprint are placed as normal construction sites (subject to the usual validity checks and total cost).
- REQ-BLD-BELT-DRAG: **Belt drag placement.** For belts, placement is a deferred drag gesture rather than immediate per-tile placement: construction sites are not placed while the cursor hovers new tiles, but only once the player releases the left mouse button. Pressing the left mouse button in the game world while in belt builder mode starts a drag anchored at the tile under the cursor. As the cursor moves, a **rectilinear (L-shaped) path** of belt tiles is computed from the anchor tile to the tile under the cursor: the path first runs along the axis **parallel to the belt's current orientation** (REQ-BLD-ROTATE) — stepping toward the cursor's coordinate on that axis to a corner tile — and then runs along the orthogonal axis to the cursor tile. When the cursor shares the anchor's row or column the path degenerates to a straight line, and when it is on the anchor tile the path is a single tile.
- **Snapping to a building.** When the tile under the cursor is occupied by a non-belt building or construction site (the **target**), the path does not end on that occupied tile. Instead the end tile is the tile **closest to the cursor** (by distance from the cursor position to the tile) among the tiles orthogonally adjacent to the target across one of its **input-capable edges** — any footprint edge that is not one of the target's output ports, i.e. an edge on which the target can accept an incoming item (REQ-MAT-INPUT-PORTS for buildings, REQ-MAT-ACCEPT-DIR for splitters and tunnels). The geometrically closest such tile is **always** used, even if it turns out not to be a valid belt endpoint — in that case it is previewed and applied by the ordinary rules below (invalid color and skipped if occupied by a non-belt building or invalid terrain; re-oriented if it already holds a belt). The rest of the L-shaped path is computed from the anchor to this end tile exactly as above. The end tile's belt direction points **toward the target** (across the shared input edge), overriding the "final tile keeps its incoming step" rule; this applies whether the end tile is a newly placed belt or an existing belt re-oriented in place, and is reflected both in the ghost preview and in the placement on release.
- **Rotating during the drag.** Rotating the belt with R / Shift+R (REQ-BLD-ROTATE) while a drag is in progress re-picks the path's primary axis immediately from the new orientation and re-derives the whole path from the anchor to the current cursor tile, without waiting for the next cursor movement.
- **Ghosts.** While dragging, a belt ghost (REQ-BLD-GHOST) is rendered on every path tile that would be acted on, instead of a single ghost under the cursor. Each ghost is oriented to point toward the next tile along the path toward the cursor, so the path forms one connected belt run that turns at the corner (curved belts along the path auto-derive per REQ-BLD-BELT); the final tile keeps the direction of its incoming step (unless the end tile is snapped to a building, in which case it points into the target — see **Snapping to a building**), and a single-tile path keeps the belt's current orientation. A tile occupied by only an existing belt or belt construction site is a valid target — its belt is re-oriented to follow the path — and shows a normal belt ghost. A tile occupied by a non-belt building or construction site, or otherwise an invalid belt position (REQ-BLD-PLACE-VALID), is drawn in the distinct invalid color, overriding the belt coloring. A tile whose new belt is unaffordable — the cumulative cost of the belts newly placed up to and including it exceeds the global stock — shows **no ghost at all**.
- **Placement on release.** No construction site is placed while dragging. On releasing the left mouse button, the path is applied in order (anchor to cursor): each cell occupied by only an existing belt or belt construction site has that belt re-oriented in place to its path direction, consuming no building blocks and preserving any construction progress (REQ-BLD-ROTATE-IN-PLACE); each empty, valid cell gets a new belt construction site, consuming building blocks from the global stock (REQ-BLD-COST). Cells occupied by a non-belt building or construction site, cells that are otherwise invalid (REQ-BLD-PLACE-VALID), and cells whose new belt can no longer be afforded once the running total has been spent are skipped. This supersedes the click-to-place of REQ-BLD-PLACE for belts, including both the single-tile case and multi-tile drags that pass over existing belts.
- **Right-click cancels the drag.** Right-clicking while a belt drag is in progress cancels it: the path is discarded, no construction site is placed, and belt builder mode stays active (the exception to REQ-BLD-BUILDER-MODE). Right-clicking when no drag is in progress exits builder mode as usual (REQ-BLD-BUILDER-MODE).
- REQ-BLD-TUNNEL-MODE: **Unified tunnel build mode.** The build button grid contains a single **Tunnel** button rather than separate Tunnel Entry and Tunnel Exit buttons (REQ-UI-BUILD-GRID), activated by that button or by hotkey 3 (REQ-UI-HOTKEYS). This one builder mode places either a Tunnel Entry or a Tunnel Exit construction site depending on the hovered position, so the player never manually chooses between the two ends. Both remain distinct building types (REQ-BLD-TUNNEL-ENTRY, REQ-BLD-TUNNEL-EXIT) with their own costs and construction; only their build-menu entry point is unified.
- **Default type.** The ghost (REQ-BLD-GHOST) is a **Tunnel Entry** by default; clicking places a Tunnel Entry construction site (REQ-BLD-PLACE). Rotation (REQ-BLD-ROTATE) sets the ghost's facing direction as for any building.
- **Exit-completion match.** While the ghost is at a valid position, the game tests whether placing a **Tunnel Exit** at the hovered tile with the current ghost rotation would pair — per the pairing rules of REQ-BLD-TUNNEL-PAIR (same facing direction, within `tunnel_max_distance`, first same-direction building along the search, nearest-claim semantics) — with an existing Tunnel Entry. If so, that Entry is the **exit-completion match** and the ghost turns into a **Tunnel Exit**; clicking then places a Tunnel Exit construction site.
- **Entry-completion match.** The game also tests whether placing a **Tunnel Entry** at the hovered tile with the current ghost rotation would pair — again per REQ-BLD-TUNNEL-PAIR — with an existing Tunnel Exit. If so, that Exit is the **entry-completion match** and the ghost stays a Tunnel Entry.
- **Resolving the type.** If neither match exists, the ghost is a Tunnel Entry (the default). If only one kind of match exists, the ghost is the kind that produces it (Tunnel Exit for an exit-completion match, Tunnel Entry for an entry-completion match). If **both** an exit-completion match (an existing Entry) and an entry-completion match (an existing Exit) exist, the mode resolves to the completion whose **existing partner building is closer to the mouse cursor position** — the actual sub-tile cursor position, not the hovered tile's center — and the ghost becomes the corresponding type (a Tunnel Exit to complete the nearer Entry, or a Tunnel Entry to complete the nearer Exit). Because the comparison uses the sub-tile cursor position, when the two partners are at the same tile distance the player can move the cursor within the hovered tile to switch which end is placed. When more than one candidate qualifies on a side, the nearest qualifying partner on that side is used.
- **Connection preview (green).** Whenever a completion match is resolved, the matched existing partner building is highlighted green, and every tile strictly between that partner and the hovered ghost tile (along the tunnel's straight run) is marked green, previewing the connection that placing the ghost would create.
- **Invalid positions.** The completion tests, type switch, and green preview apply only while the hovered position is a valid placement (REQ-BLD-PLACE-VALID). At an invalid position the ordinary invalid-colored ghost is shown (REQ-BLD-GHOST) with no green preview and no switch away from the default Tunnel Entry.
- REQ-BLD-DECONSTRUCT: The player can deconstruct a placed factory building. Deconstructing a **fully-built** factory building does not remove it instantly: it is added to the deconstruction queue (REQ-BLD-DECON-QUEUE) and, once its deconstruction completes, `world.toml [world].refund_percentage` percent of the original building block cost (default 75%) is returned to the global stock. Exception: if the building is still in the construction queue (not yet fully built, including the one currently being constructed), it is **not** queued for deconstruction but removed instantly from the construction queue, and the **full** building block cost is refunded immediately. The HQ and player defence stations cannot be deconstructed.
- REQ-BLD-DECON-QUEUE: Fully-built factory buildings marked for demolition (REQ-BLD-DECONSTRUCT) enter a **deconstruction queue** that is processed one building at a time and runs in parallel with the construction queue (REQ-BLD-QUEUE) — the two queues advance independently and simultaneously. Each building takes `world.toml [world].deconstruction_time_seconds` (default 0.1) to deconstruct, the same duration for every building type. When a building's deconstruction completes it is removed from the world and its refund is credited (REQ-BLD-DECONSTRUCT). A building **stops operating the moment it enters the queue**: it runs no production and transports no items, and no longer participates as a live building (its tunnel pairing is re-evaluated as if it were gone, REQ-BLD-TUNNEL-PAIR), but it still physically occupies its tiles until removed, so those tiles stay blocked for placement. A queued building can be taken back out of the deconstruction queue before it is removed (REQ-BLD-DECONSTRUCT-CLICK, REQ-BLD-DECONSTRUCT-BOX) — including the one currently being deconstructed; doing so discards any deconstruction progress, credits no refund, and the building resumes operating (and re-pairs, REQ-BLD-TUNNEL-PAIR). Construction sites never enter the deconstruction queue (REQ-BLD-DECONSTRUCT). Every building in the deconstruction queue is rendered with the deconstruct tint — the `visuals.toml [overlays].deconstruct_tint` color, the same tint applied to a building hovered in deconstruct mode (REQ-UI-DECONSTRUCT-BORDER) — so queued buildings are visually distinct.
- REQ-BLD-DECONSTRUCT-CLICK: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), left-clicking a placed factory building or construction site in the game world marks it for demolition, following the rules of REQ-BLD-DECONSTRUCT: a fully-built building is added to the deconstruction queue (REQ-BLD-DECON-QUEUE), and a construction site is removed instantly with the full refund. Left-clicking a fully-built building that is **already in the deconstruction queue** instead removes it from the queue (un-queues it, REQ-BLD-DECON-QUEUE), with no refund; repeated clicks on the same building therefore alternate between queueing and un-queueing it. Clicking a building that cannot be deconstructed (the HQ or a player defence station, per REQ-BLD-DECONSTRUCT), or clicking empty world space, has no effect. Deconstruct mode stays active after each action so the player can continue without re-entering the mode; it is exited via the Q toggle (REQ-UI-HOTKEYS) or the Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON).
- REQ-BLD-DECONSTRUCT-BOX: While in deconstruct mode (REQ-UI-HOTKEYS, REQ-UI-DECONSTRUCT-BUTTON), the player can click and drag a selection box in the game world. A selection rectangle is drawn while dragging, using the same box-drag gesture and coverage semantics as the multi-select box (REQ-UI-MULTI-SELECT). On mouse up, following the rules of REQ-BLD-DECONSTRUCT: every construction site covered by the box is removed instantly with the full refund; and among the fully-built deconstructible buildings covered by the box, if **all** of them are already in the deconstruction queue they are all removed from it (un-queued, REQ-BLD-DECON-QUEUE), otherwise every covered building not yet in the queue is added to the deconstruction queue (already-queued ones stay). Buildings that cannot be deconstructed (the HQ and player defence stations, per REQ-BLD-DECONSTRUCT) are excluded from the box demolition; ships and defence stations are never affected.
- REQ-BLD-ROTATE-IN-PLACE: If the ghost's footprint exactly coincides with the footprint of an existing placed building or construction site of the same building type, clicking places no new construction site and consumes no building blocks. Instead, the existing building or site is rotated to match the ghost's rotation. If the target is a construction site, its construction progress is preserved. This applies in both normal builder mode and blueprint placement mode; in blueprint placement mode it is evaluated per building in the blueprint independently — buildings in the blueprint whose footprint coincides with an existing same-type building or site are rotated in place, while the remaining buildings in the blueprint are placed as normal construction sites (subject to the usual validity checks and total cost).
- REQ-BLD-BELT-DRAG: For belts, the player can click and drag across multiple tiles to place a construction site on each tile in one gesture.
- REQ-BLD-TUNNEL-AUTO-SWITCH: After the player successfully places a Tunnel Entry construction site, builder mode automatically switches to Tunnel Exit (and vice versa), preserving the current ghost rotation. This makes it easy to immediately place the paired end without manually selecting the complementary type.
- REQ-BLD-DEMOLISH: The player can demolish a placed factory building. Demolition returns `world.toml [world].refund_percentage` percent of the original building block cost (default 75%) to the global stock. Exception: if the building is still in the construction queue (not yet fully built, including the one currently being constructed), it is removed from the queue and the **full** building block cost is refunded. The HQ and player defence stations cannot be demolished.
- REQ-BLD-SITE-CONFIG: A construction site — a building that has been placed but is still queued or under construction (REQ-BLD-QUEUE) — can be selected and configured exactly like the equivalent operational building, before it finishes building. Whatever configuration the building type supports is available on the site: the recipe for a Miner or Assembler (REQ-UI-SELECT-BUTTON), the produced-ship schematic and its module layout for a Shipyard (REQ-UI-SELECT-BUTTON, REQ-MOD-UI-PREVIEW, REQ-MOD-UI-DIALOG), and the output filters for a Splitter (REQ-BLD-SPLITTER) — all set through the same Selected Building Panel controls (REQ-UI-CONFIG-INLINE). Only currently unlocked recipes and schematics are offered, exactly as for operational buildings (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SCHEMATIC, REQ-LOCK-UI-SPLITTER). The configuration is stored on the construction site and carries over unchanged when construction completes, so the building becomes operational already configured. A construction site has no input/output buffers and runs no production cycle, so the buffer and production-progress portions of the panel (REQ-UI-SINGLE-SELECTION, REQ-UI-PRODUCTION-PROGRESS) are not shown for it; only its construction progress (REQ-UI-CONSTRUCTION-PROGRESS) and its configuration controls appear. (Blueprint placement already applies a stored recipe or schematic to a construction site on placement per REQ-UI-BLUEPRINT-PLACE; this requirement additionally lets the player set or change that configuration directly on an existing site.)
- REQ-BLD-COPY-CONFIG: **Copy building settings (hold Shift).** While the Shift key is held, the player can copy one building's settings onto other buildings of the same type, so several identical machines can be set up without opening each one's panel. This gesture is available only in the default selection mode; while a builder, blueprint placement, or deconstruct mode is active it is disabled, so it never clashes with placement or demolition clicks.
- **Shift + right-click** a building copies its current settings into a temporary cache, along with the building's type. The settings copied are whatever that building type supports: the selected recipe (Miner, Assembler), the selected schematic together with its module layout (Shipyard), or the two output filters (Splitter, REQ-BLD-SPLITTER). Copying succeeds only when there is something to copy — a Miner or Assembler with a recipe selected, a Shipyard with a schematic selected, or any Splitter (whose output filters, even when empty/accept-all, always constitute valid settings). Shift + right-clicking a configurable building with nothing yet selected, a building type that has no settings at all (Smelter, Reprocessing Plant, Salvage Bay, belt/tunnel tiles, the HQ), or empty world space, has no effect and leaves any existing cache unchanged.
- **Shift + left-click** a building of the **same type** as the cached one applies the cached settings to it, exactly as if the player had made that selection through the selected building panel — with the same effects as a normal selection change (buffer clearing per REQ-MAT-INPUT-BUFFER and REQ-MAT-OUTPUT-BUFFER, and, for a Shipyard, in-progress cycle cancellation per REQ-BLD-SHIPYARD). This can be repeated on any number of same-type buildings while Shift stays held. Shift + left-clicking a building of a different type than the cached one, any building while the cache is empty, or empty world space, has no effect.
- Both operational buildings and construction sites take part as source and target (REQ-BLD-SITE-CONFIG); settings applied to a construction site carry over unchanged when it finishes building.
- **Releasing Shift clears the temporary cache.** It is never persisted and does not survive Shift being released; the next copy starts fresh.
- Because the cached settings were already valid on a same-type source building, they remain valid and available on the target (a selected recipe/schematic stays unlocked per REQ-LOCK-UI-RECIPE and REQ-LOCK-UI-SCHEMATIC; splitter filter item types stay unlocked per REQ-LOCK-UI-SPLITTER).
## Building Types
@@ -161,48 +118,29 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-BLD-ASSEMBLER: **Assembler** (3×3): The player selects a recipe from the config-defined crafting tree. Produces the selected output item at the rate defined in the corresponding `recipes.toml [[recipe]]` entry with `building = "assembler"`. Only implicitly unlocked recipes are available for selection (REQ-LOCK-UI-RECIPE).
- REQ-BLD-REPROCESSING: **Reprocessing Plant** (3×3): Consumes scrap per cycle and produces exactly one higher-level intermediate product per cycle via weighted random pick. The input quantity, possible output items, per-output weights, and amounts are defined in `recipes.toml [[recipe]]` entries with `building = "reprocessing_plant"` (`inputs`, `outputs[].item`, `outputs[].amount`, `outputs[].weight`). Weights are normalized at load time; their sum does not need to equal 1. The output is rolled at cycle start (see REQ-MAT-CYCLE); the pool of eligible outputs is restricted to implicitly unlocked item types (REQ-LOCK-REPROCESSING-POOL). The output buffer holds at most one cycle's output — see REQ-MAT-OUTPUT-BUFFER-REPROCESSING.
- REQ-BLD-SHIPYARD: **Shipyard** (4×2): The player selects a schematic. When all required materials — the ship's base materials (`[ship.schematic].materials`) plus the materials of all modules in the configured layout (REQ-MOD-MATERIALS) — are present in its input buffer, the shipyard consumes them and begins a production cycle lasting the ship's base `[ship.schematic].production_time_seconds` plus the sum of production times contributed by all module instances in the configured layout (REQ-MOD-PRODUCTION-TIME). One ship of that type is spawned with the configured modules when the cycle completes. The shipyard cannot start a new cycle while one is in progress. If the player confirms a layout change (REQ-MOD-UI-DIALOG) while a production cycle is in progress, the current cycle is cancelled and all consumed materials are discarded; the shipyard returns to idle with the new layout configuration.
- REQ-BLD-SALVAGE-BAY: **Salvage Bay** (3×2): A dedicated drop-off point for salvage ships. It has an output buffer whose holding capacity is defined by the `output_buffer_capacity` field of the `salvage_bay` entry in `buildings.toml` (rather than by a production cycle, since the Salvage Bay has no recipe). A ship at the bay hands over one unit of scrap per tick while the buffer has free space; a full buffer blocks further drop-off until space frees up (consistent with the buffer-full semantics of REQ-MAT-OUTPUT-BUFFER). Held scrap is pushed onto connected output belts.
- REQ-BLD-BELT: **Belt** (1×1): Transports items. A belt tile has one direction (N, S, E, W) set at placement (modified by rotation). Curved belts are auto-derived: when a belt tile's outgoing direction leads into another belt whose direction is orthogonal, the downstream belt is rendered and behaves as a curve. Belt speed is defined in `world.toml [world].belt_speed_tiles_per_second` (REQ-GW-BELT-SPEED). A belt accepts items only through a non-output edge (REQ-MAT-ACCEPT-DIR).
- REQ-BLD-SPLITTER: **Splitter** (1×1): Distributes incoming items between two output directions. Incoming items are accepted only through the splitter's non-output edges (REQ-MAT-ACCEPT-DIR). Each output can optionally have a filter (a list of item types), configurable via the selected building panel; only implicitly unlocked item types are available as filter options (REQ-LOCK-UI-SPLITTER). Routing rules:
- REQ-BLD-SALVAGE-BAY: **Salvage Bay** (3×2): A dedicated drop-off point for salvage ships. Scrap delivered here is placed onto connected output belts.
- REQ-BLD-BELT: **Belt** (1×1): Transports items. A belt tile has one direction (N, S, E, W) set at placement (modified by rotation). Curved belts are auto-derived: when a belt tile's outgoing direction leads into another belt whose direction is orthogonal, the downstream belt is rendered and behaves as a curve. Belt speed is defined in `world.toml [world].belt_speed_tiles_per_second` (REQ-GW-BELT-SPEED).
- REQ-BLD-SPLITTER: **Splitter** (1×1): Distributes incoming items between two output directions. Each output can optionally have a filter (a list of item types), configurable via the selected building panel; only implicitly unlocked item types are available as filter options (REQ-LOCK-UI-SPLITTER). Routing rules:
- An item matching only one output's filter is routed to that output.
- An item matching both outputs' filters is distributed by strict alternation between those outputs.
- An item matching neither output's filter is routed to the unfiltered output. If both outputs have a filter and the item matches neither, the splitter stalls and moves no items until the situation is resolved.
- If neither output has a filter, items are distributed by strict alternation.
- In all alternation cases, if one output is blocked the item goes to the other output until it unblocks.
- REQ-BLD-TUNNEL-ENTRY: **Tunnel Entry** (1×1): The sending end of a tunnel pair. The player sets a direction (N, S, E, W) at placement, rotatable with R/Shift+R. Items arriving from an adjacent belt tile on a non-output edge (i.e. not the mouth edge in the entry's facing direction — see REQ-MAT-ACCEPT-DIR) whose direction points into the entry are forwarded through the tunnel to the paired Tunnel Exit (see REQ-BLD-TUNNEL-PAIR, REQ-BLD-TUNNEL-TRANSIT). If the entry is unpaired, or if the paired exit's output is blocked, the entry blocks like a full belt tile.
- REQ-BLD-TUNNEL-ENTRY: **Tunnel Entry** (1×1): The sending end of a tunnel pair. The player sets a direction (N, S, E, W) at placement, rotatable with R/Shift+R. Items arriving from an adjacent belt tile whose direction points into the entry are forwarded through the tunnel to the paired Tunnel Exit (see REQ-BLD-TUNNEL-PAIR, REQ-BLD-TUNNEL-TRANSIT). If the entry is unpaired, or if the paired exit's output is blocked, the entry blocks like a full belt tile.
- REQ-BLD-TUNNEL-EXIT: **Tunnel Exit** (1×1): The receiving end of a tunnel pair. The player sets a direction at placement, rotatable with R/Shift+R. Items received from the paired Tunnel Entry emerge from the output side of the exit tile — the tile adjacent in the exit's facing direction — continuing in that direction. If the exit is unpaired or its output is blocked, it holds received items until they can advance.
- REQ-BLD-TUNNEL-PAIR: **Tunnel pairing rules.** Pairing is re-evaluated for all Tunnel Entries whenever any Tunnel Entry or Tunnel Exit is placed, deconstructed, or enters or leaves the deconstruction queue (REQ-BLD-DECON-QUEUE; a tunnel end that is queued for deconstruction counts as removed for pairing).
- REQ-BLD-TUNNEL-PAIR: **Tunnel pairing rules.** Pairing is re-evaluated for all Tunnel Entries whenever any Tunnel Entry or Tunnel Exit is placed or demolished.
- A Tunnel Entry searches tile-by-tile in its facing direction for a partner. Any tunnel building (entry or exit) that faces a *different* direction is ignored and skipped. The search stops at the first tunnel building that faces the *same* direction as the searching entry.
- If that first same-direction tunnel building is a Tunnel Exit, is within `tunnel_max_distance` tiles of the entry, and is not already paired with a closer entry, the two form a pair.
- Otherwise the entry is unpaired.
- Pairing is one-to-one: each Tunnel Entry pairs with at most one Tunnel Exit, and vice versa. A Tunnel Exit is claimed by the nearest Tunnel Entry that can validly reach it; all other entries for which it would otherwise qualify are unpaired.
- When one end of a pair is deconstructed, the pair is dissolved and any items currently in transit are discarded.
- When one end of a pair is demolished, the pair is dissolved and any items currently in transit are discarded.
- REQ-BLD-TUNNEL-TRANSIT: **Tunnel transit.** Items inside a tunnel are not rendered (they travel invisibly). Transit time equals the tile-coordinate distance between entry and exit divided by `world.toml [world].belt_speed_tiles_per_second`, matching the time a chain of belt tiles of equivalent length would take. Multiple items may be in transit simultaneously, spaced as they would be on a belt chain of the same length. Clearing a tunnel entry or exit tile (REQ-UI-BELT-CLEAR) also discards all items currently in transit through that tunnel.
- REQ-BLD-TUNNEL-SELECT-HIGHLIGHT: **Selected-tunnel connection highlight.** While a Tunnel Entry or Tunnel Exit — operational building or construction site — is part of the current selection (single selection or multi-selection, REQ-UI-MULTI-SELECT), its tunnel connection is marked green in the game world, using the same `visuals.toml [overlays].tunnel_preview` green as the placement connection preview (REQ-BLD-TUNNEL-MODE). The matching end is found by applying the pairing scan of REQ-BLD-TUNNEL-PAIR over both built tunnels **and** construction-site tunnels (site-inclusive, matching the placement preview): for a selected entry, the first same-direction tunnel within `tunnel_max_distance` along its facing direction, if it is a Tunnel Exit; for a selected exit, the first same-direction tunnel within `tunnel_max_distance` opposite its facing direction, if it is a Tunnel Entry. When a matching end is found, the entry tile, the exit tile, and every tile strictly between them (along the tunnel's straight run) are marked green. A selected tunnel with no matching end shows no green highlight (it still receives the normal selection outline). In multi-selection each selected tunnel end that has a matching end contributes its connection, and a given connection is shown whenever either of its ends is selected. The highlight is presentation-only and has no effect on the simulation.
## Material Transport & Buffers
- REQ-MAT-BELT-ONLY: Materials are transported exclusively via belts, splitters, and tunnels, with one exception: two directly adjacent buildings whose output and input ports meet transfer items straight between them without an intervening transport tile (REQ-MAT-DIRECT-COUPLE).
- REQ-MAT-INPUT-PORTS: A building accepts items from any adjacent belt tile on any edge of its footprint (excluding cells occupied by output port(s)) whose direction points toward the building, provided the item is an input required by the currently selected recipe and the matching per-material input buffer has free space. An accepted item does not enter the building instantly; it is removed from the belt and travels inward across the input port's footprint cell on that port's own input belt before being added to the buffer (REQ-MAT-INPUT-INTAKE).
- REQ-MAT-INPUT-INTAKE: Accepted input items travel into a building as an animation rather than vanishing off the belt instantly — the input-side mirror of REQ-MAT-OUTPUT-EMERGE. Each input port has its own **input belt** — a virtual belt tile occupying the input port's footprint cell (the body cell the feeding belt points into), oriented in the port's inward flow direction, with progress 0.0 at the outer edge adjacent to the feeding belt and 0.5 at the tile centre. It reuses the belt subsystem: movement at belt speed (REQ-GW-BELT-SPEED), item rendering and spacing (REQ-GW-TILE-SIZE), and capacity/packing (REQ-GW-BELT-CAPACITY), but restricted to the 0.0→0.5 half of the tile. This applies to every building that pulls items from adjacent belts into an input buffer (Smelter, Assembler, Reprocessing Plant, Shipyard); a building may run several input belts at once when belts feed it from more than one side. The HQ is included with the one difference noted below.
- **Acceptance & reservation.** The acceptance test of REQ-MAT-INPUT-PORTS is unchanged — an item is accepted only if it is a required input whose per-material input buffer has space — except that "has space" now counts both the items already buffered **and** the items of that material currently travelling on the building's input belts (reserved but not yet arrived), so the total (buffered + in-transit) never exceeds that material's buffer cap (REQ-MAT-INPUT-BUFFER). An item that fails this test is not placed on an input belt and stays on the feeding belt exactly as before, so items that are not required inputs never enter the building.
- **Feeding.** An accepted item is removed from the feeding belt on the same tick it would have been taken without this animation, and placed on the input belt at progress 0.0, reserving a slot in its per-material buffer. (An input belt may also be fed directly by an adjacent producer's output belt rather than by a real belt — see REQ-MAT-DIRECT-COUPLE — with the same reservation and entry rules.) A new item is placed only when the input belt's entry slot at progress 0.0 is free (per REQ-GW-BELT-CAPACITY spacing — no in-transit item within a quarter tile of 0.0). The 0.0→0.5 span holds at most three in-transit items (progress 0.0, 0.25, 0.5); the reservation limit above may permit fewer.
- **Travel & arrival.** An in-transit item advances from progress 0.0 to 0.5 at belt speed. On reaching progress 0.5 it leaves the input belt and is added to its per-material input buffer, turning its reservation into buffered stock; only then does it count toward starting a production cycle (REQ-MAT-CYCLE). Because the slot was reserved on entry, arrival always succeeds — there is no deadlock.
- **Reservation may delay production.** A reserved item occupies buffer capacity for its whole 0.0→0.5 travel without yet being consumable, so an input-starved building may briefly wait for an in-transit item to arrive before it can start a cycle. This is accepted.
- **Clearing.** Clearing the input buffers on a recipe or schematic change (REQ-MAT-INPUT-BUFFER) also discards any items currently travelling on the input belts and releases their reservations.
- **HQ.** The HQ has no input buffer (REQ-HQ-BELT-INPUT); a building block accepted at an HQ input port travels its input belt the same way but reserves nothing, and is added to the global building blocks stock (REQ-MAT-GLOBAL-STOCK) on reaching progress 0.5.
- **Intake rendering (no pop-out).** Mirror of the emergence rendering in REQ-MAT-OUTPUT-EMERGE: the building is rendered over the input belt, so an in-transit item is occluded while inside the footprint and is only visible as it crosses the outer edge — appearing to sink into the port. The portion inside the footprint is hidden, and the item disappears at the tile centre (progress 0.5) as it enters the buffer.
- REQ-MAT-OUTPUT-PORT: Each building has one or more fixed output port(s) defined by its surface_mask (direction determined by rotation). Produced items do not appear on the outgoing belt instantly; each item leaves the building by first emerging across the output port tile on that port's own output belt and then transferring onto the adjacent real belt tile (REQ-MAT-OUTPUT-EMERGE). The adjacent belt's direction is otherwise unconstrained (it may flow away from the building or perpendicular to it), except that a belt oriented with its own output edge facing back into the building refuses the transfer and the item stays stuck at the port (REQ-MAT-ACCEPT-DIR, REQ-MAT-OUTPUT-EMERGE).
- REQ-MAT-OUTPUT-EMERGE: Items emerge from a building output port as an animation rather than popping directly onto the outgoing belt. Each output port has its own **output belt** — a virtual belt tile occupying the output port tile, oriented in the port's facing direction, with progress 0.0 at the tile's inner edge and 1.0 at the outer (port) edge adjacent to the next real belt tile. It reuses the belt subsystem: movement at belt speed (REQ-GW-BELT-SPEED), item rendering and spacing (REQ-GW-TILE-SIZE), and capacity/packing (REQ-GW-BELT-CAPACITY), but restricted to the 0.5→1.0 half of the tile. This applies to every building that outputs items onto belts (Miner, Smelter, Assembler, Reprocessing Plant, Salvage Bay); it does not apply to the Shipyard, which spawns a ship rather than a belt item (REQ-SHP-SPAWN-PLAYER).
- **Feeding.** While the output buffer (REQ-MAT-OUTPUT-BUFFER) holds an item that has not yet begun emerging and the output belt's entry slot at progress 0.5 is free (per REQ-GW-BELT-CAPACITY spacing — no emerging item within a quarter tile of progress 0.5), the next buffered item is placed on the output belt at progress 0.5. Because only the 0.5→1.0 span is used, the output belt holds at most three emerging items (progress 0.5, 0.75, 1.0); once that span is full the building places no further items on it even if the output buffer still holds more.
- **Cosmetic hold.** An emerging item still counts as residing in the output buffer (REQ-MAT-GLOBAL-STOCK) for the whole animation; it only leaves the building when it transfers onto a real belt tile at progress 1.0. The output belt therefore adds no inventory capacity beyond the output buffer, and clearing the output buffer on a recipe or schematic change (REQ-MAT-OUTPUT-BUFFER) also removes any items currently emerging.
- **Travel & handoff.** An emerging item advances from progress 0.5 to 1.0 at belt speed. At progress 1.0 it attempts to transfer onto the adjacent real belt tile using the normal belt hand-off and accept-direction rules (REQ-MAT-OUTPUT-PORT, REQ-MAT-ACCEPT-DIR): the transfer succeeds only if a transport tile exists there, is not oriented with its output edge facing back into the building, and has free space. On success the item leaves the output buffer and becomes an ordinary item on that belt tile. If instead the output port tile is a directly adjacent building's input edge, the item transfers straight into that building (REQ-MAT-DIRECT-COUPLE).
- **Stuck items.** If there is no next real belt tile and no directly-coupled building (REQ-MAT-DIRECT-COUPLE), or the transfer is refused or blocked, the emerging item stops at progress 1.0 and is rendered there (still counted in the output buffer). Following items pile up behind it at progress 0.75 and 0.5 per the packing above, and once the 0.5→1.0 span is full no further items emerge until the front item transfers.
- **Emergence rendering (no pop-in).** An emerging item must not simply appear at progress 0.5. The output port tile's building is rendered over the output belt, so an emerging item is occluded while inside the footprint and is revealed progressively as it slides past the port edge — appearing to physically emerge from the building. The portion of the item still within the output port tile is hidden; the portion past the outer edge is drawn.
- REQ-MAT-DIRECT-COUPLE: **Direct port coupling.** Two directly adjacent buildings whose ports meet transfer items between them with no intervening transport tile. A direct coupling exists at a shared edge where a producer building's output port tile (the tile it pushes toward, REQ-MAT-OUTPUT-PORT) is a body cell of a consumer building, and the producer's output direction carries the item across that edge into the consumer through one of the consumer's input edges (any perimeter edge other than the consumer's own output port, per REQ-MAT-INPUT-PORTS). Over a direct coupling the two virtual belts chain end to end: an item that reaches progress 1.0 on the producer's output belt at the shared edge (REQ-MAT-OUTPUT-EMERGE) is handed, instead of onto a real belt tile, directly onto the consumer's input belt at progress 0.0 (REQ-MAT-INPUT-INTAKE) and continues inward to the consumer's buffer — so the item appears to slide continuously across the shared edge from one building into the next.
- **Acceptance.** The hand-off obeys the consumer's normal input rules (REQ-MAT-INPUT-PORTS, REQ-MAT-INPUT-INTAKE): it succeeds only if the item is a required input of the consumer whose per-material buffer has space (reservation-aware — buffered + in-transit below the cap) and the consumer's input belt entry at progress 0.0 is free. On success the item leaves the producer's output buffer and reserves a slot in the consumer's input buffer, exactly as a belt-fed intake would. If the consumer does not accept the item — it is not one of its inputs, or the buffer is full, or the input-belt entry is occupied — the item stays stuck at the producer's output port at progress 1.0, exactly as when a downstream belt is blocked (REQ-MAT-OUTPUT-EMERGE stuck items).
- **Scope.** Direct coupling is the only case in which materials move between buildings without a belt, splitter, or tunnel (REQ-MAT-BELT-ONLY); it bridges only two buildings that are directly adjacent with meeting output/input ports. Transport tiles feeding a building (belt, splitter, or tunnel exit) continue to work through the normal pull, and a producer still hands off to a transport tile placed in the gap as before; a single such tile between two buildings is unaffected by this requirement.
- REQ-MAT-ACCEPT-DIR: A transport tile (belt, splitter, tunnel entry, or tunnel exit) accepts an incoming item only through a non-output edge; an item that would enter through one of the tile's output edges is refused. For a belt or a tunnel entry/exit the sole output edge is the one in its facing direction; for a splitter either of its two output directions is an output edge. This applies both to items pushed from an adjacent transport tile and to items deposited by a building's output port (REQ-MAT-OUTPUT-PORT).
- REQ-MAT-BELT-ONLY: Materials are transported exclusively via belts, splitters, and tunnels.
- REQ-MAT-INPUT-PORTS: A building accepts items from any adjacent belt tile on any edge of its footprint (excluding cells occupied by output port(s)) whose direction points toward the building, provided the item is an input required by the currently selected recipe and the matching per-material input buffer has free space.
- REQ-MAT-OUTPUT-PORT: Each building has one or more fixed output port(s) defined by its surface_mask (direction determined by rotation). Produced items are placed onto the belt at the output port tile regardless of that belt's direction.
- REQ-MAT-INPUT-BUFFER: Each building has one input buffer per required input material. Each per-material buffer holds up to twice that material's per-cycle requirement. When the player selects a new recipe or schematic, all items in all input buffers are cleared.
- REQ-MAT-OUTPUT-BUFFER: Each building has an output buffer that holds up to twice the quantity produced by one production cycle. If the output buffer is full, production stops until space is available. When the player selects a new recipe or schematic, all items in the output buffer are cleared (relevant when the adjacent belt is jammed and items have accumulated).
- REQ-MAT-OUTPUT-BUFFER-REPROCESSING: Exception to REQ-MAT-OUTPUT-BUFFER — the Reprocessing Plant's output buffer holds at most one cycle's output. This prevents exploits where the player stalls the output belt to force the plant to reroll.
@@ -217,7 +155,7 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
## Ships
- REQ-SHP-AUTONOMOUS: Ships are produced by shipyards and are fully autonomous once produced.
- REQ-SHP-STATS: Base hull stats are defined as plain values in `ships.toml`: HP (`[ship.health].hp`), max linear speed (`[ship.movement].speed`), sensor range (`[ship.sensors].range`), main acceleration (`[ship.movement].main_acceleration`, tiles/s²), maneuvering acceleration (`[ship.movement].maneuvering_acceleration`, tiles/s²), angular acceleration (`[ship.movement].angular_acceleration`, rad/s²), max rotation speed (`[ship.movement].max_rotation_speed`, rad/s). Required build materials (`[ship.schematic].materials`) are also defined there; whether the schematic starts unlocked or must be awarded during play is defined in `unlocks.toml` (REQ-LOCK-EXPLICIT). Combat, salvage, and repair capabilities are provided by modules (see REQ-MOD-CONFIG). Final hull stats incorporate passive module modifiers per REQ-MOD-STAT-CALC.
- REQ-SHP-STATS: Base hull stats are defined as plain values in `ships.toml`: HP (`[ship.health].hp`), max linear speed (`[ship.movement].speed`), sensor range (`[ship.sensors].range`), main acceleration (`[ship.movement].main_acceleration`, tiles/s²), maneuvering acceleration (`[ship.movement].maneuvering_acceleration`, tiles/s²), angular acceleration (`[ship.movement].angular_acceleration`, rad/s²), max rotation speed (`[ship.movement].max_rotation_speed`, rad/s). Required build materials (`[ship.schematic].materials`) and the station level at which the schematic becomes available for unlock (`[[ship]].unlock_at_station_level`; -1 = player starts with the schematic already unlocked) are also defined there. Combat, salvage, and repair capabilities are provided by modules (see REQ-MOD-CONFIG). Final hull stats incorporate passive module modifiers per REQ-MOD-STAT-CALC.
- REQ-SHP-SPAWN-PLAYER: A ship produced by a shipyard spawns centered on the shipyard's output port tile.
- REQ-SHP-SPAWN-ENEMY: Enemy ships spawn at a uniformly random position within the current enemy buffer zone — random X across the buffer's width and random Y across the world height.
- REQ-SHP-MOVEMENT: Ships move using a physics-based model. Each ship has a velocity and a facing direction, both updated each tick. The main acceleration (`main_acceleration`) is applied along the ship's current facing direction only. The maneuvering acceleration (`maneuvering_acceleration`) can be applied in any direction independently of the facing direction, enabling lateral or braking movement without rotating. The angular acceleration (`angular_acceleration`) controls how quickly the ship rotates. Linear speed is capped at the ship's `speed` value; rotation rate is capped at the ship's `max_rotation_speed` value. Ship position refers to the ship's center for all range, sensor, and attack checks.
@@ -258,6 +196,8 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- `id` — unique identifier, also used as the display name in the UI.
- `surface_mask` — footprint within the ship layout grid (see Module Surface Mask Format).
- `materials` — list of materials required per instance (added to the ship's build cost).
- `unlock_at_station_level` — the enemy defence station level at which this module's schematic becomes available for unlock; -1 means the player starts with the module schematic already unlocked.
- `unlock_requires` — optional list of prerequisite schematic ids that must already be unlocked before this module's schematic can drop (REQ-LOCK-PREREQ). Defaults to empty.
- `production_time_seconds` — time added to the ship's production cycle per instance.
- `fill_color` — fill color used to render this module's cells in the layout grid.
- `glyph` — single character rendered on this module's cells in the layout grid and preview widget.
@@ -311,7 +251,7 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
### Module UI
- REQ-MOD-UI-PREVIEW: For a selected shipyard (operational building or construction site), the selected building panel always shows a small non-interactive **ship layout preview** widget below the schematic selection button (REQ-UI-SELECT-BUTTON) and a "Configure" button below the preview. Both are **disabled while no schematic is selected**, and enabled once one is; the preview then shows an empty placeholder in place of a layout grid. When a schematic is selected, the preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` with the module's `glyph` character. For non-shipyard buildings, neither the preview nor the "Configure" button is shown.
- REQ-MOD-UI-PREVIEW: When a schematic is selected in a shipyard's selected building panel, a small non-interactive **ship layout preview** widget is shown below the schematic selection button (REQ-UI-SELECT-BUTTON). The preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` with the module's `glyph` character. Below the preview, a "Configure" button is shown.
- REQ-MOD-UI-DIALOG: Clicking the "Configure" button opens the **layout configuration dialog** as a modal. While the dialog is open, the game is paused (speed set to 0×). On close, the game speed is restored to what it was before the dialog was opened.
The dialog contains:
@@ -321,12 +261,6 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- **Right** (below the grid): The layout blueprint panel (see REQ-MOD-UI-BLUEPRINT-PANEL through REQ-MOD-UI-BLUEPRINT-FILE-LOAD).
- **Bottom**: A "Confirm" button and a "Cancel" button. Cancel discards all changes made in this dialog session and closes the dialog. Confirm applies the changes: the shipyard's configured layout is updated, the required materials and cycle time displayed in the selected building panel are recalculated, and the ship layout preview is refreshed.
- REQ-MOD-UI-EMPTY-PULSE: While a module is selected for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG), the empty buildable cells of the layout grid pulse smoothly around their normal fill shade, oscillating between a slightly darker and a slightly brighter shade at approximately 1 Hz (one full cycle per second), to draw the player's attention to where the module can be placed. All empty buildable cells pulse in phase. When no module is selected for placement (including remove mode), empty buildable cells render at their normal static shade. Non-buildable cells and cells occupied by a placed module do not pulse.
- REQ-MOD-UI-AUTO-DIALOG: When the player selects a schematic for a shipyard (operational building or construction site) through the schematic selection dialog (REQ-UI-SELECT-BUTTON), and the chosen schematic **differs** from the shipyard's current schematic, the layout configuration dialog (REQ-MOD-UI-DIALOG) opens automatically and immediately once the selection dialog closes — exactly as if the player had then clicked "Configure". Re-selecting the schematic already set does not reopen the dialog. This auto-open applies only to the manual schematic selection dialog; schematic changes applied via the copy-settings gesture (REQ-BLD-COPY-CONFIG) or blueprint placement (REQ-UI-BLUEPRINT-PLACE) do **not** auto-open the dialog. The player may still cancel the auto-opened dialog (REQ-MOD-UI-DIALOG), which leaves the newly selected schematic in place with its default empty layout; the "Configure" button (REQ-MOD-UI-PREVIEW) remains available to open the dialog again later.
- REQ-MOD-UI-MODULE-TOOLTIP: Each module selection button in the layout configuration dialog (REQ-MOD-UI-DIALOG) shows a hover tooltip with the descriptive text defined for that module type in `modules.toml` (the optional per-module tooltip field). If a module type defines no tooltip text, its button shows no tooltip. The "Remove" button is not a module type and has no config-defined tooltip.
- REQ-MOD-UI-STATS-PANEL: The **ship stats panel** in the layout configuration dialog shows the stats of the currently configured ship layout as they would be computed, incorporating all passive module modifiers per REQ-MOD-STAT-CALC. The panel updates in real time whenever modules are placed or removed in the layout grid.
The panel always shows all hull stats as final computed values:
@@ -371,27 +305,35 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-DEF-ENEMY-FIRE: Enemy defence stations automatically fire at player ships within range.
- REQ-DEF-NO-CROSSFIRE: Enemy and player defence stations are never in each other's firing range.
- REQ-DEF-PUSH: When both enemy defence stations in a set are destroyed, the boss countdown is advanced (REQ-WAV-BOSS-ADVANCE), the scrollable area is extended (REQ-GW-PUSH-EXPAND), a new set of enemy defence stations is placed at the new boundary, and exactly one schematic drop is awarded for the destroyed set (REQ-DEF-SCHEMATIC-DROP).
- REQ-DEF-SCHEMATIC-DROP: Each destroyed set of enemy defence stations awards exactly one drop (not one per station). The drop opens a **schematic choice dialog** — a modal dialog that pauses the game (speed set to 0×; on close, speed is restored to what it was before the dialog opened). Before drawing picks, an artifact roll is made: evaluate `world.toml [world].artifact_chance_formula` with `x` set to the level of the destroyed station set, clamp the result to [0, 1], then compare against a uniform random value in [0, 1). If the roll succeeds, the dialog presents one **artifact option** plus two unlock picks drawn from the eligible pool; otherwise it presents three unlock picks. Up to three (or two, if an artifact option is present) unlock options are drawn uniformly at random **without replacement** from the eligible pool. If the pool contains fewer than the required number of entries, only that many unlock options are shown (the artifact option is always shown if the roll succeeded).
- REQ-DEF-SCHEMATIC-DROP: Each destroyed set of enemy defence stations awards exactly one schematic drop (not one per station). The drop opens a **schematic choice dialog** — a modal dialog that pauses the game (speed set to 0×; on close, speed is restored to what it was before the dialog opened). Before drawing schematic picks, an artifact roll is made: evaluate `world.toml [world].artifact_chance_formula` with `x` set to the level of the destroyed station set, clamp the result to [0, 1], then compare against a uniform random value in [0, 1). If the roll succeeds, the dialog presents one **artifact option** plus two schematic picks drawn from the eligible pool; otherwise it presents three schematic picks. Up to three (or two, if an artifact option is present) schematic options are drawn uniformly at random **without replacement** from the eligible drop pool. If the pool contains fewer than the required number of entries, only that many schematic options are shown (the artifact option is always shown if the roll succeeded). The eligible drop pool contains:
- All **ship schematics** and **module schematics** whose `unlock_at_station_level` is ≥ 0 and ≤ the level of the destroyed station set, and which have not yet been unlocked.
- All **assembler recipe schematics** whose `unlock_at_station_level` is ≥ 0 and ≤ the level of the destroyed station set, whose output item is currently implicitly unlocked (REQ-LOCK-IMPLICIT), and which have not yet been awarded.
The eligible pool contains every **unlock group** (REQ-LOCK-EXPLICIT) that (a) has not yet been awarded, (b) whose `station_level` is ≤ the level of the destroyed station set, and (c) every prerequisite in its `requires` list is currently satisfied (REQ-LOCK-PREREQ). Because the pool is rebuilt for each drop, an unlock group gated behind prerequisites first appears only after all of its prerequisites have themselves been awarded.
In addition to the conditions above, a schematic is included in the eligible drop pool only when every prerequisite in its optional `unlock_requires` list is currently satisfied (REQ-LOCK-PREREQ). Because the pool is rebuilt for each drop, a schematic gated behind prerequisites first appears only after all of its prerequisites have themselves been unlocked.
Each option in the dialog displays the unlock group's display name — derived from its `id` (same display convention as building, module, and recipe ids) — and the list of items it would grant: its ship, module, building, and assembler-recipe ids (each shown with the same display convention as its respective selection dialog). The artifact option (if present) is displayed as a distinct entry with the name "Artifact".
Each option in the dialog displays: the schematic name (ship `display_name` from `ships.toml`, module `id` from `modules.toml`, or the output item type for assembler recipes) and the schematic type (ship, module, or assembler recipe). The artifact option (if present) is displayed as a distinct entry with the name "Artifact".
Each option additionally displays a vertical list of recipe names labeled "Unlocks recipes:", showing which miner and assembler recipes would newly become implicitly unlocked (REQ-LOCK-IMPLICIT) if this option were selected — specifically, the miner recipes and implicitly-gated assembler recipes that are not currently implicitly unlocked but would become so after applying this option's effect. To compute this, all `materials` of the group's granted ship and module schematics are added to the base set per REQ-LOCK-IMPLICIT step 1a, and the output items of the group's granted assembler recipes are added per step 1b, before recomputation.
Each option additionally displays a vertical list of item names labeled "Unlocks recipes for:", showing which recipes would newly become implicitly unlocked (REQ-LOCK-IMPLICIT) if this option were selected — specifically, the output items of miner recipes and assembler recipes (without `unlock_at_station_level`) that are not currently implicitly unlocked but would become so after applying this option's effect:
- For a ship or module schematic, its `materials` are added to the base set per REQ-LOCK-IMPLICIT step 1a before recomputation.
- For an assembler recipe schematic, its output item is added to the base set per REQ-LOCK-IMPLICIT step 1b before recomputation.
Each recipe is listed by its `id` (using the same display convention as the assembler recipe-selection dialog), sorted alphabetically. Hovering a recipe in this list displays the recipe info tooltip described for a recipe in REQ-UI-SELECT-TOOLTIP (the recipe name; the name and quantity of each input item; the completion time; and the name and quantity of the produced output item). If no recipes would be newly unlocked, the list shows "None".
Item names are deduplicated and sorted alphabetically. If no recipes would be newly unlocked, the list shows "None".
The player selects one option by clicking it. If the player selects the artifact option, the player's artifact count is incremented by 1 (REQ-WIN-ARTIFACT-COUNT) and the dialog closes; no unlock is applied. Otherwise the selected unlock group is awarded and the dialog closes: every ship, module, building, and assembler recipe the group grants becomes unlocked at once — ship schematics unlock the corresponding shipyard selection; module schematics unlock the module type for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG); building types become available in the build menu (REQ-LOCK-BUILDING); assembler recipes become available in the assembler recipe-selection dialog (subject to REQ-LOCK-UI-RECIPE). The unlock group is removed from the pool permanently (REQ-LOCK-EXPLICIT), and the implicit unlock set is recomputed (REQ-LOCK-IMPLICIT).
The player selects one option by clicking it. If the player selects the artifact option, the player's artifact count is incremented by 1 (REQ-WIN-ARTIFACT-COUNT) and the dialog closes; no schematic is applied. Otherwise, the selected schematic is applied and the dialog closes:
For a **ship or module schematic**: it is unlocked (ship schematics unlock the corresponding shipyard selection; module schematics unlock the module type for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG)).
For an **assembler recipe schematic**: the recipe is explicitly unlocked and becomes available in the assembler recipe-selection dialog (subject to REQ-LOCK-UI-RECIPE). The schematic is removed from the drop pool permanently (REQ-LOCK-EXPLICIT). The implicit unlock set is recomputed (REQ-LOCK-IMPLICIT).
## Progression & Locking
- REQ-LOCK-EXPLICIT: The unit of unlocking is an **unlock group**, defined by an `[[unlock]]` entry in `unlocks.toml` (see Unlock Group Format). Each unlock group grants a set of ship schematics, module schematics, building types, and/or assembler recipes. A ship, module, building, or assembler recipe is **locked at game start if and only if some unlock group grants it**; anything not granted by any unlock group starts unlocked. (For assembler recipes this "starts unlocked" is further governed by implicit gating — see REQ-LOCK-IMPLICIT; an assembler recipe granted by an unlock group is explicitly gated and never subject to implicit unlocking, while one flagged `unlocked_at_start` is always available.) A locked item is unlocked only by awarding its unlock group via REQ-DEF-SCHEMATIC-DROP, which grants all of the group's members at once. Once awarded, an unlock group and its members are never re-locked within a run, and the group is removed from the drop pool permanently; lock states reset to their initial values on Restart (REQ-CFG-RELOAD). Each grantable id may be granted by **at most one** unlock group; a grant id that names no defined ship/module/building/assembler-recipe, that names a non-assembler recipe, or that is granted by more than one unlock group, is a configuration error that fails config load with a descriptive message (REQ-CFG-RELOAD).
- REQ-LOCK-EXPLICIT: Ship schematics, module schematics, and **assembler recipe schematics** (assembler recipes in `recipes.toml` that define `unlock_at_station_level`) are **explicitly** locked or unlocked. A schematic starts unlocked if its `unlock_at_station_level` is -1; all others start locked. Locked schematics are unlocked only by REQ-DEF-SCHEMATIC-DROP. Once unlocked, a schematic is never re-locked within a run; lock states reset to their initial values on Restart (REQ-CFG-RELOAD). Unlike ship and module schematics, an assembler recipe schematic is removed from the drop pool permanently once awarded and cannot be dropped again.
- REQ-LOCK-PREREQ: An unlock group may optionally define `requires` — a list of prerequisite **unlock-group ids** that must already have been awarded before this group may enter the drop pool. A prerequisite is **satisfied** only when the unlock group it names has been awarded (REQ-LOCK-EXPLICIT). This check is applied in addition to the conditions in REQ-DEF-SCHEMATIC-DROP: a group enters the eligible pool only when its `station_level` condition is met, it has not yet been awarded, and every id in its `requires` is satisfied. `requires` defaults to empty (no prerequisites). The check is re-evaluated against the current set of awarded unlock groups every time a drop pool is built (after each REQ-DEF-SCHEMATIC-DROP and on Restart per REQ-CFG-RELOAD), so a gated group becomes eligible in the first drop after its last prerequisite is awarded. Every id listed in any `requires` must resolve to an unlock group defined in `unlocks.toml`; an id that names no such group is a configuration error that fails config load with a descriptive message (config is loaded at startup and reloaded on Restart, REQ-CFG-RELOAD). An unlock group that lists itself, or a cycle of mutually dependent prerequisites, is not a load error but can never become eligible, since no group in the cycle can be the first to be awarded.
- REQ-LOCK-PREREQ: A ship schematic, module schematic, or assembler recipe schematic may optionally define `unlock_requires` — a list of prerequisite schematic ids (a ship `id`, module `id`, or assembler recipe `id`) that must already be unlocked before this schematic may enter the drop pool. A prerequisite is **satisfied** only when the schematic it names is currently **explicitly unlocked** (REQ-LOCK-EXPLICIT) — that is, the referenced schematic either started unlocked with `unlock_at_station_level = -1` or has been awarded via a drop. This prerequisite check is applied in addition to the per-schematic conditions in REQ-DEF-SCHEMATIC-DROP: a schematic enters the eligible drop pool only when its `unlock_at_station_level` condition is met, it has not yet been unlocked/awarded, and every id in its `unlock_requires` is satisfied. `unlock_requires` defaults to empty (no prerequisites), which reproduces the prior behaviour. The check is re-evaluated against the current explicit-unlock set every time a drop pool is built (after each REQ-DEF-SCHEMATIC-DROP and on Restart per REQ-CFG-RELOAD), so a gated schematic becomes eligible in the first drop after its last prerequisite is unlocked. Every id listed in any `unlock_requires` must resolve to a schematic that is itself explicitly unlockable (a ship, module, or assembler recipe schematic defined in config); an id that names no such schematic is a configuration error that fails config load with a descriptive message (config is loaded at startup and reloaded on Restart, REQ-CFG-RELOAD). A schematic that lists itself, or a cycle of mutually dependent prerequisites, is not a load error but can never become eligible, since no schematic in the cycle can be the first to unlock.
- REQ-LOCK-IMPLICIT: Item types and miner/assembler recipes are **implicitly** unlocked or locked based on the current set of unlocked ship, module, and assembler recipe schematics. The implicit unlock set is recomputed whenever any schematic changes lock state (on Restart or after REQ-DEF-SCHEMATIC-DROP). Computation:
1. Start with the union of: (a) all item types listed in `materials` across all currently unlocked ship schematics and all currently unlocked module schematics, and (b) the output item type of every assembler recipe that is currently **explicitly available** — that is, either flagged `unlocked_at_start` in `recipes.toml`, or granted by an unlock group that has been awarded (REQ-LOCK-EXPLICIT).
2. For each item type in the current set: for every recipe (miner, smelter, or assembler) that produces it — skipping any assembler recipe that is granted by an unlock group whose group has not yet been awarded — add each of that recipe's input item types to the set. If the recipe is a miner recipe, or an assembler recipe that is not granted by any unlock group, mark it as implicitly unlocked. Assembler recipes that are explicitly available (flagged `unlocked_at_start`, or granted by an awarded unlock group) are available in the assembler recipe-selection dialog by virtue of REQ-LOCK-EXPLICIT; their inputs are also added to the implicit set in this step.
1. Start with the union of: (a) all item types listed in `materials` across all currently unlocked ship schematics and all currently unlocked module schematics, and (b) the output item type of every currently explicitly unlocked assembler recipe schematic (REQ-LOCK-EXPLICIT).
2. For each item type in the current set: for every recipe (miner, smelter, or assembler) that produces it — skipping any assembler recipe schematic that defines `unlock_at_station_level` and is not yet explicitly unlocked — add each of that recipe's input item types to the set. If the recipe is a miner recipe or an assembler recipe that does not define `unlock_at_station_level`, mark it as implicitly unlocked. Explicitly unlocked assembler recipe schematics are available in the assembler recipe-selection dialog by virtue of REQ-LOCK-EXPLICIT; their inputs are also added to the implicit set in this step.
3. Repeat step 2 until no new item types are added.
Item types and miner/assembler recipes not reached by this process (and not explicitly unlocked) are locked. Smelter recipes participate in the traversal to propagate unlocking to their inputs but are never themselves shown in any UI dropdown.
@@ -401,11 +343,9 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
- REQ-LOCK-UI-SCHEMATIC: Locked ship schematics are not shown in the shipyard's schematic-selection dialog (REQ-UI-SELECT-BUTTON).
- REQ-LOCK-BUILDING: A building type granted by an unlock group (REQ-LOCK-EXPLICIT) is **locked** until that group is awarded. A locked building type has no button in the build button grid (REQ-UI-BUILD-GRID) and cannot be placed, selected as a build tool, or triggered by its build hotkey (REQ-UI-HOTKEYS); its button appears in the grid only once the building type is unlocked. Building types not granted by any unlock group are available from game start. Lock state resets on Restart (REQ-CFG-RELOAD).
- REQ-LOCK-UI-SPLITTER: Item types that are not implicitly unlocked are excluded from splitter filter dropdowns (REQ-BLD-SPLITTER).
- REQ-LOCK-UI-BLUEPRINT: When a blueprint is placed (REQ-UI-BLUEPRINT-PLACE): if a building in the blueprint is of a currently locked building type (REQ-LOCK-BUILDING), that building is silently skipped — no ghost, no validity check, no construction site, and its cost is excluded from the total — exactly as if it were not part of the blueprint; if a stored recipe ID for a miner or assembler is currently locked, that building's recipe is left unset rather than applied; if a stored splitter filter entry refers to a locked item type, that entry is silently removed. (The analogous rule for locked ship schematics is defined in REQ-UI-BLUEPRINT-PLACE.)
- REQ-LOCK-UI-BLUEPRINT: When a blueprint is placed (REQ-UI-BLUEPRINT-PLACE): if a stored recipe ID for a miner or assembler is currently locked, that building's recipe is left unset rather than applied; if a stored splitter filter entry refers to a locked item type, that entry is silently removed. (The analogous rule for locked ship schematics is defined in REQ-UI-BLUEPRINT-PLACE.)
## Threat Level & Enemy Waves
@@ -453,51 +393,29 @@ The screen is divided into two columns: a main column (75% width) containing the
```
- REQ-UI-HEADER: The header bar spans the width of the game world column (75% of the screen width) and always shows the elapsed survival time, the current global building blocks stock, and the artifact count (REQ-WIN-ARTIFACT-COUNT) displayed as `Artifacts: x/y` (where `x` is the current artifact count and `y` is `world.toml [world].artifact_win_count`) on the left, the boss wave counter and boss countdown (REQ-UI-BOSS-STATUS) and an asteroid expansion button (REQ-UI-EXPAND-BUTTON) to the left of the speed buttons, and game speed controls on the right.
- REQ-UI-BLOCKS-TOOLTIP: The header bar's building blocks stock display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].building_blocks_tooltip` — intended to tell the player what building blocks are used for and how to obtain them. If the field is unset, the stock display shows no tooltip. This tooltip is distinct from the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP).
- REQ-UI-ARTIFACTS-TOOLTIP: The header bar's artifact count display (REQ-UI-HEADER) shows a hover tooltip with the descriptive text defined in `world.toml [world].artifact_tooltip` — intended to tell the player what artifacts are, how they are obtained (REQ-DEF-SCHEMATIC-DROP), and that collecting `world.toml [world].artifact_win_count` of them wins the game (REQ-WIN-ARTIFACT-COUNT). If the field is unset, the artifact count display shows no tooltip. This tooltip is distinct from the building blocks tooltip (REQ-UI-BLOCKS-TOOLTIP) and the build/module button tooltips (REQ-UI-BUILD-TOOLTIP, REQ-MOD-UI-MODULE-TOOLTIP).
- REQ-UI-BOSS-STATUS: The header bar displays, to the left of the speed buttons, the current boss wave counter (REQ-WAV-BOSS-COUNTER) and the time remaining on the boss countdown (REQ-WAV-BOSS-COUNTDOWN). The boss wave counter is shown as `Boss Wave #<x>` and the countdown as `Next boss: <M:SS>`, where `<M:SS>` is the remaining seconds formatted as whole minutes and two-digit seconds. Both values update continuously as the simulation runs.
- REQ-UI-SPEED: The game speed controls in the header bar are buttons for 0×, 0.5×, 1×, 2×, and 10× speed. The currently active speed is shown as selected. All game simulation (production, movement, threat accumulation, wave timing) scales with the selected speed. 0× pauses the game.
- REQ-UI-PAUSE-BORDER: While the game is paused (speed 0×, whether set via the speed controls (REQ-UI-SPEED), the Space toggle (REQ-UI-HOTKEYS), or an auto-pausing modal), a vignette border is drawn around the edges of the game world view to make the paused state hard to miss. The border is black and fades in the alpha channel from fully transparent at its inner (center-facing) edge to 50% opacity at the viewport edge, over a thickness of 100 pixels (capped at half the smaller viewport dimension on very small views).
- REQ-UI-DECONSTRUCT-BORDER: While deconstruct mode is active (REQ-UI-DECONSTRUCT-BUTTON, REQ-UI-HOTKEYS), a vignette border is drawn around the edges of the game world view to signal the mode, matching the geometry of the paused-state vignette (REQ-UI-PAUSE-BORDER): a 100-pixel thickness (capped at half the smaller viewport dimension on very small views) with the four sides meeting along mitred corner diagonals. It fades in the alpha channel from fully transparent at its inner (center-facing) edge to the deconstruct tint color at the viewport edge. The color — including its alpha, which sets the peak opacity at the viewport edge — is read from `visuals.toml [overlays].deconstruct_tint`, the same deconstruct-mode color used for the hover tint. The border is presentation-only and has no effect on the simulation. If the game is both paused and in deconstruct mode, both vignettes are drawn and compose over each other.
- REQ-UI-SPEED: The game speed controls in the header bar are buttons for 0×, 0.5×, 1×, 2×, and 4× speed. The currently active speed is shown as selected. All game simulation (production, movement, threat accumulation, wave timing) scales with the selected speed. 0× pauses the game.
- REQ-UI-EXPAND-BUTTON: The header bar shows an asteroid expansion button captioned `Expand: <x> Blocks`, where `<x>` is the current expansion cost computed from `world.toml [expansion].cost_building_blocks_formula` at the current number of purchased expansions (REQ-EXP-COST). Clicking the button unlocks the next asteroid expansion (REQ-EXP-UNLOCK, REQ-GW-ASTEROID-EXPAND), spending that many building blocks from the global stock. The button is disabled when the player cannot currently afford the cost (consistent with REQ-UI-BUILD-DISABLED). The caption updates as the cost changes with each purchased expansion.
- REQ-UI-WORLD-SIZE: The game world view occupies the full height below the header bar in the main column (75% of the screen width).
- REQ-UI-PANEL-COLUMN: The side panel column occupies 25% of the screen width and the full screen height. It is divided into three equal-height panels stacked top to bottom: selected building panel (top), build button grid (middle), and blueprint panel (bottom).
- REQ-UI-MODAL-DIM: While a modal dialog, menu, or full-screen state screen is open on top of the game, a transparent black overlay (a dim/scrim) is drawn over the **entire game window** — the header bar, the game world view, and the side panel column — behind that modal, so the game reads as inactive while the modal holds focus. The overlay is shown for every modal that auto-pauses the simulation — the escape menu (REQ-UI-GAME-MENU), the recipe/schematic selection dialog (REQ-UI-SELECT-BUTTON), the layout configuration dialog (REQ-MOD-UI-DIALOG), and the schematic choice dialog (REQ-DEF-SCHEMATIC-DROP) — as well as the game-over screen (REQ-HQ-GAME-OVER) and the win screen (REQ-WIN-SCREEN), which end rather than pause the game. When modals are nested (for example the Create Blueprint name dialog (REQ-MOD-UI-BLUEPRINT-CREATE) opened from the layout configuration dialog), only a single dim is shown over the game window; nested modals do not stack additional overlays. The dim color and opacity are read from `visuals.toml [overlays]` (a semi-transparent black modal-dim color), consistent with the other overlay colors. The overlay is presentation-only and has no effect on the simulation.
### Game World
- REQ-UI-SCROLL: The player scrolls the view horizontally across the scrollable area by pressing A (scroll left) and D (scroll right). The pan speed is not constant; it varies with the view's position per REQ-UI-SCROLL-SPEED.
- REQ-UI-SCROLL-SPEED: The horizontal pan speed varies with position so the player crosses the empty middle of the world quickly while retaining fine control near the asteroid and near the front line. Two pan speeds are read from `world.toml [scroll]`: `pan_speed_slow_tiles_per_second` (the base speed, used while the view is over the asteroid and player buffer zone) and `pan_speed_fast_tiles_per_second` (the faster speed, used while the view is over the contest zone). Both are expressed in tiles per second and apply equally to the A and D scroll directions. The current pan speed is a function of the view's horizontal center X (REQ-GW-REGIONS defines the regions):
- **Flat regions:** while the view center is left of the contest zone (over the asteroid or player buffer zone) and outside any ramp band, the pan speed is the slow speed; while the view center is inside the contest zone and outside any ramp band, the pan speed is the fast speed.
- **Ramp bands:** a transition ramp band of width `world.toml [scroll].pan_ramp_band_width_tiles` tiles straddles each contest-zone boundary (the player defence stations on the left, the enemy defence stations on the right), centered on the boundary with half the band width on each side. While the view center is within a ramp band, the pan speed is linearly interpolated between the slow speed at the band's outer (non-contest-zone) edge and the fast speed at the band's inner (contest-zone) edge, by the view center's fractional position across the band. This produces smooth speed changes when entering and exiting the fast contest-zone range rather than an abrupt jump.
- **Narrow contest zone:** should the two ramp bands overlap (a contest zone narrower than the band width), each ramp is clamped at the contest-zone center so the bands do not cross; the fast plateau then reduces to a single point at the center and the peak speed there may be below the fast speed.
Because the contest-zone boundaries shift as the scrollable area grows with each push (REQ-GW-PUSH-EXPAND, REQ-GW-SCROLL-LIMIT), the ramp bands are recomputed from the current contest-zone boundaries. This is a presentation-only concern and does not affect the simulation, consistent with REQ-UI-NO-ZOOM.
- REQ-UI-SCROLL: The player scrolls the view horizontally across the scrollable area by pressing A (scroll left) and D (scroll right).
- REQ-UI-CONSTRUCTION-PROGRESS: Construction sites display the building's glyph centered on the footprint (same as an operational building). Below the glyph — or centered on the footprint if the building has no glyph — a construction progress percentage is shown (integer, e.g. `42%`), increasing from 0% to 100% as construction completes.
- REQ-UI-PORT-GLYPH: Every output port of every building is indicated by a directional glyph drawn on the port's tile. The glyph is a `>` rotated to face the port's exit direction (`>` for East, `^` for North, `<` for West, `v` for South). It is drawn at the midpoint between the tile center and the tile edge that the port exits through (i.e. halfway from center toward the exit edge). The indicator is rendered for all building states: operational buildings, construction sites, and the builder-mode ghost. Buildings with multiple output ports (e.g. splitters) show one indicator per port.
- REQ-UI-PORT-TARGET-GLYPH: While in builder mode (REQ-BLD-BUILDER-MODE), the builder-mode ghost additionally shows, for each of the building's output ports, a directional glyph drawn centered in the port's **target cell** — the cell immediately outside the footprint that the port pushes into, i.e. the cell the surface-mask output-port indicator occupies (see Surface Mask Format). As in REQ-UI-PORT-GLYPH the glyph is a `>` rotated to face the port's exit direction (`>` East, `^` North, `<` West, `v` South), previewing where the port's output will go before placement. This is in addition to the on-tile port glyph of REQ-UI-PORT-GLYPH, and — unlike that indicator — is shown only for the builder-mode ghost, not for operational buildings, construction sites, or the blueprint-placement ghost (REQ-UI-BLUEPRINT-PLACE). A building with multiple output ports (e.g. a splitter) shows one target-cell glyph per port. The target-cell glyph is drawn larger than the on-tile port glyph so it stands out as the flow-direction preview. Exceptions: the Tunnel Entry shows no target-cell glyph, because it receives items (which may arrive from any of its non-mouth edges, REQ-BLD-TUNNEL-ENTRY) rather than emitting into a single adjacent cell; the Shipyard shows none either, because its output port is a ship-spawn point (REQ-SHP-SPAWN-PLAYER) rather than a belt-item output (REQ-MAT-OUTPUT-EMERGE).
- REQ-UI-STATUS-LIGHT: Every operational production building — Miner, Smelter, Assembler, Reprocessing Plant, Shipyard, and Salvage Bay — renders a small **status light**: a filled circle with a black outline drawn in the building's upper-right corner, letting the player read a building's production state without selecting it. The light is anchored to the footprint corner that is the upper-right corner in the building's default orientation and rotates with the building — like the output-port glyph (REQ-UI-PORT-GLYPH) — so it stays on the same physical corner of the building as it is rotated. The status light is rendered only for operational buildings; construction sites (which instead show construction progress, REQ-UI-CONSTRUCTION-PROGRESS) and the builder-mode ghost do not render it. Buildings that are not production buildings — belts, splitters, tunnel entries/exits, and the HQ — have no status light. The black outline is constant; the fill color reflects the building's current production state.
- For the five production buildings (Miner, Smelter, Assembler, Reprocessing Plant, Shipyard), the fill color is determined by evaluating, in order:
- **Grey** — no recipe or schematic is selected. This applies only to buildings with a player-facing selection (Miner, Assembler, Shipyard); the Smelter and Reprocessing Plant always run an implicit recipe (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) and are never grey.
- **Green** — the building is currently producing: a production cycle is active (REQ-MAT-CYCLE; for the Shipyard, an in-progress production cycle per REQ-BLD-SHIPYARD).
- **Red** — the building is idle because a required input is missing from its input buffers, so it cannot start a cycle. Missing input takes precedence over a full output buffer: if any required input is missing the light is red even when the output buffer is also full.
- **Yellow** — the building is idle with all required inputs present but its output buffer full, so no new cycle can start (REQ-MAT-OUTPUT-BUFFER, REQ-MAT-CYCLE).
- A configured building that is momentarily idle yet blocked by neither condition (all inputs present and the output buffer has room — a transient state that resolves into a started cycle on the same or the next tick per REQ-MAT-CYCLE) shows green.
- The Salvage Bay has no recipe and no production cycle (REQ-BLD-SALVAGE-BAY); its status light uses only two states: **green** while its output buffer holds at least one unit of scrap, and **red** while its output buffer is empty. The Salvage Bay's status light is never grey or yellow.
- The four fill colors (grey, green, red, yellow) and the outline color are read from `visuals.toml [status_light]`, consistent with the other rendering-only colors. The status light is presentation-only and has no effect on the simulation.
- REQ-UI-HP-BARS: All entities with HP — the HQ, player and enemy defence stations, and player and enemy ships — render an HP bar below them. The bar is always visible regardless of current HP. The bar's filled portion represents the fraction of current HP to maximum HP.
- REQ-UI-NO-ZOOM: The view has a fixed zoom level; the player cannot zoom in or out.
- REQ-UI-HOTKEYS: Global keyboard shortcuts:
- **Space** — toggles pause. Pressing Space pauses (sets speed to 0×) and stores the previously selected non-zero speed; pressing Space again restores that speed.
- **W** — increases game speed by one step in the sequence 0×, 0.5×, 1×, 2×, 10× (no wrap-around past 10×).
- **W** — increases game speed by one step in the sequence 0×, 0.5×, 1×, 2×, 4× (no wrap-around past 4×).
- **S** — decreases game speed by one step in the same sequence (no wrap-around past 0×).
- **A / D** — scroll the view left / right (REQ-UI-SCROLL).
- **Q** — context-sensitive. If a build mode is active (builder mode or blueprint placement mode), pressing Q exits it. Otherwise, pressing Q toggles deconstruct mode: it enters deconstruct mode if inactive, or exits deconstruct mode if already active. (See also REQ-UI-DECONSTRUCT-BUTTON for the equivalent button.)
- **Q** — context-sensitive. If a build mode is active (builder mode or blueprint placement mode), pressing Q exits it. Otherwise, pressing Q toggles demolish mode: it enters demolish mode if inactive, or exits demolish mode if already active. (See also REQ-UI-DEMOLISH-BUTTON for the equivalent button.)
- **R / Shift+R** — in builder mode, rotate the ghost counter-clockwise / clockwise (REQ-BLD-ROTATE).
- **T** — create a temporary blueprint from the current selection and enter its placement mode (REQ-UI-BLUEPRINT-TEMP).
- **Escape** — opens the escape menu (REQ-UI-GAME-MENU).
- **Build mode selection** — pressing a build hotkey activates builder mode for the corresponding building type, equivalent to clicking its build button (REQ-BLD-BUILDER-MODE):
- **1** — Belt, **2** — Splitter, **3** — Tunnel (the unified tunnel build mode, REQ-BLD-TUNNEL-MODE). Hotkey 4 is unused.
- **1** — Belt, **2** — Splitter, **3** — Tunnel Entry, **4** — Tunnel Exit.
- **Shift+1** — Miner, **Shift+2** — Smelter, **Shift+3** — Assembler, **Shift+4** — Shipyard, **Shift+5** — Salvage Bay, **Shift+6** — Reprocessing Plant.
### Debug Draw
@@ -521,63 +439,47 @@ The screen is divided into two columns: a main column (75% width) containing the
### Selected Building Panel
- REQ-UI-EMPTY-SELECTION: When nothing is selected (no building, construction site, ship, defence station, or scrap pile), the panel is empty.
- REQ-UI-SELECTION-CATEGORIES: **Selection categories and precedence.** Every selectable object belongs to one of two mutually exclusive selection categories: **buildings** (buildings and construction sites) and **field objects** (ships and defence stations — player or enemy — together with scrap piles). A single selection holds objects from only one category at a time. Field objects of different kinds may be selected together (e.g. several ships plus scrap piles, freely mixing player and enemy actors). Buildings are exclusive and take precedence — **buildings win**: selecting a building (by click, Ctrl+click, or a box-drag covering at least one building) clears any field selection and yields a buildings-only selection, and conversely selecting any field object clears any building selection. Point hit-testing prefers a building over a coincident field object, and among field objects prefers an actor (ship or defence station) over a coincident scrap pile (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-SCRAP-CLICK-SELECT).
- REQ-UI-EMPTY-SELECTION: When no building is selected, the panel is empty.
- REQ-UI-SINGLE-SELECTION: When one building is selected, the panel shows: building name, current recipe or schematic selection, input buffer contents, and output buffer contents. Buffer counts are displayed as `a/b` where `a` is the current item count and `b` is the per-cycle amount (items consumed per run for inputs; items produced per run for outputs). For a selected construction site, the recipe/schematic selection (and, for a shipyard, the layout preview and "Configure" button) are shown but the buffer rows are omitted (REQ-BLD-SITE-CONFIG).
- REQ-UI-PRODUCTION-PROGRESS: For buildings that produce items or ships (miner, smelter, assembler, reprocessing plant, shipyard), the selected building panel also shows: (a) the cycle time of the currently selected recipe or schematic in seconds, and (b) the completion percentage of the active production cycle as an integer (e.g. `42%`), or the text `idle` when no production cycle is active. When no recipe or schematic is selected, neither the cycle time nor the progress indicator is shown.
- REQ-UI-MULTI-SELECT: The player selects multiple objects by box-drag or by Ctrl+clicking individual objects to add or remove them from the selection. Multi-select operates within a single category (REQ-UI-SELECTION-CATEGORIES). A box-drag that covers at least one building selects buildings (any field objects within the box are ignored — buildings win); a box-drag that covers no building but does cover ships, defence stations, or scrap piles selects all of those field objects together (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-SCRAP-MULTI-SELECT).
- REQ-UI-MULTI-SELECTION: When multiple buildings are selected, the panel shows how many of each building type are selected. No per-building detail is shown. The panel additionally shows the **total building block cost** of the selection — the sum of each selected building's placement cost (`buildings.toml [[building]].cost`, per REQ-BLD-COST), counting only player-placeable buildings (buildings with a button in the build button grid); non-player-placeable buildings (the HQ and defence stations) are excluded from the total, consistent with the blueprint total (REQ-UI-BLUEPRINT-BUTTON). Construction sites count at their building type's full placement cost regardless of construction progress.
- REQ-UI-MULTI-SELECT: The player selects multiple buildings by box-drag or by Ctrl+clicking individual buildings to add or remove them from the selection.
- REQ-UI-MULTI-SELECTION: When multiple buildings are selected, the panel shows how many of each building type are selected. No per-building detail is shown.
- REQ-UI-CONFIG-INLINE: Recipe and schematic configuration for a selected building is shown within this panel. Recipe selection (miner, assembler) and schematic selection (shipyard) use the selection button and dialog (REQ-UI-SELECT-BUTTON) rather than an inline control. For shipyards, the panel additionally shows the ship layout preview and "Configure" button below the schematic selection button (REQ-MOD-UI-PREVIEW).
- REQ-UI-SELECT-BUTTON: **Recipe and schematic selection control.** Recipe selection (Miner ore type, Assembler recipe) and schematic selection (Shipyard) are each presented in the selected building panel as a single **selection button** whose caption is the name of the currently selected recipe or schematic, or a placeholder ("Select recipe" / "Select schematic") when none is selected. Clicking the button opens a modal **selection dialog** that pauses the game (speed set to 0×; on close, the speed is restored to what it was before the dialog was opened). The dialog contains a grid of option buttons, one per selectable option — only options that are currently unlocked are shown (REQ-LOCK-UI-RECIPE for recipes, REQ-LOCK-UI-SCHEMATIC for schematics). Hovering an option button shows the selection info tooltip (REQ-UI-SELECT-TOOLTIP). Clicking an option button selects that recipe/schematic, closes the dialog, and updates the selection button's caption in the selected building panel. The dialog can be dismissed without changing the current selection (e.g. closing it without clicking an option). Selecting a new recipe or schematic has the same effects as before (REQ-MAT-INPUT-BUFFER, REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD).
- REQ-UI-SELECT-TOOLTIP: **Selection info tooltip.** Hovering an option button in the selection dialog (REQ-UI-SELECT-BUTTON), and hovering the selection button in the selected building panel when a selection is set, displays an info tooltip:
- For a **recipe** (Miner or Assembler): the recipe name; the name and quantity of each input item (no inputs are listed for miner recipes, which consume nothing); the completion time (`duration_seconds`); and the name and quantity of the produced output item.
- For a **ship schematic** (Shipyard): the ship's `display_name`; the name and quantity of each base required material (`[ship.schematic].materials`, excluding any module contributions); the base production time (`[ship.schematic].production_time_seconds`); and "Produces: 1 <ship display name>".
- REQ-UI-BELT-CLEAR: When one or more belt, splitter, tunnel entry, or tunnel exit tiles are selected, the panel shows a "Clear" button that removes all items from the selected tiles. Clearing a tunnel entry or exit also discards all items currently in transit through that tunnel (REQ-BLD-TUNNEL-TRANSIT). This can be used to resolve stalled belts, splitters, and tunnels.
- REQ-UI-ENTITY-CLICK-SELECT: The player can click any ship (player or enemy) or any defence station (player or enemy) in the game world to select it. A plain click on a ship or defence station makes it the sole selection, clearing any previous selection. Ships and defence stations can be multi-selected — by Ctrl+clicking individual actors to add or remove them, or by box-drag (REQ-UI-MULTI-SELECT) — and can be selected together with scrap piles and with one another in a single field selection (REQ-UI-SELECTION-CATEGORIES), freely mixing player and enemy actors. Actors cannot be selected together with buildings: selecting a ship or defence station clears any building selection, and selecting a building clears the actors (buildings win). Clicking a scrap pile adds to or establishes a field selection (REQ-UI-SCRAP-CLICK-SELECT). Clicking empty world space (no building, ship, defence station, or scrap pile) clears the selection.
- REQ-UI-SHIP-STATS-PANEL: When exactly one ship is selected (REQ-UI-ENTITY-CLICK-SELECT) and no scrap is selected, the selected building panel shows a **ship stats panel**. (If scrap is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.) The panel structure mirrors REQ-MOD-UI-STATS-PANEL but reflects the ship's actual live state: stats are computed from its installed modules per REQ-MOD-STAT-CALC. The panel always shows all hull stats: HP (current / maximum), max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, and max rotation speed. In addition, capability module summaries are shown conditioned on which module types are installed, using the same aggregation rules as REQ-MOD-UI-STATS-PANEL: weapons (combined DPS, maximum range), salvage (combined collection rate, maximum range), and repair (combined repair rate, maximum range), each section appearing only if at least one instance of that module type is installed. While debug draw mode is active (REQ-UI-DEBUG-DRAW), the panel additionally shows the ship's derived threat cost (REQ-MOD-THREAT).
- REQ-UI-SHIP-BEHAVIOR: The ship stats panel (REQ-UI-SHIP-STATS-PANEL) additionally displays the selected ship's **current behavior** — a single label naming the top-priority behavior currently governing the ship's navigation, as resolved by the fixed-priority behavior arbitration. Only the winning behavior is named; lower-priority behaviors that are suppressed are not shown, and neither are the salvage/repair cycles that run regardless of the active behavior (REQ-SHP-SALVAGE, REQ-SHP-REPAIR). The label updates live as the ship's behavior changes, and it is always shown (independent of debug draw mode, unlike the threat-cost line of REQ-UI-SHIP-STATS-PANEL). This applies to both player and enemy ships (REQ-UI-ENTITY-CLICK-SELECT); enemy ships only ever show **Engaging** or **Advancing**. The behavior labels (all wrapped in `tr()`) are:
- **Retreating** — the ship is retreating (REQ-SHP-RETREAT).
- **Engaging** — the ship is engaging a combat target (player: REQ-SHP-COMBAT; enemy: REQ-SHP-ENEMY-AI).
- **Salvaging** — the ship is executing salvage navigation: seeking scrap, collecting, or delivering to a Salvage Bay (REQ-SHP-SALVAGE).
- **Repairing** — the ship is navigating to a repair target (REQ-SHP-REPAIR).
- **Rallying** — the ship is moving to or orbiting the rally point (REQ-SHP-RALLY).
- **Standby** — the ship is holding with its fleet (REQ-SHP-STANDBY).
- **Advancing** — the ship is executing the baseline forward advance with no higher-priority behavior active (player: REQ-SHP-COMBAT advance toward the enemy; enemy: REQ-SHP-ENEMY-AI advance toward the asteroid).
- REQ-UI-STATION-STATS-PANEL: When exactly one defence station is selected (REQ-UI-ENTITY-CLICK-SELECT) and no scrap is selected, the selected building panel shows a **station stats panel** displaying the station's stats computed at its current level: HP (current / maximum), damage, range, and fire rate. (If scrap is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.)
- REQ-UI-FIELD-MULTI-SELECTION: The full single-actor stats panel (REQ-UI-SHIP-STATS-PANEL, REQ-UI-STATION-STATS-PANEL) is shown only when the field selection holds exactly one actor and no scrap. Whenever the selection holds more than one object — multiple actors, or a single actor together with scrap — the panel shows a **compact summary** instead: a count per actor type, one line per type rendered as "<type> x <count>" (the same `x`-count notation as the recipe tooltip and the building multi-selection, REQ-UI-MULTI-SELECTION). Ships are grouped by schematic display name and defence stations as a group, distinguishing player from enemy. No per-actor detail and no total-actor-count header are shown (consistent with the building panel). If scrap piles are also part of the field selection (REQ-UI-SELECTION-CATEGORIES) their total is appended as a final line of the same summary (REQ-UI-SCRAP-PANEL), so all lines share uniform spacing. Building selections use REQ-UI-SINGLE-SELECTION / REQ-UI-MULTI-SELECTION instead.
- REQ-UI-SCRAP-CLICK-SELECT: The player can click any scrap pile (REQ-RES-SCRAP-DROP) in the game world to select it. Scrap piles are field objects (REQ-UI-SELECTION-CATEGORIES) and can be selected together with ships and defence stations, but not with buildings. A plain click on a scrap pile makes it the sole selection, clearing any previous selection; selecting a building clears any scrap (buildings win), and selecting a scrap pile clears any building selection. Hit-testing prefers a building over a coincident actor or scrap pile, and an actor (ship or defence station) over a coincident scrap pile: a scrap pile is selected only when no building or actor is under the cursor. A selected scrap pile that despawns or is fully collected (REQ-RES-SCRAP-DROP) is removed from the selection; if no selected object remains, the panel becomes empty (REQ-UI-EMPTY-SELECTION).
- REQ-UI-SCRAP-MULTI-SELECT: Multiple scrap piles can be selected by box-drag or by Ctrl+clicking individual piles to add or remove them, mirroring building multi-select (REQ-UI-MULTI-SELECT). Scrap shares the field-object category with ships and defence stations (REQ-UI-SELECTION-CATEGORIES), so a field selection may hold scrap piles and actors together. Ctrl+clicking a scrap pile while a field selection is active adds or removes that pile within the same selection; Ctrl+clicking a scrap pile while a building selection is active first clears the buildings and begins a field selection (buildings win). Conversely, selecting a building while a field selection is active clears it. Box-drag disambiguation follows REQ-UI-MULTI-SELECT (a box covering any building selects buildings; a box covering no building selects the ships, defence stations, and scrap piles within it).
- REQ-UI-SCRAP-PANEL: When one or more scrap piles are selected, the selected building panel shows the **total remaining scrap amount** across all selected piles — the sum of the piles' current remaining amounts (REQ-RES-SCRAP-DROP), e.g. "Scrap x 47". The same summed-amount display is used whether one pile or many are selected; no per-pile detail and no pile count are shown. The displayed total updates as selected piles are partially collected or despawn (REQ-UI-SCRAP-CLICK-SELECT). When actors are also selected, this scrap total is shown as an additional line of the actor count summary rather than alongside a single-actor stats panel (REQ-UI-FIELD-MULTI-SELECTION).
- REQ-UI-ENTITY-CLICK-SELECT: The player can click any ship (player or enemy) or any defence station (player or enemy) in the game world to select it. Clicking a ship or defence station clears any existing selection and establishes a single-entity selection containing only that entity. Ships and defence stations cannot participate in multi-select together with buildings. Clicking empty world space (no building, ship, or defence station) clears the selection.
- REQ-UI-SHIP-STATS-PANEL: When a single ship is selected (REQ-UI-ENTITY-CLICK-SELECT), the selected building panel shows a **ship stats panel**. The panel structure mirrors REQ-MOD-UI-STATS-PANEL but reflects the ship's actual live state: stats are computed from its installed modules per REQ-MOD-STAT-CALC. The panel always shows all hull stats: HP (current / maximum), max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, and max rotation speed. In addition, capability module summaries are shown conditioned on which module types are installed, using the same aggregation rules as REQ-MOD-UI-STATS-PANEL: weapons (combined DPS, maximum range), salvage (combined collection rate, maximum range), and repair (combined repair rate, maximum range), each section appearing only if at least one instance of that module type is installed. While debug draw mode is active (REQ-UI-DEBUG-DRAW), the panel additionally shows the ship's derived threat cost (REQ-MOD-THREAT).
- REQ-UI-STATION-STATS-PANEL: When a single defence station is selected (REQ-UI-ENTITY-CLICK-SELECT), the selected building panel shows a **station stats panel** displaying the station's stats computed at its current level: HP (current / maximum), damage, range, and fire rate.
### Build Button Grid
- REQ-UI-BUILD-GRID: All placeable building types are shown as a flat grid of buttons with no grouping. Tunnel Entry and Tunnel Exit share a single **Tunnel** button (REQ-BLD-TUNNEL-MODE) rather than one button each.
- REQ-UI-BUILD-GRID: All placeable building types are shown as a flat grid of buttons with no grouping.
- REQ-UI-BUILD-COST: Each button caption shows the building name and its building block cost, e.g. "Belt: 2 Blocks".
- REQ-UI-BUILD-TOOLTIP: Each building-type button shows a hover tooltip with the descriptive text defined for that building type in `buildings.toml` (the optional per-building tooltip field). This tooltip is distinct from the recipe/schematic selection tooltip (REQ-UI-SELECT-TOOLTIP). If a building type defines no tooltip text, its button shows no tooltip. The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) is not a building type and has no config-defined tooltip.
- REQ-UI-BUILD-DISABLED: Buttons for buildings the player cannot currently afford are shown as disabled.
- REQ-UI-DECONSTRUCT-BUTTON: A dedicated **Deconstruct** button is shown in the build button grid. Clicking it toggles deconstruct mode on and off, equivalent to the Q deconstruct toggle (REQ-UI-HOTKEYS). The button is shown in a visually active/pressed state while deconstruct mode is active.
- REQ-UI-DEMOLISH-BUTTON: A dedicated **Demolish** button is shown in the build button grid. Clicking it toggles demolish mode on and off, equivalent to the Q demolish toggle (REQ-UI-HOTKEYS). The button is shown in a visually active/pressed state while demolish mode is active.
### Blueprint Panel
- REQ-UI-BLUEPRINT-PANEL: The blueprint panel is shown to the right of the build button grid. It contains, from top to bottom: a "Create Blueprint" button, and a list of blueprint entries (one per saved blueprint, in creation order). The panel has no Save or Load buttons; blueprints are persisted automatically (REQ-UI-BLUEPRINT-SAVE) and restored at startup (REQ-UI-BLUEPRINT-LOAD).
- REQ-UI-BLUEPRINT-PANEL: The blueprint panel is shown to the right of the build button grid. It contains, from top to bottom: a "Create Blueprint" button, and a list of blueprint entries (one per saved blueprint, in creation order).
- REQ-UI-BLUEPRINT-CREATE: The "Create Blueprint" button is enabled only when at least one player-placeable building (i.e. a building with a button in the build button grid) is currently selected; non-player-placeable buildings (HQ, defence stations) in the selection do not count toward this condition. A selected player-placeable building may be either an operational building or a construction site (a building placed but not yet fully built, REQ-BLD-SITE-CONFIG); both count toward this condition and are captured identically (REQ-UI-BLUEPRINT-STORAGE). When clicked, a modal dialog appears prompting the player to enter a name. The dialog has Confirm and Cancel buttons. Clicking Cancel closes the dialog with no effect. Clicking Confirm with a non-empty name creates a blueprint from the current selection, silently excluding any non-player-placeable buildings, and appends its button to the blueprint list.
- REQ-UI-BLUEPRINT-CREATE: The "Create Blueprint" button is enabled only when at least one player-placeable building (i.e. a building with a button in the build button grid) is currently selected; non-player-placeable buildings (HQ, defence stations) in the selection do not count toward this condition. When clicked, a modal dialog appears prompting the player to enter a name. The dialog has Confirm and Cancel buttons. Clicking Cancel closes the dialog with no effect. Clicking Confirm with a non-empty name creates a blueprint from the current selection, silently excluding any non-player-placeable buildings, and appends its button to the blueprint list.
- REQ-UI-BLUEPRINT-TEMP: Pressing the **T** key (REQ-UI-HOTKEYS) creates a **temporary blueprint** from the current selection and immediately enters blueprint placement mode for it, without opening the naming dialog. It has effect only when at least one player-placeable building is currently selected — the same condition as REQ-UI-BLUEPRINT-CREATE; pressing T with an empty selection, or a selection containing only non-player-placeable buildings (HQ, defence stations), does nothing. Entering this mode replaces any currently active build, blueprint placement, or deconstruct mode. The temporary blueprint is captured exactly as a saved blueprint (REQ-UI-BLUEPRINT-STORAGE), silently excluding any non-player-placeable buildings from the selection, but it is never named, never shown in the blueprint panel (REQ-UI-BLUEPRINT-PANEL), and never persisted to `blueprints.toml` (REQ-UI-BLUEPRINT-SAVE). Placement behaves identically to a saved blueprint's placement mode (REQ-UI-BLUEPRINT-MODE, REQ-UI-BLUEPRINT-PLACE): a ghost is rendered per building, R / Shift+R rotate the entire constellation, placement follows the same per-building validity and total-cost rules, and after a successful placement the mode stays active so the blueprint can be placed again. Right-clicking in the game world exits placement mode, at which point the temporary blueprint is discarded.
- REQ-UI-BLUEPRINT-STORAGE: A blueprint stores its name and, for each building in the selection, the building type, its rotation, its tile offset (integer dx, dy) from the center of the bounding box of all selected buildings' footprints, and — where applicable — the selected recipe ID (miners and assemblers) or schematic ID (shipyards), and for splitters the two output filters (each a list of item types; an empty list means accept-all), at the time of capture. A source building may be either an operational building or a construction site (REQ-BLD-SITE-CONFIG); a construction site is captured identically, storing whatever configuration it currently holds and never any buffer or construction-progress state. If no recipe or schematic was selected at capture time, none is stored; for a splitter with no filters set, no filter lists are stored. This structure maps directly to a TOML representation (e.g. one `[[building]]` array entry per constituent building, with the splitter filters as `filter_a`/`filter_b` arrays of item-type ids).
- REQ-UI-BLUEPRINT-STORAGE: A blueprint stores its name and, for each building in the selection, the building type, its rotation, its tile offset (integer dx, dy) from the center of the bounding box of all selected buildings' footprints, and — where applicable — the selected recipe ID (miners and assemblers) or schematic ID (shipyards), and for splitters the two output filters (each a list of item types; an empty list means accept-all), at the time of capture. If no recipe or schematic was selected at capture time, none is stored; for a splitter with no filters set, no filter lists are stored. This structure maps directly to a TOML representation (e.g. one `[[building]]` array entry per constituent building, with the splitter filters as `filter_a`/`filter_b` arrays of item-type ids).
- REQ-UI-BLUEPRINT-BUTTON: Each blueprint entry consists of a blueprint button and a dedicated delete icon ("×") placed to the right of the button. The blueprint button displays the blueprint name and, below it, the total building block cost of the blueprint (sum of the individual costs of all constituent buildings). A blueprint button is disabled when the player cannot afford the total cost. Clicking an enabled blueprint button enters blueprint placement mode for that blueprint. The delete icon is always enabled regardless of whether the player can afford the blueprint.
- REQ-UI-BLUEPRINT-MODE: In blueprint placement mode a ghost is rendered for every building in the blueprint (excluding any of a currently locked building type, REQ-LOCK-BUILDING, which is omitted entirely per REQ-LOCK-UI-BLUEPRINT) at the position determined by its stored tile offset from the bounding-box center, which is anchored to the tile under the cursor. Each ghost is rendered individually as valid or invalid, applying REQ-BLD-PLACE-VALID conditions (a) and (b) per building (the other ghosts in the same blueprint do not count as existing buildings for the overlap check). A valid ghost uses its building type's semi-transparent per-building coloring (REQ-BLD-GHOST); an invalid ghost uses the distinct "invalid" color, as in single-building builder mode. Pressing R / Shift+R rotates the entire constellation 90° counter-clockwise / clockwise: each building's tile offset is rotated around the bounding-box center and each building's own rotation is updated, consistent with REQ-BLD-ROTATE. Blueprint placement mode is exited by right-clicking in the game world. Clicking a different blueprint button exits the current mode and enters blueprint placement mode for the newly clicked blueprint.
- REQ-UI-BLUEPRINT-MODE: In blueprint placement mode a ghost is rendered for every building in the blueprint at the position determined by its stored tile offset from the bounding-box center, which is anchored to the tile under the cursor. Each ghost is rendered individually as valid or invalid, applying REQ-BLD-PLACE-VALID conditions (a) and (b) per building (the other ghosts in the same blueprint do not count as existing buildings for the overlap check). A valid ghost uses its building type's semi-transparent per-building coloring (REQ-BLD-GHOST); an invalid ghost uses the distinct "invalid" color, as in single-building builder mode. Pressing R / Shift+R rotates the entire constellation 90° counter-clockwise / clockwise: each building's tile offset is rotated around the bounding-box center and each building's own rotation is updated, consistent with REQ-BLD-ROTATE. Blueprint placement mode is exited by right-clicking in the game world. Clicking a different blueprint button exits the current mode and enters blueprint placement mode for the newly clicked blueprint.
- REQ-UI-BLUEPRINT-PLACE: Buildings of a currently locked building type (REQ-LOCK-BUILDING) are first excluded from the blueprint for this placement, per REQ-LOCK-UI-BLUEPRINT — they are not ghosted, not validity-checked, not placed, and their cost is excluded from the total. Left-clicking in blueprint placement mode then places the (remaining) blueprint if (a) every building in the constellation satisfies REQ-BLD-PLACE-VALID conditions (a) and (b) at its resolved tile, and (b) the player has enough building blocks to afford the total cost. If both conditions are met, a construction site is added to the build queue for each building in the blueprint and the full total cost is deducted from the global building blocks stock in one transaction. If a recipe ID is stored for a building, it is applied to the construction site immediately. If a schematic ID is stored, it is applied only if that schematic is currently unlocked; if it is not unlocked, the shipyard's schematic is left unset. If splitter output filters are stored, they are applied to the construction site immediately and carry over when it finishes building (REQ-BLD-SITE-CONFIG). Locked recipe IDs and splitter filter entries for locked item types are handled on placement per REQ-LOCK-UI-BLUEPRINT. After a successful placement the game remains in blueprint placement mode, allowing the player to place the same blueprint again immediately.
- REQ-UI-BLUEPRINT-PLACE: Left-clicking in blueprint placement mode places the blueprint if (a) every building in the constellation satisfies REQ-BLD-PLACE-VALID conditions (a) and (b) at its resolved tile, and (b) the player has enough building blocks to afford the total cost. If both conditions are met, a construction site is added to the build queue for each building in the blueprint and the full total cost is deducted from the global building blocks stock in one transaction. If a recipe ID is stored for a building, it is applied to the construction site immediately. If a schematic ID is stored, it is applied only if that schematic is currently unlocked; if it is not unlocked, the shipyard's schematic is left unset. If splitter output filters are stored, they are applied to the construction site immediately and carry over when it finishes building (REQ-BLD-SITE-CONFIG). Locked recipe IDs and splitter filter entries for locked item types are handled on placement per REQ-LOCK-UI-BLUEPRINT. After a successful placement the game remains in blueprint placement mode, allowing the player to place the same blueprint again immediately.
- REQ-UI-BLUEPRINT-DELETE: Clicking the delete icon ("×") on a blueprint entry immediately removes that blueprint from the list. If the deleted blueprint was active in blueprint placement mode, that mode is exited.
- REQ-UI-BLUEPRINT-SAVE: On application shutdown, all current blueprints are serialized to a file named `blueprints.toml` located in the same directory as the application executable. The TOML structure matches REQ-UI-BLUEPRINT-STORAGE. Write errors are silently ignored on shutdown (no button, no dialog).
- REQ-UI-BLUEPRINT-SAVE: A "Save" button is shown at the bottom of the blueprint panel. Clicking it serializes all current blueprints to a file named `blueprints.toml` located in the same directory as the application executable. The TOML structure matches REQ-UI-BLUEPRINT-STORAGE. If writing fails, a modal error dialog is shown describing the failure.
- REQ-UI-BLUEPRINT-LOAD: At application startup, blueprints are loaded from `blueprints.toml` in the same directory as the application executable, populating the blueprint list (in the order they appear in the file). If the file does not exist, the blueprint list starts empty with no error. If the file exists but cannot be parsed (malformed TOML), a modal error dialog describes the failure and the blueprint list starts empty. There is no Load button and no runtime reload.
- REQ-UI-BLUEPRINT-LOAD: A "Load" button is shown at the bottom of the blueprint panel, to the right of the "Save" button. Clicking it shows a confirmation dialog ("Load blueprints? This will replace all current blueprints.") with Confirm and Cancel buttons. Clicking Cancel closes the dialog with no effect. Clicking Confirm reads `blueprints.toml` from the same directory as the application executable, replaces all current blueprints with those from the file (in the order they appear in the file), and exits any active blueprint-related mode (blueprint placement mode, delete mode). If the file does not exist or cannot be parsed, a modal error dialog is shown describing the failure and the current blueprint list is left unchanged.
## Balancing Tool
@@ -605,7 +507,7 @@ A separate executable target (`balancing`) that links against `lib` but contains
- REQ-BAL-SIM-ENV: Each arena simulates a pure-space environment using the same tick-based simulation as the main game. There is no asteroid, no buildings, no belts, no wave system, and no threat accumulation. Only ships, HQs, defence stations, and combat are active.
- REQ-BAL-SIM-AI: Ships use the same AI and stats as in the main game. Ships with no target in sensor range advance toward the enemy team's HQ. Ships that detect an enemy in sensor range engage it as in the normal game (REQ-SHP-COMBAT, REQ-SHP-ENEMY-AI).
- REQ-BAL-SIM-SPEED: Each arena that is not being inspected runs its simulation at maximum tick rate (as many ticks per second as the hardware allows), with no rendering. An inspected arena runs at a player-controllable game speed (same speed steps as the main game: 0×, 0.5×, 1×, 2×, 10×) with full rendering in the inspect window, defaulting to 1× on open.
- REQ-BAL-SIM-SPEED: Each arena that is not being inspected runs its simulation at maximum tick rate (as many ticks per second as the hardware allows), with no rendering. An inspected arena runs at a player-controllable game speed (same speed steps as the main game: 0×, 0.5×, 1×, 2×, 4×) with full rendering in the inspect window, defaulting to 1× on open.
- REQ-BAL-SIM-PARALLEL: All arenas are simulated in parallel, each on its own thread.
- REQ-BAL-SIM-END: An arena fight ends when either team's HQ is destroyed or all ships and defence stations of one team have been destroyed. If a team has no defence stations, destroying all its ships is sufficient. When the fight ends, the simulation for that arena stops.
@@ -622,6 +524,6 @@ A separate executable target (`balancing`) that links against `lib` but contains
- REQ-BAL-UI-WIDGET-START: Each arena widget contains a "Start" button that starts the simulation for that arena. The button is disabled while the arena's simulation is running. When a finished arena's Start button is clicked, a fresh simulation is created and started (the widget resets to initial unit counts, the border returns to blue, and the previous results are replaced).
- REQ-BAL-UI-WIDGET-BORDER: Each arena widget has a colored border indicating its state: grey when not yet started, blue while its simulation is running, and green when the fight has ended.
- REQ-BAL-UI-INSPECT: Clicking an arena widget's "Inspect" button opens a new inspect window for that arena. Any previously open inspect window is closed first (its arena's simulation is aborted and its widget border returns to grey). The inspected arena is restarted with a fresh simulation that runs at controllable game speed with full rendering (REQ-BAL-SIM-SPEED). The arena widget updates live during inspection (surviving counts, border color, `[WON]` prefix) as it does for non-inspected arenas. Only one inspect window may be open at a time.
- REQ-BAL-UI-INSPECT-WINDOW: The inspect window consists of three sections, top to bottom: a title bar area containing the arena name and game speed controls (same buttons as the main game: 0×, 0.5×, 1×, 2×, 10×, with Space to toggle pause — see REQ-UI-SPEED and REQ-UI-HOTKEYS), the arena view in the center, and an info panel at the bottom displaying the same team columns and entry format as the arena widget in the main window (REQ-BAL-UI-WIDGET), updated live, including the arena's battle duration once the fight has ended (REQ-BAL-UI-WIDGET).
- REQ-BAL-UI-INSPECT-WINDOW: The inspect window consists of three sections, top to bottom: a title bar area containing the arena name and game speed controls (same buttons as the main game: 0×, 0.5×, 1×, 2×, 4×, with Space to toggle pause — see REQ-UI-SPEED and REQ-UI-HOTKEYS), the arena view in the center, and an info panel at the bottom displaying the same team columns and entry format as the arena widget in the main window (REQ-BAL-UI-WIDGET), updated live, including the arena's battle duration once the fight has ended (REQ-BAL-UI-WIDGET).
- REQ-BAL-UI-INSPECT-VIEW: The arena view renders all tiles of the arena and displays ships, HQs, defence stations, and laser beams using the same visual elements and `visuals.toml` colors as the main game. Team 1 uses player visual styles; team 2 uses enemy visual styles. The view has a fixed zoom level — no zoom or scroll is possible. The tile size is derived so that the full arena (all tiles) fits within the view.
- REQ-BAL-UI-INSPECT-CLOSE: Closing the inspect window (via the window's close button) aborts the inspected arena's simulation. The arena widget's border returns to grey and its surviving counts are left as they were at the moment of closing. All main window buttons and controls are re-enabled.

View File

@@ -1,4 +1,4 @@
set(TARGET_BASE_NAME "${PRODUCT_NAME}")
set(TARGET_BASE_NAME "DotaFactory")
set(TARGET_APP_NAME "${TARGET_BASE_NAME}")
set(TARGET_LIB_NAME "${TARGET_BASE_NAME}_lib")
@@ -117,7 +117,6 @@ target_link_libraries(${TARGET_UI_NAME}
Qt5::Network
Qt5::Multimedia
Qt5::Charts
Qt5::Svg
)
target_compile_definitions(${TARGET_UI_NAME} PRIVATE TOML_FLOAT_CHARCONV=0)
@@ -184,19 +183,6 @@ target_compile_definitions(${TARGET_APP_NAME} PRIVATE
)
target_link_libraries(${TARGET_APP_NAME} ${TARGET_UI_NAME})
# Embed the Windows version resource so the version shows on the executable's
# Details tab (right-click -> Properties). Values come from cmake/version.cmake
# (version numbers) and the product identity variables in the top-level
# CMakeLists.txt. MSVC compiles the .rc automatically once it is a target source.
if (WIN32)
configure_file(
"${CMAKE_SOURCE_DIR}/cmake/version.rc.in"
"${CMAKE_CURRENT_BINARY_DIR}/version.rc"
@ONLY
)
target_sources(${TARGET_APP_NAME} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/version.rc")
endif ()
unset(APP_FILES)
unset(RELATIVE_HDRS)
unset(RELATIVE_SRCS)

View File

@@ -44,6 +44,7 @@ ArenaSimulation::ArenaSimulation(const GameConfig& gameConfig,
, m_team1HqEntity(entt::null)
, m_team2HqEntity(entt::null)
, m_finished(false)
, m_winnerTeam(-1)
, m_stopRequested(false)
{
m_buildingSystem = std::make_unique<BuildingSystem>(
@@ -94,7 +95,7 @@ ArenaSimulation::ArenaSimulation(const GameConfig& gameConfig,
updateStatus();
}
std::string ArenaStatus::TeamStatus::getEhpPercentText() const
std::string ArenaStatus::TeamStatus::ehpPercentText() const
{
if (maxEhp <= 0.0)
{
@@ -311,7 +312,7 @@ void ArenaSimulation::requestStop()
m_stopRequested.store(true, std::memory_order_relaxed);
}
ArenaStatus ArenaSimulation::getStatus() const
ArenaStatus ArenaSimulation::status() const
{
std::lock_guard<std::mutex> lock(m_statusMutex);
return m_status;
@@ -472,42 +473,42 @@ bool ArenaSimulation::isFinished() const
return m_finished;
}
std::optional<int> ArenaSimulation::getWinnerTeam() const
int ArenaSimulation::winnerTeam() const
{
return m_winnerTeam;
}
Tick ArenaSimulation::getCurrentTick() const
Tick ArenaSimulation::currentTick() const
{
return m_currentTick;
}
const ArenaConfig& ArenaSimulation::getArenaConfig() const
const ArenaConfig& ArenaSimulation::arenaConfig() const
{
return m_arenaConfig;
}
const BuildingSystem& ArenaSimulation::getBuildings() const
const BuildingSystem& ArenaSimulation::buildings() const
{
return *m_buildingSystem;
}
const ShipSystem& ArenaSimulation::getShips() const
const ShipSystem& ArenaSimulation::ships() const
{
return *m_shipSystem;
}
const ScrapSystem& ArenaSimulation::getScraps() const
const ScrapSystem& ArenaSimulation::scraps() const
{
return *m_scrapSystem;
}
EntityAdmin& ArenaSimulation::getAdmin()
EntityAdmin& ArenaSimulation::admin()
{
return m_admin;
}
const EntityAdmin& ArenaSimulation::getAdmin() const
const EntityAdmin& ArenaSimulation::admin() const
{
return m_admin;
}

View File

@@ -46,19 +46,19 @@ struct ArenaStatus
double threatLevel = 0.0; // accumulated threat of the team's configured ships
// Remaining durability of the team's ships and defence stations (HQ
// excluded). currentEhp is summed live; maxEhp is the fixed full-HP
// baseline. See getEhpPercentText() for the displayed value.
// baseline. See ehpPercentText() for the displayed value.
double currentEhp = 0.0;
double maxEhp = 0.0;
std::vector<Entry> entries; // HQ first, then ships, then stations
// Remaining EHP as a whole-number percentage ("NN%"), or "n/a" when the
// team has no ships or stations (maxEhp == 0).
std::string getEhpPercentText() const;
std::string ehpPercentText() const;
};
TeamStatus teams[2];
bool finished = false;
std::optional<int> winnerTeam; // 0 or 1 when finished; nullopt while running
int winnerTeam = -1; // 0 or 1 when finished; -1 while running
// Game time the fight has lasted (simulated ticks * fixed tick duration).
// Meaningful once finished; the battle duration shown for completed runs.
double durationSeconds = 0.0;
@@ -78,17 +78,17 @@ public:
void tickOnce();
std::vector<BeamFiredEvent> drainBeamFiredEvents();
ArenaStatus getStatus() const;
ArenaStatus status() const;
bool isFinished() const;
std::optional<int> getWinnerTeam() const;
Tick getCurrentTick() const;
int winnerTeam() const;
Tick currentTick() const;
const ArenaConfig& getArenaConfig() const;
const BuildingSystem& getBuildings() const;
const ShipSystem& getShips() const;
const ScrapSystem& getScraps() const;
EntityAdmin& getAdmin();
const EntityAdmin& getAdmin() const;
const ArenaConfig& arenaConfig() const;
const BuildingSystem& buildings() const;
const ShipSystem& ships() const;
const ScrapSystem& scraps() const;
EntityAdmin& admin();
const EntityAdmin& admin() const;
private:
BuildingId allocateBuildingId();
@@ -122,7 +122,7 @@ private:
entt::entity m_team2HqEntity;
bool m_finished;
std::optional<int> m_winnerTeam;
int m_winnerTeam;
std::atomic<bool> m_stopRequested;
// Static accumulated threat per team, computed once from the configured roster.

View File

@@ -15,7 +15,7 @@
#include "Building.h"
#include "BuildingSystem.h"
#include "EntityHitTest.h"
#include "EntitySelectionChangedEvent.h"
#include "EntitySelectedEvent.h"
#include "EventManager.h"
#include "FacingComponent.h"
#include "FactionComponent.h"
@@ -73,7 +73,7 @@ void ArenaView::setGameSpeed(double multiplier)
std::make_shared<GameSpeedChangedEvent>(multiplier));
}
double ArenaView::getGameSpeed() const
double ArenaView::gameSpeed() const
{
return m_gameSpeedMultiplier;
}
@@ -121,7 +121,7 @@ void ArenaView::onFrame()
// Expire old beams. Lifetime is measured in game ticks so beams stay
// visible while the simulation is paused or slowed (REQ-SHP-FIRING-BEAM).
{
const Tick now = m_sim->getCurrentTick();
const Tick now = m_sim->currentTick();
std::vector<ActiveBeam> live;
for (const ActiveBeam& b : m_activeBeams)
{
@@ -144,16 +144,16 @@ void ArenaView::onFrame()
void ArenaView::handleEvent(std::shared_ptr<const BeamFiredEvent> event)
{
float maxRadius = 0.125f;
if (m_sim->getAdmin().isValid(event->target)
&& m_sim->getAdmin().hasAll<StationBodyComponent>(event->target))
if (m_sim->admin().isValid(event->target)
&& m_sim->admin().hasAll<StationBodyComponent>(event->target))
{
const StationBodyComponent& sb = m_sim->getAdmin().get<StationBodyComponent>(event->target);
const StationBodyComponent& sb = m_sim->admin().get<StationBodyComponent>(event->target);
const int shorter = std::min(sb.footprint.width(),
sb.footprint.height());
maxRadius = shorter / 2.0f;
}
else if (m_sim->getAdmin().isValid(event->target)
&& m_sim->getAdmin().hasAll<ScrapDataComponent>(event->target))
else if (m_sim->admin().isValid(event->target)
&& m_sim->admin().hasAll<ScrapDataComponent>(event->target))
{
maxRadius = 0.1f;
}
@@ -192,9 +192,9 @@ void ArenaView::paintGL()
// Coordinate helpers
// ---------------------------------------------------------------------------
float ArenaView::getTilePx() const
float ArenaView::tilePx() const
{
const ArenaConfig& ac = m_sim->getArenaConfig();
const ArenaConfig& ac = m_sim->arenaConfig();
const int totalWidth = ac.playerBufferWidth_tiles
+ ac.contestZoneWidth_tiles
+ ac.enemyBufferWidth_tiles;
@@ -209,8 +209,8 @@ float ArenaView::getTilePx() const
QPointF ArenaView::worldToWidget(QVector2D worldPos) const
{
return QPointF(
static_cast<qreal>(worldPos.x() * getTilePx()),
static_cast<qreal>(worldPos.y() * getTilePx()));
static_cast<qreal>(worldPos.x() * tilePx()),
static_cast<qreal>(worldPos.y() * tilePx()));
}
QPointF ArenaView::tileToWidget(QPoint tile) const
@@ -223,21 +223,21 @@ QRectF ArenaView::tileRect(QPoint tile) const
{
const QPointF tl = tileToWidget(tile);
return QRectF(tl.x(), tl.y(),
static_cast<qreal>(getTilePx()), static_cast<qreal>(getTilePx()));
static_cast<qreal>(tilePx()), static_cast<qreal>(tilePx()));
}
std::optional<QVector2D> ArenaView::entityPosition(entt::entity entity) const
{
if (!m_sim->getAdmin().isValid(entity) || !m_sim->getAdmin().hasAll<PositionComponent>(entity))
if (!m_sim->admin().isValid(entity) || !m_sim->admin().hasAll<PositionComponent>(entity))
{
return std::nullopt;
}
return m_sim->getAdmin().get<PositionComponent>(entity).value;
return m_sim->admin().get<PositionComponent>(entity).value;
}
QVector2D ArenaView::widgetToWorld(QPoint widgetPt) const
{
const float px = getTilePx();
const float px = tilePx();
if (px < 0.001f) { return QVector2D(0.0f, 0.0f); }
return QVector2D(static_cast<float>(widgetPt.x()) / px,
static_cast<float>(widgetPt.y()) / px);
@@ -248,7 +248,7 @@ void ArenaView::mousePressEvent(QMouseEvent* event)
if (event->button() == Qt::LeftButton)
{
const QVector2D worldPos = widgetToWorld(event->pos());
entt::entity hit = entityAtWorldPos(m_sim->getAdmin(), worldPos);
entt::entity hit = entityAtWorldPos(m_sim->admin(), worldPos);
if (hit != entt::null)
{
@@ -259,14 +259,8 @@ void ArenaView::mousePressEvent(QMouseEvent* event)
m_selectedEntity = std::nullopt;
}
// The arena is strictly single-select; emit a vector of size 0 or 1.
std::vector<entt::entity> selection;
if (m_selectedEntity.has_value())
{
selection.push_back(*m_selectedEntity);
}
EventManager::getInstance()->sendEventImmediately(
std::make_shared<EntitySelectionChangedEvent>(selection));
std::make_shared<EntitySelectedEvent>(m_selectedEntity));
}
QOpenGLWidget::mousePressEvent(event);
@@ -288,7 +282,7 @@ void ArenaView::keyPressEvent(QKeyEvent* event)
void ArenaView::drawTiles(QPainter& painter)
{
const ArenaConfig& ac = m_sim->getArenaConfig();
const ArenaConfig& ac = m_sim->arenaConfig();
const int totalWidth = ac.playerBufferWidth_tiles
+ ac.contestZoneWidth_tiles
+ ac.enemyBufferWidth_tiles;
@@ -306,7 +300,7 @@ void ArenaView::drawTiles(QPainter& painter)
void ArenaView::drawBuildings(QPainter& painter)
{
for (const Building& b : m_sim->getBuildings().getAllBuildings())
for (const Building& b : m_sim->buildings().allBuildings())
{
const std::map<BuildingType, BuildingVisuals>::const_iterator it =
m_visuals->buildings.find(b.type);
@@ -321,8 +315,8 @@ void ArenaView::drawBuildings(QPainter& painter)
const QPointF tl = tileToWidget(b.anchor);
const QRectF bboxRect(tl.x(), tl.y(),
b.footprint.width() * static_cast<qreal>(getTilePx()),
b.footprint.height() * static_cast<qreal>(getTilePx()));
b.footprint.width() * static_cast<qreal>(tilePx()),
b.footprint.height() * static_cast<qreal>(tilePx()));
painter.setPen(QPen(bv.outline, 1));
painter.setBrush(Qt::NoBrush);
@@ -338,8 +332,8 @@ void ArenaView::drawBuildings(QPainter& painter)
void ArenaView::drawScrap(QPainter& painter)
{
const float r = getTilePx() * 0.2f;
for (const ScrapInfo& scrap : m_sim->getScraps().getAllScrapInfo())
const float r = tilePx() * 0.2f;
for (const ScrapInfo& scrap : m_sim->scraps().allScrapInfo())
{
const QPointF center = worldToWidget(scrap.position);
painter.setBrush(QColor(128, 110, 90));
@@ -351,7 +345,7 @@ void ArenaView::drawScrap(QPainter& painter)
void ArenaView::drawStations(QPainter& painter)
{
m_sim->getAdmin().forEach<StationBodyComponent, FactionComponent, HealthComponent>(
m_sim->admin().forEach<StationBodyComponent, FactionComponent, HealthComponent>(
[&](entt::entity e, const StationBodyComponent& sb, const FactionComponent& f, const HealthComponent& h)
{
const BuildingType visType = f.isEnemy
@@ -370,8 +364,8 @@ void ArenaView::drawStations(QPainter& painter)
const QPointF tl = tileToWidget(sb.anchor);
const QRectF bboxRect(tl.x(), tl.y(),
sb.footprint.width() * static_cast<qreal>(getTilePx()),
sb.footprint.height() * static_cast<qreal>(getTilePx()));
sb.footprint.width() * static_cast<qreal>(tilePx()),
sb.footprint.height() * static_cast<qreal>(tilePx()));
painter.setPen(QPen(bv.outline, 1));
painter.setBrush(Qt::NoBrush);
@@ -380,7 +374,7 @@ void ArenaView::drawStations(QPainter& painter)
if (h.maxHp > 0.0f)
{
const float fraction = std::max(0.0f, h.hp / h.maxHp);
const qreal barH = static_cast<qreal>(getTilePx()) * 0.12;
const qreal barH = static_cast<qreal>(tilePx()) * 0.12;
const qreal barY = bboxRect.bottom() + 1.0;
const qreal barW = bboxRect.width();
painter.fillRect(QRectF(bboxRect.left(), barY, barW, barH),
@@ -400,7 +394,7 @@ void ArenaView::drawStations(QPainter& painter)
void ArenaView::drawShips(QPainter& painter)
{
m_sim->getAdmin().forEach<ShipIdentityComponent, PositionComponent, FacingComponent,
m_sim->admin().forEach<ShipIdentityComponent, PositionComponent, FacingComponent,
FactionComponent, HealthComponent>(
[&](entt::entity e, const ShipIdentityComponent& si,
const PositionComponent& pos, const FacingComponent& facing,
@@ -414,8 +408,8 @@ void ArenaView::drawShips(QPainter& painter)
const QVector2D dir(std::cos(facing.radians), std::sin(facing.radians));
const QVector2D perp(-dir.y(), dir.x());
const float fwd = getTilePx() * 0.45f;
const float side = getTilePx() * 0.25f;
const float fwd = tilePx() * 0.45f;
const float side = tilePx() * 0.25f;
QPolygonF tri;
tri << QPointF(center.x() + static_cast<qreal>(dir.x() * fwd),
@@ -433,7 +427,7 @@ void ArenaView::drawShips(QPainter& painter)
{
const float fraction = std::max(0.0f, h.hp / h.maxHp);
const qreal barW = static_cast<qreal>(fwd) * 2.0;
const qreal barH = static_cast<qreal>(getTilePx()) * 0.12;
const qreal barH = static_cast<qreal>(tilePx()) * 0.12;
const qreal barX = center.x() - static_cast<qreal>(fwd);
const qreal barY = center.y() + static_cast<qreal>(fwd) + 1.0;
painter.fillRect(QRectF(barX, barY, barW, barH), QColor(60, 60, 60));
@@ -443,7 +437,7 @@ void ArenaView::drawShips(QPainter& painter)
if (m_selectedEntity.has_value() && *m_selectedEntity == e)
{
const qreal radius = static_cast<qreal>(getTilePx()) * 0.55;
const qreal radius = static_cast<qreal>(tilePx()) * 0.55;
painter.setPen(QPen(QColor(255, 255, 0), 2));
painter.setBrush(Qt::NoBrush);
painter.drawEllipse(center, radius, radius);
@@ -454,7 +448,7 @@ void ArenaView::drawShips(QPainter& painter)
void ArenaView::drawDebugSensorRanges(QPainter& painter)
{
painter.setBrush(Qt::NoBrush);
m_sim->getAdmin().forEach<ShipIdentityComponent, PositionComponent, SensorRangeComponent>(
m_sim->admin().forEach<ShipIdentityComponent, PositionComponent, SensorRangeComponent>(
[&](entt::entity /*e*/, const ShipIdentityComponent& si,
const PositionComponent& pos, const SensorRangeComponent& sensor)
{
@@ -464,7 +458,7 @@ void ArenaView::drawDebugSensorRanges(QPainter& painter)
const QPointF center = worldToWidget(pos.value);
const qreal radiusPx = static_cast<qreal>(sensor.value_tiles)
* static_cast<qreal>(getTilePx());
* static_cast<qreal>(tilePx());
QColor circleColor = it->second.outline;
circleColor.setAlpha(77);
painter.setPen(QPen(circleColor, 1));
@@ -493,7 +487,7 @@ void ArenaView::drawDebugTargetLines(QPainter& painter)
painter.drawLine(worldToWidget(from), worldToWidget(to));
};
m_sim->getAdmin().forEach<ShipIdentityComponent, PositionComponent,
m_sim->admin().forEach<ShipIdentityComponent, PositionComponent,
FactionComponent, AttackBehavior>(
[&](entt::entity /*e*/, const ShipIdentityComponent& /*si*/,
const PositionComponent& pos, const FactionComponent& fac,
@@ -508,7 +502,7 @@ void ArenaView::drawDebugTargetLines(QPainter& painter)
drawTargetLine(fac.isEnemy, pos.value, *targetPos);
});
m_sim->getAdmin().forEach<ShipIdentityComponent, PositionComponent,
m_sim->admin().forEach<ShipIdentityComponent, PositionComponent,
FactionComponent, RepairBehavior>(
[&](entt::entity /*e*/, const ShipIdentityComponent& /*si*/,
const PositionComponent& pos, const FactionComponent& fac,
@@ -523,7 +517,7 @@ void ArenaView::drawDebugTargetLines(QPainter& painter)
drawTargetLine(fac.isEnemy, pos.value, *targetPos);
});
m_sim->getAdmin().forEach<ShipIdentityComponent, PositionComponent,
m_sim->admin().forEach<ShipIdentityComponent, PositionComponent,
FactionComponent, SalvageScrapBehavior>(
[&](entt::entity /*e*/, const ShipIdentityComponent& /*si*/,
const PositionComponent& pos, const FactionComponent& fac,

View File

@@ -13,7 +13,7 @@
#include "BeamFiredEvent.h"
#include "entt/entity/entity.hpp"
#include "EntitySelectionChangedEvent.h"
#include "EntitySelectedEvent.h"
#include "Tick.h"
#include "TickDriver.h"
#include "VisualsConfig.h"
@@ -32,7 +32,7 @@ public:
~ArenaView() override;
void setGameSpeed(double multiplier);
double getGameSpeed() const;
double gameSpeed() const;
void togglePause();
void stopRendering();
@@ -56,7 +56,7 @@ private:
void drawDebugTargetLines(QPainter& painter);
void drawBeams(QPainter& painter);
float getTilePx() const;
float tilePx() const;
QPointF worldToWidget(QVector2D worldPos) const;
QPointF tileToWidget(QPoint tile) const;
QRectF tileRect(QPoint tile) const;

View File

@@ -141,7 +141,7 @@ void ArenaWidget::updateStatus(const ArenaStatus& status)
}
threat->setText(tr("Threat: %1").arg(QString::number(team.threatLevel, 'f', 0)));
ehp->setText(tr("EHP: %1").arg(QString::fromStdString(team.getEhpPercentText())));
ehp->setText(tr("EHP: %1").arg(QString::fromStdString(team.ehpPercentText())));
QString lines;
for (const ArenaStatus::Entry& entry : team.entries)

View File

@@ -46,7 +46,7 @@ namespace
header = QStringLiteral("[WON] ") + header;
}
header += QStringLiteral(" - threat %1").arg(QString::number(team.threatLevel, 'f', 0));
header += QStringLiteral(" - EHP %1").arg(QString::fromStdString(team.getEhpPercentText()));
header += QStringLiteral(" - EHP %1").arg(QString::fromStdString(team.ehpPercentText()));
return escapeCell(header);
}
@@ -76,6 +76,7 @@ BalancingWindow::BalancingWindow(const BalancingConfig& balancingConfig,
, m_balancingConfigPath(balancingConfigPath)
, m_nextSeed(0)
, m_inspectWindow(nullptr)
, m_inspectedArenaIndex(-1)
{
m_visuals = VisualsLoader::load(m_configDir + "/visuals.toml");
setWindowTitle(tr("DotaFactory — Balancing Tool"));
@@ -146,7 +147,7 @@ void BalancingWindow::populateArenas(const BalancingConfig& balancingConfig)
entry.widget = new ArenaWidget(index, arenaConfig.name, scrollContent);
contentLayout->addWidget(entry.widget);
entry.widget->updateStatus(entry.simulation->getStatus());
entry.widget->updateStatus(entry.simulation->status());
m_arenas.push_back(std::move(entry));
}
@@ -178,15 +179,15 @@ void BalancingWindow::pollStatuses()
{
if (entry.worker.joinable())
{
const ArenaStatus status = entry.simulation->getStatus();
const ArenaStatus status = entry.simulation->status();
entry.widget->updateStatus(status);
}
}
if (m_inspectedSim && m_inspectedArenaIndex.has_value())
if (m_inspectedSim && m_inspectedArenaIndex >= 0)
{
const ArenaStatus status = m_inspectedSim->getStatus();
m_arenas[static_cast<std::size_t>(*m_inspectedArenaIndex)].widget->updateStatus(status);
const ArenaStatus status = m_inspectedSim->status();
m_arenas[static_cast<std::size_t>(m_inspectedArenaIndex)].widget->updateStatus(status);
}
updateButtons();
@@ -241,7 +242,7 @@ void BalancingWindow::startArena(int index)
entry.simulation = std::make_unique<ArenaSimulation>(
m_gameConfig, entry.config, m_nextSeed++);
entry.widget->startSimulation();
entry.widget->updateStatus(entry.simulation->getStatus());
entry.widget->updateStatus(entry.simulation->status());
ArenaSimulation* sim = entry.simulation.get();
entry.worker = std::thread([sim]() { sim->run(); });
updateButtons();
@@ -254,13 +255,13 @@ void BalancingWindow::inspectArena(int index)
delete m_inspectWindow;
m_inspectWindow = nullptr;
if (m_inspectedSim && m_inspectedArenaIndex.has_value()
if (m_inspectedSim && m_inspectedArenaIndex >= 0
&& !m_inspectedSim->isFinished())
{
m_arenas[static_cast<std::size_t>(*m_inspectedArenaIndex)].widget->resetToGrey();
m_arenas[static_cast<std::size_t>(m_inspectedArenaIndex)].widget->resetToGrey();
}
m_inspectedSim.reset();
m_inspectedArenaIndex = std::nullopt;
m_inspectedArenaIndex = -1;
}
ArenaEntry& entry = m_arenas[static_cast<std::size_t>(index)];
@@ -277,7 +278,7 @@ void BalancingWindow::inspectArena(int index)
entry.widget->resetToGrey();
entry.widget->startSimulation();
entry.widget->updateStatus(m_inspectedSim->getStatus());
entry.widget->updateStatus(m_inspectedSim->status());
m_inspectWindow = new InspectWindow(
m_inspectedSim.get(), &m_gameConfig, &m_visuals, entry.config.name, nullptr);
@@ -296,16 +297,16 @@ void BalancingWindow::closeInspectWindow()
m_inspectWindow->deleteLater();
m_inspectWindow = nullptr;
if (m_inspectedArenaIndex.has_value() && m_inspectedSim)
if (m_inspectedArenaIndex >= 0 && m_inspectedSim)
{
if (!m_inspectedSim->isFinished())
{
m_arenas[static_cast<std::size_t>(*m_inspectedArenaIndex)].widget->resetToGrey();
m_arenas[static_cast<std::size_t>(m_inspectedArenaIndex)].widget->resetToGrey();
}
}
m_inspectedSim.reset();
m_inspectedArenaIndex = std::nullopt;
m_inspectedArenaIndex = -1;
setMainControlsEnabled(true);
updateButtons();
}
@@ -335,7 +336,7 @@ void BalancingWindow::updateButtons()
bool allRunning = true;
for (ArenaEntry& entry : m_arenas)
{
if (entry.worker.joinable() && !entry.simulation->getStatus().finished)
if (entry.worker.joinable() && !entry.simulation->status().finished)
{
anyRunning = true;
}

View File

@@ -1,7 +1,6 @@
#pragma once
#include <memory>
#include <optional>
#include <string>
#include <thread>
#include <vector>
@@ -79,6 +78,6 @@ private:
QTimer* m_pollTimer;
InspectWindow* m_inspectWindow;
std::optional<int> m_inspectedArenaIndex; // nullopt = no arena inspected
int m_inspectedArenaIndex;
std::unique_ptr<ArenaSimulation> m_inspectedSim;
};

View File

@@ -14,7 +14,6 @@
#include "HealthComponent.h"
#include "InspectWindowClosedEvent.h"
#include "ModuleOwnerComponent.h"
#include "SelectedBehaviorComponent.h"
#include "ShipIdentityComponent.h"
#include "ShipStatsCalculator.h"
#include "ShipStatsPanel.h"
@@ -199,7 +198,7 @@ void InspectWindow::handleEvent(std::shared_ptr<const GameSpeedChangedEvent> eve
void InspectWindow::pollStatus()
{
const ArenaStatus status = m_sim->getStatus();
const ArenaStatus status = m_sim->status();
updateInfoPanel(status);
refreshEntityStats();
}
@@ -228,7 +227,7 @@ void InspectWindow::updateInfoPanel(const ArenaStatus& status)
}
threat->setText(tr("Threat: %1").arg(QString::number(team.threatLevel, 'f', 0)));
ehp->setText(tr("EHP: %1").arg(QString::fromStdString(team.getEhpPercentText())));
ehp->setText(tr("EHP: %1").arg(QString::fromStdString(team.ehpPercentText())));
QString lines;
for (const ArenaStatus::Entry& entry : team.entries)
@@ -250,14 +249,13 @@ void InspectWindow::updateInfoPanel(const ArenaStatus& status)
}
}
void InspectWindow::handleEvent(std::shared_ptr<const EntitySelectionChangedEvent> event)
void InspectWindow::handleEvent(std::shared_ptr<const EntitySelectedEvent> event)
{
if (!event->entities.empty())
if (event->entity.has_value())
{
// The arena is single-select, so only the first entity is inspected.
m_selectedEntity = event->entities.front();
m_selectedEntity = event->entity;
EntityAdmin& admin = m_sim->getAdmin();
EntityAdmin& admin = m_sim->admin();
entt::entity entity = *m_selectedEntity;
if (!admin.isValid(entity))
@@ -280,8 +278,6 @@ void InspectWindow::handleEvent(std::shared_ptr<const EntitySelectionChangedEven
const ShipStats stats = buildShipStatsFromEntity(admin, entity);
m_entityStatsPanel->refreshFromLive(stats, health.hp);
m_entityStatsPanel->setBehavior(
admin.get<SelectedBehaviorComponent>(entity).winner);
m_entityStatsPanel->show();
m_stationStatsLabel->hide();
}
@@ -333,7 +329,7 @@ void InspectWindow::refreshEntityStats()
{
if (!m_selectedEntity.has_value()) { return; }
EntityAdmin& admin = m_sim->getAdmin();
EntityAdmin& admin = m_sim->admin();
entt::entity entity = *m_selectedEntity;
if (!admin.isValid(entity))
@@ -359,8 +355,6 @@ void InspectWindow::refreshEntityStats()
{
const ShipStats stats = buildShipStatsFromEntity(admin, entity);
m_entityStatsPanel->refreshFromLive(stats, health.hp);
m_entityStatsPanel->setBehavior(
admin.get<SelectedBehaviorComponent>(entity).winner);
}
else if (admin.hasAll<StationBodyComponent>(entity))
{

View File

@@ -12,7 +12,7 @@
#include "entt/entity/entity.hpp"
#include "ArenaSimulation.h"
#include "EntitySelectionChangedEvent.h"
#include "EntitySelectedEvent.h"
#include "EventHandler.h"
#include "GameConfig.h"
#include "GameSpeedChangedEvent.h"
@@ -22,7 +22,7 @@ class ArenaView;
class ShipStatsPanel;
class InspectWindow : public QWidget,
public CombinedEventHandler<EntitySelectionChangedEvent,
public CombinedEventHandler<EntitySelectedEvent,
GameSpeedChangedEvent>
{
Q_OBJECT
@@ -38,7 +38,7 @@ protected:
void keyPressEvent(QKeyEvent* event) override;
private:
void handleEvent(std::shared_ptr<const EntitySelectionChangedEvent> event) override;
void handleEvent(std::shared_ptr<const EntitySelectedEvent> event) override;
void handleEvent(std::shared_ptr<const GameSpeedChangedEvent> event) override;
private slots:

View File

@@ -1,6 +1,5 @@
#pragma once
#include <optional>
#include <string>
#include <vector>
@@ -19,30 +18,9 @@ struct BuildingDef
// Stored as raw strings here; parsing into per-cell tiles + output ports
// happens when buildings are placed, not at load time.
std::vector<std::string> surfaceMask;
// Output-buffer holding size for buildings without a recipe-driven buffer.
// Only the Salvage Bay sets this (REQ-BLD-SALVAGE-BAY).
std::optional<int> outputBufferCapacity;
// Optional hover-tooltip text for the build button (REQ-UI-BUILD-TOOLTIP).
std::optional<std::string> tooltip;
};
struct BuildingsConfig
{
std::vector<BuildingDef> buildings;
// Returns the definition for the given building type, or nullptr if the
// type has no entry in buildings.toml.
const BuildingDef* findBuildingDef(BuildingType type) const
{
for (const BuildingDef& def : buildings)
{
if (def.type == type)
{
return &def;
}
}
return nullptr;
}
};

View File

@@ -8,7 +8,6 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/StationsConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/GameConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/ModulesConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/UnlocksConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/ConfigLoader.h
${CMAKE_CURRENT_SOURCE_DIR}/SurfaceMask.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintSerializer.h

View File

@@ -263,7 +263,6 @@ WorldConfig ConfigLoader::loadWorld(const std::string& path)
cfg.heightTiles = static_cast<int>(requireInt(tbl["world"]["height_tiles"], file, "world.height_tiles"));
cfg.refundPercentage = static_cast<int>(requireInt(tbl["world"]["refund_percentage"], file, "world.refund_percentage"));
cfg.deconstructionTimeSeconds = requireDouble(tbl["world"]["deconstruction_time_seconds"], file, "world.deconstruction_time_seconds");
cfg.startingBuildingBlocks = static_cast<int>(requireInt(tbl["world"]["starting_building_blocks"], file, "world.starting_building_blocks"));
cfg.scrapDespawnSeconds = requireDouble(tbl["world"]["scrap_despawn_seconds"], file, "world.scrap_despawn_seconds");
cfg.scrapPerThreat = requireDouble(tbl["world"]["scrap_per_threat"], file, "world.scrap_per_threat");
@@ -274,18 +273,6 @@ WorldConfig ConfigLoader::loadWorld(const std::string& path)
cfg.orbitFactor = requireDouble(tbl["world"]["orbit_factor"], file, "world.orbit_factor");
cfg.rallyOrbitRadius_tiles = requireDouble(tbl["world"]["rally_orbit_radius_tiles"], file, "world.rally_orbit_radius_tiles");
if (const std::optional<std::string> tip =
tbl["world"]["building_blocks_tooltip"].value<std::string>())
{
cfg.buildingBlocksTooltip = *tip;
}
if (const std::optional<std::string> tip =
tbl["world"]["artifact_tooltip"].value<std::string>())
{
cfg.artifactTooltip = *tip;
}
cfg.regions.asteroidWidth_tiles = static_cast<int>(requireInt(tbl["regions"]["asteroid_width_tiles"], file, "regions.asteroid_width_tiles"));
cfg.regions.playerBufferWidth_tiles = static_cast<int>(requireInt(tbl["regions"]["player_buffer_width_tiles"], file, "regions.player_buffer_width_tiles"));
cfg.regions.contestZoneWidth_tiles = static_cast<int>(requireInt(tbl["regions"]["contest_zone_width_tiles"], file, "regions.contest_zone_width_tiles"));
@@ -318,10 +305,6 @@ WorldConfig ConfigLoader::loadWorld(const std::string& path)
cfg.artifacts.artifactChanceFormula = requireFormula(tbl["artifacts"]["artifact_chance_formula"], file, "artifacts.artifact_chance_formula");
cfg.artifacts.artifactWinCount = static_cast<int>(requireInt(tbl["artifacts"]["artifact_win_count"], file, "artifacts.artifact_win_count"));
cfg.scroll.panSpeedSlow_tps = requireDouble(tbl["scroll"]["pan_speed_slow_tiles_per_second"], file, "scroll.pan_speed_slow_tiles_per_second");
cfg.scroll.panSpeedFast_tps = requireDouble(tbl["scroll"]["pan_speed_fast_tiles_per_second"], file, "scroll.pan_speed_fast_tiles_per_second");
cfg.scroll.panRampBandWidth_tiles = static_cast<int>(requireInt(tbl["scroll"]["pan_ramp_band_width_tiles"], file, "scroll.pan_ramp_band_width_tiles"));
return cfg;
}
@@ -350,17 +333,6 @@ BuildingsConfig ConfigLoader::loadBuildings(const std::string& path)
def.constructionTimeSeconds = requireDouble(mt["construction_time_seconds"], file, elemPath + ".construction_time_seconds");
def.surfaceMask = requireStringArray(mt["surface_mask"], file, elemPath + ".surface_mask");
if (mt.contains("output_buffer_capacity"))
{
def.outputBufferCapacity = static_cast<int>(
requireInt(mt["output_buffer_capacity"], file, elemPath + ".output_buffer_capacity"));
}
if (mt.contains("tooltip"))
{
def.tooltip = requireString(mt["tooltip"], file, elemPath + ".tooltip");
}
const std::optional<BuildingType> parsedType = parseBuildingType(def.id);
if (!parsedType)
{
@@ -405,10 +377,18 @@ RecipesConfig ConfigLoader::loadRecipes(const std::string& path)
}
def.building = *parsedType;
if (def.building == BuildingType::Assembler && mt.contains("unlocked_at_start"))
if (def.building == BuildingType::Assembler)
{
def.unlockedAtStart = requireBool(mt["unlocked_at_start"], file,
elemPath + ".unlocked_at_start");
const auto level = mt["unlock_at_station_level"].value<int64_t>();
if (level)
{
def.unlockAtStationLevel = static_cast<int>(*level);
}
if (mt.contains("unlock_requires"))
{
def.unlockRequires = requireStringArray(mt["unlock_requires"], file,
elemPath + ".unlock_requires");
}
}
// inputs may be omitted (e.g. miner recipes). An empty array is fine.
@@ -447,6 +427,11 @@ ShipsConfig ConfigLoader::loadShips(const std::string& path)
ShipDef def;
def.id = requireString(mt["id"], file, elemPath + ".id");
def.unlockAtStationLevel = static_cast<int>(requireInt(mt["unlock_at_station_level"], file, elemPath + ".unlock_at_station_level"));
if (mt.contains("unlock_requires"))
{
def.unlockRequires = requireStringArray(mt["unlock_requires"], file, elemPath + ".unlock_requires");
}
def.layout = requireStringArray(mt["layout"], file, elemPath + ".layout");
// Schematic
@@ -596,17 +581,18 @@ ModulesConfig ConfigLoader::loadModules(const std::string& path)
ModuleDef def;
def.id = requireString(mt["id"], file, elemPath + ".id");
def.unlockAtStationLevel = static_cast<int>(
mt["unlock_at_station_level"].value_or<int64_t>(-1));
if (mt.contains("unlock_requires"))
{
def.unlockRequires = requireStringArray(mt["unlock_requires"], file, elemPath + ".unlock_requires");
}
def.surfaceMask = requireStringArray(mt["surface_mask"], file, elemPath + ".surface_mask");
def.productionTimeSeconds = requireDouble(
mt["production_time_seconds"], file, elemPath + ".production_time_seconds");
def.fillColor = requireString(mt["fill_color"], file, elemPath + ".fill_color");
def.glyph = requireString(mt["glyph"], file, elemPath + ".glyph");
if (mt.contains("tooltip"))
{
def.tooltip = requireString(mt["tooltip"], file, elemPath + ".tooltip");
}
// Materials
{
const toml::array& materials = requireArray(mt["materials"], file, elemPath + ".materials");
@@ -713,141 +699,62 @@ ModulesConfig ConfigLoader::loadModules(const std::string& path)
return cfg;
}
UnlocksConfig ConfigLoader::loadUnlocks(const std::string& path)
{
const std::string file = "unlocks.toml";
toml::table tbl = parseFile(path, file);
UnlocksConfig cfg;
if (!tbl.contains("unlock"))
{
return cfg;
}
const toml::array& arr = requireArray(tbl["unlock"], file, "unlock");
for (std::size_t i = 0; i < arr.size(); ++i)
{
const std::string elemPath = "unlock[" + std::to_string(i) + "]";
const toml::table* ut = arr[i].as_table();
if (ut == nullptr)
{
throw makeError(file, elemPath, "not a table");
}
toml::table& mt = const_cast<toml::table&>(*ut);
UnlockGroupDef def;
def.id = requireString(mt["id"], file, elemPath + ".id");
def.stationLevel = static_cast<int>(
requireInt(mt["station_level"], file, elemPath + ".station_level"));
if (mt.contains("requires"))
{
def.requiredGroupIds = requireStringArray(mt["requires"], file, elemPath + ".requires");
}
if (mt.contains("ships"))
{
def.ships = requireStringArray(mt["ships"], file, elemPath + ".ships");
}
if (mt.contains("modules"))
{
def.modules = requireStringArray(mt["modules"], file, elemPath + ".modules");
}
if (mt.contains("buildings"))
{
def.buildings = requireStringArray(mt["buildings"], file, elemPath + ".buildings");
}
if (mt.contains("recipes"))
{
def.recipes = requireStringArray(mt["recipes"], file, elemPath + ".recipes");
}
cfg.groups.push_back(std::move(def));
}
return cfg;
}
namespace
{
// Validates unlocks.toml against the rest of the config (REQ-LOCK-EXPLICIT,
// REQ-LOCK-PREREQ): each granted id resolves to the right kind of definition
// (recipe grants must name assembler recipes), each grantable id is granted by
// at most one group, group ids are unique, every group grants at least one
// item, and every `requires` id names a defined group.
void validateUnlocks(const GameConfig& cfg)
// Throws if any id in requiredIds is not a valid explicitly-unlockable schematic.
void checkUnlockRequires(const std::vector<std::string>& requiredIds,
const std::unordered_set<std::string>& schematicIds,
const std::string& file,
const std::string& path)
{
const std::string file = "unlocks.toml";
for (const std::string& requiredId : requiredIds)
{
if (schematicIds.count(requiredId) == 0)
{
throw makeError(file, path,
"references unknown schematic '" + requiredId + "'");
}
}
}
std::unordered_set<std::string> shipIds;
for (const ShipDef& def : cfg.ships.ships) { shipIds.insert(def.id); }
std::unordered_set<std::string> moduleIds;
for (const ModuleDef& def : cfg.modules.modules) { moduleIds.insert(def.id); }
std::unordered_set<std::string> buildingIds;
for (const BuildingDef& def : cfg.buildings.buildings) { buildingIds.insert(def.id); }
std::unordered_set<std::string> assemblerRecipeIds;
// Validates that every id listed in an `unlock_requires` (REQ-LOCK-PREREQ)
// resolves to an explicitly-unlockable schematic: a ship, a module, or an
// assembler recipe that carries `unlock_at_station_level` (a recipe schematic,
// per REQ-LOCK-EXPLICIT). An unresolved id is a config error surfaced at load.
void validateUnlockRequires(const GameConfig& cfg)
{
std::unordered_set<std::string> schematicIds;
for (const ShipDef& def : cfg.ships.ships)
{
schematicIds.insert(def.id);
}
for (const ModuleDef& def : cfg.modules.modules)
{
schematicIds.insert(def.id);
}
for (const RecipeDef& def : cfg.recipes.recipes)
{
if (def.building == BuildingType::Assembler) { assemblerRecipeIds.insert(def.id); }
if (def.building == BuildingType::Assembler && def.unlockAtStationLevel.has_value())
{
schematicIds.insert(def.id);
}
}
std::unordered_set<std::string> groupIds;
std::unordered_set<std::string> grantedShipIds;
std::unordered_set<std::string> grantedModuleIds;
std::unordered_set<std::string> grantedBuildingIds;
std::unordered_set<std::string> grantedRecipeIds;
const auto checkGrants = [&](const std::vector<std::string>& ids,
const std::unordered_set<std::string>& valid,
std::unordered_set<std::string>& granted,
const std::string& kind,
const std::string& gPath)
for (const ShipDef& def : cfg.ships.ships)
{
for (const std::string& id : ids)
{
if (valid.count(id) == 0)
{
throw makeError(file, gPath, "grants unknown " + kind + " '" + id + "'");
}
if (!granted.insert(id).second)
{
throw makeError(file, gPath,
"grants " + kind + " '" + id + "' which is already granted by another unlock group");
}
}
};
for (const UnlockGroupDef& group : cfg.unlocks.groups)
{
const std::string gPath = "unlock '" + group.id + "'";
if (!groupIds.insert(group.id).second)
{
throw makeError(file, gPath, "duplicate unlock group id");
}
if (group.ships.empty() && group.modules.empty()
&& group.buildings.empty() && group.recipes.empty())
{
throw makeError(file, gPath, "grants no items (must grant at least one)");
}
checkGrants(group.ships, shipIds, grantedShipIds, "ship", gPath);
checkGrants(group.modules, moduleIds, grantedModuleIds, "module", gPath);
checkGrants(group.buildings, buildingIds, grantedBuildingIds, "building", gPath);
checkGrants(group.recipes, assemblerRecipeIds, grantedRecipeIds, "assembler recipe", gPath);
checkUnlockRequires(def.unlockRequires, schematicIds, "ships.toml",
"ship '" + def.id + "'.unlock_requires");
}
// requires must reference defined group ids (checked once all group ids known).
for (const UnlockGroupDef& group : cfg.unlocks.groups)
for (const ModuleDef& def : cfg.modules.modules)
{
for (const std::string& req : group.requiredGroupIds)
{
if (groupIds.count(req) == 0)
{
throw makeError(file, "unlock '" + group.id + "'.requires",
"references unknown unlock group '" + req + "'");
}
}
checkUnlockRequires(def.unlockRequires, schematicIds, "modules.toml",
"module '" + def.id + "'.unlock_requires");
}
for (const RecipeDef& def : cfg.recipes.recipes)
{
checkUnlockRequires(def.unlockRequires, schematicIds, "recipes.toml",
"recipe '" + def.id + "'.unlock_requires");
}
}
@@ -862,8 +769,7 @@ GameConfig ConfigLoader::loadFromDirectory(const std::string& configDir)
cfg.ships = loadShips(configDir + "/ships.toml");
cfg.stations = loadStations(configDir + "/stations.toml");
cfg.modules = loadModules(configDir + "/modules.toml");
cfg.unlocks = loadUnlocks(configDir + "/unlocks.toml");
validateUnlocks(cfg);
validateUnlockRequires(cfg);
cfg.threatCosts = computeThreatCostTable(cfg);
return cfg;
}

View File

@@ -22,5 +22,4 @@ public:
static ShipsConfig loadShips(const std::string& path);
static StationsConfig loadStations(const std::string& path);
static ModulesConfig loadModules(const std::string& path);
static UnlocksConfig loadUnlocks(const std::string& path);
};

View File

@@ -30,7 +30,7 @@ public:
// Evaluates the expression at the given x. Requires a compiled formula.
double evaluate(double x) const;
const std::string& getSource() const { return m_source; }
const std::string& source() const { return m_source; }
bool isValid() const { return m_expr != nullptr; }
private:

View File

@@ -6,7 +6,6 @@
#include "ShipsConfig.h"
#include "StationsConfig.h"
#include "ModulesConfig.h"
#include "UnlocksConfig.h"
#include "ThreatCostCalculator.h"
// Aggregate of all simulation config files. Loaded at startup and reloaded
@@ -19,6 +18,5 @@ struct GameConfig
ShipsConfig ships;
StationsConfig stations;
ModulesConfig modules;
UnlocksConfig unlocks;
ThreatCostTable threatCosts;
};

View File

@@ -40,6 +40,10 @@ struct ModuleRepairCapability
struct ModuleDef
{
std::string id;
int unlockAtStationLevel;
// Prerequisite schematic ids that must be explicitly unlocked before this
// schematic can enter the drop pool (REQ-LOCK-PREREQ). Empty = none.
std::vector<std::string> unlockRequires;
std::vector<std::string> surfaceMask;
std::vector<RecipeIngredient> materials;
double productionTimeSeconds;
@@ -50,10 +54,6 @@ struct ModuleDef
std::optional<ModuleWeaponCapability> weaponCapability;
std::optional<ModuleSalvageCapability> salvageCapability;
std::optional<ModuleRepairCapability> repairCapability;
// Optional hover-tooltip text for the module selection button
// (REQ-MOD-UI-MODULE-TOOLTIP).
std::optional<std::string> tooltip;
};
struct ModulesConfig

View File

@@ -32,12 +32,14 @@ struct RecipeDef
std::vector<RecipeIngredient> inputs;
std::vector<RecipeOutput> outputs;
double durationSeconds;
// Assembler only. When true, this recipe is available from game start
// regardless of the implicit item graph — used for base recipes that no
// schematic's materials reach (e.g. building blocks). See REQ-LOCK-IMPLICIT.
// Otherwise an assembler recipe is either explicitly gated (granted by an
// unlock group, REQ-LOCK-EXPLICIT) or implicitly gated via the item graph.
bool unlockedAtStart = false;
// Assembler only. nullopt = implicit-only locking. -1 = explicitly unlocked
// at game start. >= 0 = locked; schematic enters drop pool at that station
// level once the output item is implicitly unlocked (REQ-LOCK-EXPLICIT).
std::optional<int> unlockAtStationLevel;
// Assembler recipe schematics only. Prerequisite schematic ids that must be
// explicitly unlocked before this schematic can enter the drop pool
// (REQ-LOCK-PREREQ). Empty = none.
std::vector<std::string> unlockRequires;
};
struct RecipesConfig

View File

@@ -35,6 +35,10 @@ struct ShipSensor
struct ShipDef
{
std::string id;
int unlockAtStationLevel;
// Prerequisite schematic ids that must be explicitly unlocked before this
// schematic can enter the drop pool (REQ-LOCK-PREREQ). Empty = none.
std::vector<std::string> unlockRequires;
std::vector<std::string> layout;
ShipSchematic schematic;

View File

@@ -1,26 +0,0 @@
#pragma once
#include <string>
#include <vector>
// A single [[unlock]] entry from unlocks.toml — an unlock group, the unit of
// loot awarded by defence station drops (REQ-DEF-SCHEMATIC-DROP,
// REQ-LOCK-EXPLICIT). Awarding a group unlocks all of its granted members at
// once. Anything not granted by any group is available from game start.
struct UnlockGroupDef
{
std::string id; // Unique unlock-group id.
int stationLevel; // Min destroyed station level to become eligible.
std::vector<std::string> requiredGroupIds; // Prerequisite unlock-group ids (REQ-LOCK-PREREQ).
// Granted ids by kind (each defaults to empty; a group grants >= 1 item).
std::vector<std::string> ships;
std::vector<std::string> modules;
std::vector<std::string> buildings;
std::vector<std::string> recipes; // Assembler recipe ids only.
};
struct UnlocksConfig
{
std::vector<UnlockGroupDef> groups;
};

View File

@@ -1,8 +1,5 @@
#pragma once
#include <optional>
#include <string>
#include "Formula.h"
// Region widths are in tiles (REQ-GW-REGIONS).
@@ -56,19 +53,10 @@ struct WorldArtifacts
int artifactWinCount;
};
// View pan speed (REQ-UI-SCROLL-SPEED). Presentation-only; the simulation ignores these.
struct WorldScroll
{
double panSpeedSlow_tps; // tiles/s, used outside the contest zone
double panSpeedFast_tps; // tiles/s, used inside the contest zone
int panRampBandWidth_tiles; // full width of the ramp band straddling each contest-zone boundary
};
struct WorldConfig
{
int heightTiles; // REQ-GW-HEIGHT
int refundPercentage; // REQ-BLD-DECONSTRUCT
double deconstructionTimeSeconds; // REQ-BLD-DECON-QUEUE
int refundPercentage; // REQ-BLD-DEMOLISH
int startingBuildingBlocks; // REQ-HQ-STARTING-BLOCKS
double scrapDespawnSeconds; // REQ-RES-SCRAP-DROP
double scrapPerThreat; // REQ-RES-SCRAP-DROP, REQ-THREAT-SCRAP (scrap dropped per unit threat)
@@ -79,19 +67,10 @@ struct WorldConfig
double orbitFactor; // REQ-SHP-ORBIT (multiplies tool range for orbit radius)
double rallyOrbitRadius_tiles; // REQ-SHP-ORBIT (fixed orbit radius around the rally point)
// Optional hover-tooltip for the header building blocks stock display
// (REQ-UI-BLOCKS-TOOLTIP). Presentation-only; the simulation ignores it.
std::optional<std::string> buildingBlocksTooltip;
// Optional hover-tooltip for the header artifact count display
// (REQ-UI-ARTIFACTS-TOOLTIP). Presentation-only; the simulation ignores it.
std::optional<std::string> artifactTooltip;
WorldRegions regions;
WorldExpansion expansion;
WorldPush push;
WorldWaves waves;
WorldTargeting targeting;
WorldArtifacts artifacts;
WorldScroll scroll;
};

View File

@@ -1,94 +0,0 @@
#include "BeltDragPath.h"
#include <cstddef>
namespace
{
int signOf(int value)
{
if (value > 0) { return 1; }
if (value < 0) { return -1; }
return 0;
}
// Direction stepping from one tile to an orthogonally adjacent tile.
Rotation directionBetween(QPoint from, QPoint to)
{
const QPoint delta = to - from;
if (delta.x() > 0) { return Rotation::East; }
if (delta.x() < 0) { return Rotation::West; }
if (delta.y() > 0) { return Rotation::South; }
return Rotation::North;
}
}
std::vector<BeltPathTile> computeBeltDragPath(QPoint anchor, QPoint cursor,
Rotation orientation)
{
const bool horizontalFirst =
(orientation == Rotation::East || orientation == Rotation::West);
// Build the ordered tile coordinates: first leg along the primary axis to the
// corner, then the orthogonal leg to the cursor (no duplicated corner tile).
std::vector<QPoint> coords;
if (horizontalFirst)
{
const int stepX = signOf(cursor.x() - anchor.x());
for (int x = anchor.x(); ; x += stepX)
{
coords.push_back(QPoint(x, anchor.y()));
if (x == cursor.x() || stepX == 0) { break; }
}
const int stepY = signOf(cursor.y() - anchor.y());
if (stepY != 0)
{
for (int y = anchor.y() + stepY; ; y += stepY)
{
coords.push_back(QPoint(cursor.x(), y));
if (y == cursor.y()) { break; }
}
}
}
else
{
const int stepY = signOf(cursor.y() - anchor.y());
for (int y = anchor.y(); ; y += stepY)
{
coords.push_back(QPoint(anchor.x(), y));
if (y == cursor.y() || stepY == 0) { break; }
}
const int stepX = signOf(cursor.x() - anchor.x());
if (stepX != 0)
{
for (int x = anchor.x() + stepX; ; x += stepX)
{
coords.push_back(QPoint(x, cursor.y()));
if (x == cursor.x()) { break; }
}
}
}
// Assign each tile the direction toward the next tile; the last tile keeps its
// incoming step direction, and a single-tile path keeps the belt orientation.
std::vector<BeltPathTile> path;
path.reserve(coords.size());
const std::size_t count = coords.size();
for (std::size_t index = 0; index < count; ++index)
{
Rotation rotation;
if (count == 1)
{
rotation = orientation;
}
else if (index + 1 < count)
{
rotation = directionBetween(coords[index], coords[index + 1]);
}
else
{
rotation = directionBetween(coords[index - 1], coords[index]);
}
path.push_back(BeltPathTile{ coords[index], rotation });
}
return path;
}

View File

@@ -1,27 +0,0 @@
#pragma once
#include <vector>
#include <QPoint>
#include "Rotation.h"
// One tile of a belt drag-placement path: the tile coordinate and the belt
// orientation it should be given (REQ-BLD-BELT-DRAG).
struct BeltPathTile
{
QPoint tile;
Rotation rotation;
};
// Computes the rectilinear (L-shaped) belt path from `anchor` to `cursor` for a
// belt whose current orientation is `orientation` (REQ-BLD-BELT-DRAG). The path
// first runs along the axis parallel to `orientation` (horizontal for East/West,
// vertical for North/South), stepping toward the cursor's coordinate on that axis
// to the corner tile, then runs along the orthogonal axis to the cursor tile. Each
// tile is oriented to point toward the next tile along the path; the final tile
// keeps the direction of its incoming step, and a single-tile path keeps
// `orientation`. Returned tiles are ordered from anchor to cursor with no duplicate
// corner tile.
std::vector<BeltPathTile> computeBeltDragPath(QPoint anchor, QPoint cursor,
Rotation orientation);

View File

@@ -11,8 +11,6 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/Port.h
${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoiceOption.h
${CMAKE_CURRENT_SOURCE_DIR}/DisplayName.h
${CMAKE_CURRENT_SOURCE_DIR}/BeltDragPath.h
${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.h
PARENT_SCOPE
)
@@ -21,8 +19,6 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/BuildingType.cpp
${CMAKE_CURRENT_SOURCE_DIR}/EntityAdmin.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DisplayName.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BeltDragPath.cpp
${CMAKE_CURRENT_SOURCE_DIR}/TunnelCompletion.cpp
PARENT_SCOPE
)

View File

@@ -3,45 +3,25 @@
#include <string>
#include <vector>
// The kind of a single granted schematic within an unlock option.
enum class SchematicType
{
Ship,
Module,
Building,
Recipe
};
// One item granted by an unlock group (REQ-LOCK-EXPLICIT), shown in the
// schematic choice dialog's granted-items list.
struct GrantedSchematic
{
SchematicType type;
std::string id;
std::string displayName;
Recipe,
Artifact
};
// One option presented to the player in the schematic choice dialog
// (REQ-DEF-SCHEMATIC-DROP). Built by the simulation when enemy stations are
// destroyed; the UI reads these to populate the dialog. A non-artifact option
// represents one unlock group; selecting it awards the whole group.
// destroyed; the UI reads these to populate the dialog.
struct SchematicChoiceOption
{
bool isArtifact = false;
// Unlock group id (empty for the artifact option).
std::string unlockGroupId;
// Display name shown as the option's title: the unlock group's derived name,
// or "Artifact" for the artifact option.
std::string schematicId;
SchematicType type;
std::string displayName;
// The ships, modules, buildings, and assembler recipes this group grants
// (empty for the artifact option).
std::vector<GrantedSchematic> grantedItems;
// Ids of miner/assembler recipes that would newly become implicitly
// unlocked (REQ-LOCK-IMPLICIT) if this option is selected. Sorted
// alphabetically by display name; empty if none.
std::vector<std::string> newlyUnlockedRecipeIds;
// Display names of items produced by recipes that would newly become
// implicitly unlocked (REQ-LOCK-IMPLICIT) if this option is selected.
// Deduplicated and sorted alphabetically; empty if none.
std::vector<std::string> newlyUnlockedItemNames;
};

View File

@@ -1,155 +0,0 @@
#include "TunnelCompletion.h"
namespace
{
QPoint stepTile(QPoint tile, Rotation dir)
{
switch (dir)
{
case Rotation::North: return {tile.x(), tile.y() - 1};
case Rotation::East: return {tile.x() + 1, tile.y() };
case Rotation::South: return {tile.x(), tile.y() + 1};
case Rotation::West: return {tile.x() - 1, tile.y() };
}
return tile;
}
Rotation oppositeRotation(Rotation dir)
{
switch (dir)
{
case Rotation::North: return Rotation::South;
case Rotation::East: return Rotation::West;
case Rotation::South: return Rotation::North;
case Rotation::West: return Rotation::East;
}
return dir;
}
float tileCenterDistanceSq(QPoint tile, QVector2D cursorWorldPos)
{
const QVector2D center(static_cast<float>(tile.x()) + 0.5f,
static_cast<float>(tile.y()) + 0.5f);
return (center - cursorWorldPos).lengthSquared();
}
} // namespace
std::optional<QPoint> firstTunnelFacing(const TunnelLookup& lookup, QPoint start,
Rotation stepDir, Rotation targetFacing,
int maxDistance)
{
QPoint probe = start;
for (int distance = 1; distance <= maxDistance; ++distance)
{
probe = stepTile(probe, stepDir);
const std::optional<TunnelTileInfo> info = lookup(probe);
if (info.has_value() && info->rotation == targetFacing)
{
return probe;
}
}
return std::nullopt;
}
TunnelCompletion resolveTunnelCompletion(const TunnelLookup& lookup, QPoint hoverTile,
Rotation rotation, int maxDistance,
QVector2D cursorWorldPos)
{
// Entry-completion: a hypothetical entry at the hovered tile searches ahead (its
// facing direction) for a same-direction exit to pair with. The first
// same-direction tunnel ahead completes the entry only if it is an exit.
std::optional<QPoint> exitPartner;
if (const std::optional<QPoint> ahead =
firstTunnelFacing(lookup, hoverTile, rotation, rotation, maxDistance);
ahead.has_value())
{
const std::optional<TunnelTileInfo> info = lookup(*ahead);
if (info.has_value() && info->type == BuildingType::TunnelExit)
{
exitPartner = ahead;
}
}
// Exit-completion: a hypothetical exit at the hovered tile pairs with an existing
// entry behind it — one whose forward search (its facing direction) reaches the
// hovered tile as its first same-direction tunnel. Scanning backwards, the first
// same-direction tunnel completes the exit only if it is an entry.
std::optional<QPoint> entryPartner;
if (const std::optional<QPoint> behind =
firstTunnelFacing(lookup, hoverTile, oppositeRotation(rotation), rotation,
maxDistance);
behind.has_value())
{
const std::optional<TunnelTileInfo> info = lookup(*behind);
if (info.has_value() && info->type == BuildingType::TunnelEntry)
{
entryPartner = behind;
}
}
// Default: a TunnelEntry with no partner.
if (!entryPartner.has_value() && !exitPartner.has_value())
{
return TunnelCompletion{BuildingType::TunnelEntry, std::nullopt};
}
if (entryPartner.has_value() && !exitPartner.has_value())
{
return TunnelCompletion{BuildingType::TunnelExit, entryPartner};
}
if (exitPartner.has_value() && !entryPartner.has_value())
{
return TunnelCompletion{BuildingType::TunnelEntry, exitPartner};
}
// Both apply: complete whichever existing partner is closer to the sub-tile
// cursor position (REQ-BLD-TUNNEL-MODE).
const float entryDistanceSq = tileCenterDistanceSq(*entryPartner, cursorWorldPos);
const float exitDistanceSq = tileCenterDistanceSq(*exitPartner, cursorWorldPos);
if (entryDistanceSq <= exitDistanceSq)
{
return TunnelCompletion{BuildingType::TunnelExit, entryPartner};
}
return TunnelCompletion{BuildingType::TunnelEntry, exitPartner};
}
std::optional<QPoint> findTunnelPartner(const TunnelLookup& lookup, QPoint tile,
BuildingType type, Rotation rotation,
int maxDistance)
{
if (type == BuildingType::TunnelEntry)
{
// An entry pairs with the first same-direction tunnel ahead, if it is an exit.
const std::optional<QPoint> ahead =
firstTunnelFacing(lookup, tile, rotation, rotation, maxDistance);
if (ahead.has_value())
{
const std::optional<TunnelTileInfo> info = lookup(*ahead);
if (info.has_value() && info->type == BuildingType::TunnelExit)
{
return ahead;
}
}
return std::nullopt;
}
if (type == BuildingType::TunnelExit)
{
// An exit is claimed by the first same-direction tunnel behind it, if it is an
// entry (its forward search reaches this exit as its first same-direction tunnel).
const std::optional<QPoint> behind =
firstTunnelFacing(lookup, tile, oppositeRotation(rotation), rotation, maxDistance);
if (behind.has_value())
{
const std::optional<TunnelTileInfo> info = lookup(*behind);
if (info.has_value() && info->type == BuildingType::TunnelEntry)
{
return behind;
}
}
return std::nullopt;
}
return std::nullopt;
}

View File

@@ -1,66 +0,0 @@
#pragma once
#include <functional>
#include <optional>
#include <QPoint>
#include <QVector2D>
#include "BuildingType.h"
#include "Rotation.h"
// A tunnel building occupying a single tile: whether it is an entry or an exit and
// the direction it faces. Used by the tunnel pairing scan (REQ-BLD-TUNNEL-PAIR) and
// the unified tunnel build mode (REQ-BLD-TUNNEL-MODE).
struct TunnelTileInfo
{
BuildingType type; // TunnelEntry or TunnelExit
Rotation rotation; // facing direction
};
// Given a tile, returns the tunnel building on it (entry or exit) with its facing
// direction, or std::nullopt when the tile holds no tunnel building.
using TunnelLookup = std::function<std::optional<TunnelTileInfo>(QPoint)>;
// Steps from `start` in `stepDir` over the tiles at distance 1..maxDistance and
// returns the first tile whose tunnel faces `targetFacing`. Tunnel buildings facing
// any other direction are skipped, mirroring the "stop at the first same-direction
// tunnel" rule of REQ-BLD-TUNNEL-PAIR. Returns std::nullopt if none is found in range.
std::optional<QPoint> firstTunnelFacing(const TunnelLookup& lookup, QPoint start,
Rotation stepDir, Rotation targetFacing,
int maxDistance);
// Result of resolving which tunnel end the ghost should become at a hovered tile
// (REQ-BLD-TUNNEL-MODE): the type to place and the existing tunnel it would complete.
struct TunnelCompletion
{
BuildingType resolvedType; // TunnelEntry (default) or TunnelExit
std::optional<QPoint> partnerTile; // matched existing tunnel, if any
};
// Resolves the tunnel ghost type for a hover at `hoverTile` with the ghost facing
// `rotation` (REQ-BLD-TUNNEL-MODE):
// - exit-completion: placing an exit here would pair with an existing entry behind
// it (the entry's forward search reaches this tile as its first same-direction
// tunnel) — the ghost becomes a TunnelExit;
// - entry-completion: placing an entry here would pair with an existing exit ahead
// of it — the ghost stays a TunnelEntry.
// When both apply, the end whose existing partner is closer to `cursorWorldPos` (the
// sub-tile cursor position in world tile units) wins, so nudging the cursor within a
// single tile can flip the target. With no match the ghost stays a TunnelEntry with
// no partner.
TunnelCompletion resolveTunnelCompletion(const TunnelLookup& lookup, QPoint hoverTile,
Rotation rotation, int maxDistance,
QVector2D cursorWorldPos);
// Finds the matching end of an existing tunnel building at `tile` of the given `type`
// (TunnelEntry or TunnelExit) facing `rotation`, applying the pairing scan of
// REQ-BLD-TUNNEL-PAIR over `lookup`:
// - for an entry, the first same-direction tunnel along its facing direction, if it
// is an exit;
// - for an exit, the first same-direction tunnel opposite its facing direction, if it
// is an entry.
// Returns the partner tile, or std::nullopt when the tunnel is unpaired.
std::optional<QPoint> findTunnelPartner(const TunnelLookup& lookup, QPoint tile,
BuildingType type, Rotation rotation,
int maxDistance);

View File

@@ -1,7 +1,5 @@
#pragma once
#include <optional>
#include "BuildingId.h"
// Deliver-scrap behavior (one half of the old SalvageBehaviorComponent). Scored
@@ -9,6 +7,6 @@
// SalvagerSystem performs the actual delivery.
struct DeliverScrapBehavior
{
std::optional<BuildingId> deliveryBay; // nullopt until a bay is assigned
float score = 0.0f;
BuildingId deliveryBay = kInvalidBuildingId;
float score = 0.0f;
};

View File

@@ -30,7 +30,7 @@ void SalvagerSystem::tick(Tick currentTick, ScrapSystem& scraps, BuildingSystem&
// Apply collections whose mid-beam delay has elapsed (cycles started earlier).
applyPendingCollections(currentTick, scraps);
const std::vector<ScrapInfo> allScrap = scraps.getAllScrapInfo();
const std::vector<ScrapInfo> allScrap = scraps.allScrapInfo();
// Tick down per-module collection cooldowns.
m_admin.forEach<SalvagerComponent>(
@@ -88,8 +88,8 @@ void SalvagerSystem::tick(Tick currentTick, ScrapSystem& scraps, BuildingSystem&
m_admin.forEach<DeliverScrapBehavior, PositionComponent>(
[&](entt::entity ship, const DeliverScrapBehavior& deliver, const PositionComponent& pos)
{
if (!deliver.deliveryBay.has_value()) { return; }
const Building* bay = buildings.findBuilding(*deliver.deliveryBay);
if (deliver.deliveryBay == kInvalidBuildingId) { return; }
const Building* bay = buildings.findBuilding(deliver.deliveryBay);
if (!bay) { return; }
const QVector2D bayCenter(bay->anchor.x() + bay->footprint.width() / 2.0f,
@@ -100,7 +100,7 @@ void SalvagerSystem::tick(Tick currentTick, ScrapSystem& scraps, BuildingSystem&
if (!m_admin.hasAll<CargoComponent>(ship)) { return; }
CargoComponent& cargo = m_admin.get<CargoComponent>(ship);
if (cargo.current <= 0) { return; }
if (buildings.deliverScrapToSalvageBay(*deliver.deliveryBay))
if (buildings.deliverScrapToSalvageBay(deliver.deliveryBay))
{
--cargo.current;
}

View File

@@ -65,13 +65,13 @@ bool ScrapSystem::collectOne(entt::entity entity)
return true;
}
std::vector<ScrapInfo> ScrapSystem::getAllScrapInfo() const
std::vector<ScrapInfo> ScrapSystem::allScrapInfo() const
{
std::vector<ScrapInfo> result;
m_admin.forEach<ScrapDataComponent>(
[&result, this](entt::entity e, const ScrapDataComponent& sd)
[&result, this](entt::entity e, const ScrapDataComponent& /*sd*/)
{
result.push_back(ScrapInfo{e, m_admin.get<PositionComponent>(e).value, sd.amount});
result.push_back(ScrapInfo{e, m_admin.get<PositionComponent>(e).value});
});
return result;
}

View File

@@ -15,7 +15,6 @@ struct ScrapInfo
{
entt::entity entity;
QVector2D position;
int amount;
};
class ScrapSystem
@@ -35,7 +34,7 @@ public:
bool collectOne(entt::entity entity);
// Lightweight snapshot for callers that need to iterate all scrap.
std::vector<ScrapInfo> getAllScrapInfo() const;
std::vector<ScrapInfo> allScrapInfo() const;
private:
EntityAdmin& m_admin;

View File

@@ -398,7 +398,8 @@ entt::entity ShipSystem::spawn(const std::string& schematicId,
maxCollRange * static_cast<float>(m_config.world.orbitFactor);
m_admin.addComponent<SalvageScrapBehavior>(entity, salvage);
DeliverScrapBehavior deliver; // deliveryBay starts unassigned (nullopt)
DeliverScrapBehavior deliver;
deliver.deliveryBay = kInvalidBuildingId;
m_admin.addComponent<DeliverScrapBehavior>(entity, deliver);
}

View File

@@ -31,7 +31,7 @@ void DeliverScrapEvaluator::evaluate(EntityAdmin& admin, const BuildingSystem& b
}
// Assign nearest SalvageBay if not yet assigned.
if (!deliver.deliveryBay.has_value())
if (deliver.deliveryBay == kInvalidBuildingId)
{
const Building* bay =
buildings.findNearestBuilding(pos.value, BuildingType::SalvageBay);

View File

@@ -24,9 +24,9 @@ void DeliverScrapExecutor::execute(EntityAdmin& admin, const BuildingSystem& bui
if (selected.winner != BehaviorKind::DeliverScrap) { return; }
QVector2D dest = pos.value;
if (deliver.deliveryBay.has_value())
if (deliver.deliveryBay != kInvalidBuildingId)
{
const Building* bay = buildings.findBuilding(*deliver.deliveryBay);
const Building* bay = buildings.findBuilding(deliver.deliveryBay);
if (bay)
{
dest = QVector2D(bay->anchor.x() + bay->footprint.width() / 2.0f,

View File

@@ -19,7 +19,7 @@ void SalvageScrapEvaluator::evaluate(EntityAdmin& admin, const ScrapSystem& scra
{
TRACE();
const std::unordered_map<entt::entity, CargoState> cargoByShip = buildCargoByShip(admin);
const std::vector<ScrapInfo> allScrap = scraps.getAllScrapInfo();
const std::vector<ScrapInfo> allScrap = scraps.allScrapInfo();
admin.forEach<SalvageScrapBehavior, PositionComponent, SensorRangeComponent>(
[&](entt::entity e, SalvageScrapBehavior& salvage, const PositionComponent& pos,

View File

@@ -4,7 +4,7 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/TickAdvancedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingBlocksChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ExpansionCostChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/EntitySelectionChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/EntitySelectedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/GameSpeedChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BossWaveUpdatedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoicesAvailableEvent.h
@@ -12,18 +12,16 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/GameOverEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/WinEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ArtifactCountChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/UnlockedBuildingsChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BuilderModeExitedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintModeExitedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/EscapeMenuRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DeconstructModeChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DemolishModeChangedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingTypeSelectedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildHotkeyPressedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ExitBuilderModeRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DeconstructModeToggleRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DemolishModeToggleRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/BlueprintPlacementRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/ExitBlueprintModeRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/TemporaryBlueprintRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/SpeedChangeRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/LayoutDialogRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionRequestedEvent.h
@@ -33,7 +31,6 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/BeamFiredEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/DebugDrawToggledEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/CommandRequestedEvent.h
${CMAKE_CURRENT_SOURCE_DIR}/PlayerCommandsAppliedEvent.h
PARENT_SCOPE
)

View File

@@ -1,10 +0,0 @@
#pragma once
#include "Event.h"
class DeconstructModeChangedEvent : public Event
{
public:
explicit DeconstructModeChangedEvent(bool active) : active(active) {}
const bool active;
};

View File

@@ -1,7 +0,0 @@
#pragma once
#include "Event.h"
class DeconstructModeToggleRequestedEvent : public Event
{
};

View File

@@ -0,0 +1,10 @@
#pragma once
#include "Event.h"
class DemolishModeChangedEvent : public Event
{
public:
explicit DemolishModeChangedEvent(bool active) : active(active) {}
const bool active;
};

View File

@@ -0,0 +1,7 @@
#pragma once
#include "Event.h"
class DemolishModeToggleRequestedEvent : public Event
{
};

View File

@@ -0,0 +1,21 @@
#ifndef ENTITY_SELECTED_EVENT_H
#define ENTITY_SELECTED_EVENT_H
#include <optional>
#include "entt/entity/entity.hpp"
#include "Event.h"
class EntitySelectedEvent : public Event
{
public:
explicit EntitySelectedEvent(std::optional<entt::entity> entity)
: entity(entity)
{
}
const std::optional<entt::entity> entity;
};
#endif // ENTITY_SELECTED_EVENT_H

View File

@@ -1,25 +0,0 @@
#ifndef ENTITY_SELECTION_CHANGED_EVENT_H
#define ENTITY_SELECTION_CHANGED_EVENT_H
#include <vector>
#include "entt/entity/entity.hpp"
#include "Event.h"
// The set of currently selected ships and/or defence stations. An empty list means
// no actor is selected. Actors share the "field" selection category with scrap piles
// (REQ-UI-SELECTION-CATEGORIES): they can be selected together, but never together with
// buildings.
class EntitySelectionChangedEvent : public Event
{
public:
explicit EntitySelectionChangedEvent(std::vector<entt::entity> entities)
: entities(std::move(entities))
{
}
const std::vector<entt::entity> entities;
};
#endif // ENTITY_SELECTION_CHANGED_EVENT_H

View File

@@ -1,13 +0,0 @@
#pragma once
#include "Event.h"
// Emitted by GameWorldView once per frame after queued player commands have been
// drained and applied to the simulation. It lets presentation widgets refresh
// even while the game is paused (no tick advances, so no TickAdvancedEvent), for
// example so a shipyard's layout preview appears immediately after its schematic
// is chosen. It is a UI notification only and never feeds back into the command
// queue, so it has no effect on replay recording or determinism.
class PlayerCommandsAppliedEvent : public Event
{
};

View File

@@ -1,18 +0,0 @@
#pragma once
#include <vector>
#include "entt/entity/entity.hpp"
#include "Event.h"
// The set of currently selected scrap piles (REQ-UI-SCRAP-CLICK-SELECT,
// REQ-UI-SCRAP-MULTI-SELECT). An empty list means no scrap is selected. Scrap forms
// its own selection category, mutually exclusive with buildings and entities.
class ScrapSelectionChangedEvent : public Event
{
public:
explicit ScrapSelectionChangedEvent(std::vector<entt::entity> scrap)
: scrap(std::move(scrap)) {}
const std::vector<entt::entity> scrap;
};

View File

@@ -1,9 +0,0 @@
#pragma once
#include "Event.h"
// Emitted when the player presses the temporary-blueprint hotkey (REQ-UI-BLUEPRINT-TEMP).
// Carries no payload: the blueprint is built from the current selection by the receiver.
class TemporaryBlueprintRequestedEvent : public Event
{
};

View File

@@ -1,13 +0,0 @@
#ifndef UNLOCKED_BUILDINGS_CHANGED_EVENT_H
#define UNLOCKED_BUILDINGS_CHANGED_EVENT_H
#include "Event.h"
// Emitted when the set of unlocked building types changes (REQ-LOCK-BUILDING),
// i.e. after an unlock group granting a building is awarded (REQ-DEF-SCHEMATIC-DROP)
// or on Restart. The build button grid re-evaluates which buttons are shown.
class UnlockedBuildingsChangedEvent : public Event
{
};
#endif // UNLOCKED_BUILDINGS_CHANGED_EVENT_H

View File

@@ -1,45 +0,0 @@
#include "BeltSlot.h"
#include <cstddef>
void advanceBeltSlots(std::vector<BeltItemSlot>& slots, double progressPerTick)
{
for (std::size_t i = 0; i < slots.size(); ++i)
{
slots[i].progress += progressPerTick;
// Absolute cap: slot i cannot exceed 1.0 - i * 0.25.
const double absoluteCap = 1.0 - static_cast<double>(i) * 0.25;
if (slots[i].progress > absoluteCap)
{
slots[i].progress = absoluteCap;
}
// Gap constraint: must stay 0.25 behind the slot ahead.
if (i > 0)
{
const double gapCap = slots[i - 1].progress - 0.25;
if (slots[i].progress > gapCap)
{
slots[i].progress = (gapCap < 0.0 ? 0.0 : gapCap);
}
}
}
}
QPointF beltSlotWorldPos(QPoint tile, Rotation dir, double progress)
{
// Map progress [0, 1] along the belt direction to a fractional tile-unit position.
// Progress 0 = entered from opposite side; 1 = at output edge.
const double baseX = tile.x() + 0.5;
const double baseY = tile.y() + 0.5;
switch (dir)
{
case Rotation::North: return {baseX, baseY - (progress - 0.5)};
case Rotation::East: return {baseX + (progress - 0.5), baseY};
case Rotation::South: return {baseX, baseY + (progress - 0.5)};
case Rotation::West: return {baseX - (progress - 0.5), baseY};
}
return {baseX, baseY};
}

View File

@@ -1,30 +0,0 @@
#pragma once
#include <vector>
#include <QPoint>
#include <QPointF>
#include "Item.h"
#include "Rotation.h"
// A single item on a belt-like lane: an item plus its fractional progress along
// the lane's travel direction. Shared by BeltSystem's belt/tunnel tiles and by a
// building's virtual output belt (REQ-MAT-OUTPUT-EMERGE) so the packing and
// geometry live in exactly one place.
struct BeltItemSlot
{
Item item;
double progress; // [0.0, 1.0]: 0 = just entered, 1 = at output edge
};
// Advances every slot in `slots` by `progressPerTick`, applying the standard belt
// packing: the front (index 0) carries the highest progress; each following slot
// stays at least 0.25 behind the slot ahead and is capped at 1.0 - i * 0.25.
// `slots` must be ordered front (highest progress) first. This is the per-tile
// advance shared by belts, tunnel entries, and tunnel exits.
void advanceBeltSlots(std::vector<BeltItemSlot>& slots, double progressPerTick);
// World-space centre (in tile units) of a slot at `progress` on a lane occupying
// `tile` and flowing in `dir`. Progress 0 = entry edge, 1 = output edge.
QPointF beltSlotWorldPos(QPoint tile, Rotation dir, double progress);

View File

@@ -4,7 +4,6 @@
#include "StateChecksum.h"
#include "Tick.h"
#include "TunnelCompletion.h"
#include "tracing.h"
// ---------------------------------------------------------------------------
@@ -28,54 +27,21 @@ QPoint BeltSystem::adjacentTile(QPoint tile, Rotation dir)
return tile;
}
Rotation BeltSystem::oppositeRotation(Rotation dir)
QPointF BeltSystem::slotWorldPos(QPoint tile, Rotation dir, double progress)
{
// Map progress [0, 1] along the belt direction to a fractional tile-unit position.
// Progress 0 = entered from opposite side; 1 = at output edge.
double baseX = tile.x() + 0.5;
double baseY = tile.y() + 0.5;
switch (dir)
{
case Rotation::North: return Rotation::South;
case Rotation::East: return Rotation::West;
case Rotation::South: return Rotation::North;
case Rotation::West: return Rotation::East;
case Rotation::North: return {baseX, baseY - (progress - 0.5)};
case Rotation::East: return {baseX + (progress - 0.5), baseY};
case Rotation::South: return {baseX, baseY + (progress - 0.5)};
case Rotation::West: return {baseX - (progress - 0.5), baseY};
}
return dir;
}
bool BeltSystem::entersThroughOutputEdge(QPoint tile, Rotation travelDir) const
{
// An item travelling in travelDir crosses into the tile through the edge
// opposite that direction. If that entry edge is one of the tile's output
// edges, the tile must refuse the item (REQ-MAT-ACCEPT-DIR).
const Rotation entryEdge = oppositeRotation(travelDir);
const std::map<std::pair<int, int>, BeltTile>::const_iterator beltIt =
m_belts.find(key(tile));
if (beltIt != m_belts.end())
{
return entryEdge == beltIt->second.direction;
}
const std::map<std::pair<int, int>, SplitterTile>::const_iterator splIt =
m_splitters.find(key(tile));
if (splIt != m_splitters.end())
{
return entryEdge == splIt->second.outputA || entryEdge == splIt->second.outputB;
}
const std::map<std::pair<int, int>, TunnelEntryTile>::const_iterator teIt =
m_tunnelEntries.find(key(tile));
if (teIt != m_tunnelEntries.end())
{
return entryEdge == teIt->second.direction;
}
const std::map<std::pair<int, int>, TunnelExitTile>::const_iterator txIt =
m_tunnelExits.find(key(tile));
if (txIt != m_tunnelExits.end())
{
return entryEdge == txIt->second.direction;
}
return false;
return {baseX, baseY};
}
// ---------------------------------------------------------------------------
@@ -178,57 +144,55 @@ void BeltSystem::reevaluateTunnelPairing()
std::vector<TunnelLink> oldLinks;
std::swap(oldLinks, m_tunnelLinks);
// Tunnel index over this system's own (completed) tunnel tiles, shared with the
// scan primitive so the pairing rule lives in one place (REQ-BLD-TUNNEL-PAIR).
const TunnelLookup lookup = [this](QPoint tile) -> std::optional<TunnelTileInfo>
{
const std::map<std::pair<int, int>, TunnelEntryTile>::const_iterator teIt =
m_tunnelEntries.find(key(tile));
if (teIt != m_tunnelEntries.end())
{
return TunnelTileInfo{BuildingType::TunnelEntry, teIt->second.direction};
}
const std::map<std::pair<int, int>, TunnelExitTile>::const_iterator txIt =
m_tunnelExits.find(key(tile));
if (txIt != m_tunnelExits.end())
{
return TunnelTileInfo{BuildingType::TunnelExit, txIt->second.direction};
}
return std::nullopt;
};
for (const std::pair<const std::pair<int, int>, TunnelEntryTile>& entry : m_tunnelEntries)
{
const QPoint entryPos(entry.first.first, entry.first.second);
const Rotation dir = entry.second.direction;
const int maxDist = entry.second.maxDistance;
// The first same-direction tunnel ahead forms a pair only when it is an exit;
// a same-direction entry blocks (firstTunnelFacing stops at it either way).
const std::optional<QPoint> target =
firstTunnelFacing(lookup, entryPos, dir, dir, maxDist);
if (!target.has_value() || m_tunnelExits.find(key(*target)) == m_tunnelExits.end())
for (int d = 1; d <= maxDist; ++d)
{
continue;
}
TunnelLink link;
link.entryTile = entryPos;
link.exitTile = *target;
// The exit is colinear with the entry along `dir`, so the tile-coordinate
// distance is the Manhattan distance.
link.length = static_cast<double>((*target - entryPos).manhattanLength());
for (const TunnelLink& old : oldLinks)
{
if (old.entryTile == entryPos && old.exitTile == *target)
QPoint probe = entryPos;
for (int step = 0; step < d; ++step)
{
probe = adjacentTile(probe, dir);
}
// Check if a same-direction tunnel entry is here (blocks pairing)
const std::map<std::pair<int, int>, TunnelEntryTile>::const_iterator teIt =
m_tunnelEntries.find(key(probe));
if (teIt != m_tunnelEntries.end() && teIt->second.direction == dir)
{
link.items = old.items;
break;
}
}
m_tunnelLinks.push_back(std::move(link));
// Check if a same-direction tunnel exit is here (forms pair)
const std::map<std::pair<int, int>, TunnelExitTile>::const_iterator txIt =
m_tunnelExits.find(key(probe));
if (txIt != m_tunnelExits.end())
{
if (txIt->second.direction == dir)
{
TunnelLink link;
link.entryTile = entryPos;
link.exitTile = probe;
link.length = static_cast<double>(d);
for (const TunnelLink& old : oldLinks)
{
if (old.entryTile == entryPos && old.exitTile == probe)
{
link.items = old.items;
break;
}
}
m_tunnelLinks.push_back(std::move(link));
break;
}
// Different direction exit — skip, keep searching
}
}
}
}
@@ -238,12 +202,6 @@ void BeltSystem::reevaluateTunnelPairing()
bool BeltSystem::tryPutItem(QPoint tile, Item item, Rotation fromDir)
{
// Refuse items that would enter through the tile's output edge (REQ-MAT-ACCEPT-DIR).
if (entersThroughOutputEdge(tile, fromDir))
{
return false;
}
const std::map<std::pair<int, int>, BeltTile>::iterator bIt = m_belts.find(key(tile));
if (bIt != m_belts.end())
{
@@ -453,7 +411,29 @@ void BeltSystem::advanceProgress()
for (std::map<std::pair<int, int>, BeltTile>::iterator it = m_belts.begin();
it != m_belts.end(); ++it)
{
advanceBeltSlots(it->second.itemSlots, m_progressPerTick_tpt);
BeltTile& bt = it->second;
for (std::size_t i = 0; i < bt.itemSlots.size(); ++i)
{
bt.itemSlots[i].progress += m_progressPerTick_tpt;
// Absolute cap: slot i cannot exceed 1.0 - i * 0.25.
const double absoluteCap = 1.0 - i * 0.25;
if (bt.itemSlots[i].progress > absoluteCap)
{
bt.itemSlots[i].progress = absoluteCap;
}
// Gap constraint: must stay 0.25 behind the slot ahead.
if (i > 0)
{
const double gapCap = bt.itemSlots[i - 1].progress - 0.25;
if (bt.itemSlots[i].progress > gapCap)
{
bt.itemSlots[i].progress = (gapCap < 0.0 ? 0.0 : gapCap);
}
}
}
}
for (std::map<std::pair<int, int>, SplitterTile>::iterator it = m_splitters.begin();
@@ -509,13 +489,53 @@ void BeltSystem::advanceTunnelProgress()
for (std::map<std::pair<int, int>, TunnelEntryTile>::iterator it = m_tunnelEntries.begin();
it != m_tunnelEntries.end(); ++it)
{
advanceBeltSlots(it->second.itemSlots, m_progressPerTick_tpt);
TunnelEntryTile& te = it->second;
for (std::size_t i = 0; i < te.itemSlots.size(); ++i)
{
te.itemSlots[i].progress += m_progressPerTick_tpt;
const double absoluteCap = 1.0 - i * 0.25;
if (te.itemSlots[i].progress > absoluteCap)
{
te.itemSlots[i].progress = absoluteCap;
}
if (i > 0)
{
const double gapCap = te.itemSlots[i - 1].progress - 0.25;
if (te.itemSlots[i].progress > gapCap)
{
te.itemSlots[i].progress = (gapCap < 0.0 ? 0.0 : gapCap);
}
}
}
}
for (std::map<std::pair<int, int>, TunnelExitTile>::iterator it = m_tunnelExits.begin();
it != m_tunnelExits.end(); ++it)
{
advanceBeltSlots(it->second.itemSlots, m_progressPerTick_tpt);
TunnelExitTile& tx = it->second;
for (std::size_t i = 0; i < tx.itemSlots.size(); ++i)
{
tx.itemSlots[i].progress += m_progressPerTick_tpt;
const double absoluteCap = 1.0 - i * 0.25;
if (tx.itemSlots[i].progress > absoluteCap)
{
tx.itemSlots[i].progress = absoluteCap;
}
if (i > 0)
{
const double gapCap = tx.itemSlots[i - 1].progress - 0.25;
if (tx.itemSlots[i].progress > gapCap)
{
tx.itemSlots[i].progress = (gapCap < 0.0 ? 0.0 : gapCap);
}
}
}
}
for (TunnelLink& link : m_tunnelLinks)
@@ -559,13 +579,6 @@ void BeltSystem::moveItemsToNextTile()
const QPoint here = QPoint(it->first.first, it->first.second);
const QPoint next = adjacentTile(here, bt.direction);
// Refuse to hand off into a downstream tile's output edge (REQ-MAT-ACCEPT-DIR);
// the item stays blocked at progress 1.0.
if (entersThroughOutputEdge(next, bt.direction))
{
continue;
}
const std::map<std::pair<int, int>, BeltTile>::iterator nextBelt = m_belts.find(key(next));
const std::map<std::pair<int, int>, SplitterTile>::iterator nextSplitter = m_splitters.find(key(next));
@@ -791,12 +804,6 @@ bool BeltSystem::tryPlaceOnBelt(QPoint tile, Item item)
bool BeltSystem::tryPushToTile(QPoint dest, Item item, Rotation fromDir)
{
// Refuse items that would enter through the tile's output edge (REQ-MAT-ACCEPT-DIR).
if (entersThroughOutputEdge(dest, fromDir))
{
return false;
}
if (tryPlaceOnBelt(dest, item))
{
return true;
@@ -864,7 +871,7 @@ void BeltSystem::forEachVisualItem(QRect viewportTiles,
{
VisualItem vi;
vi.type = bt.itemSlots[i].item.type;
vi.worldPos = beltSlotWorldPos(tile, bt.direction, bt.itemSlots[i].progress);
vi.worldPos = slotWorldPos(tile, bt.direction, bt.itemSlots[i].progress);
visit(vi);
}
}
@@ -884,7 +891,7 @@ void BeltSystem::forEachVisualItem(QRect viewportTiles,
{
VisualItem vi;
vi.type = st.back[i].item.type;
vi.worldPos = beltSlotWorldPos(tile, st.backDir[i], st.back[i].progress);
vi.worldPos = slotWorldPos(tile, st.backDir[i], st.back[i].progress);
visit(vi);
}
@@ -910,7 +917,7 @@ void BeltSystem::forEachVisualItem(QRect viewportTiles,
{
VisualItem vi;
vi.type = slot->item.type;
vi.worldPos = beltSlotWorldPos(tile, dir, slot->progress);
vi.worldPos = slotWorldPos(tile, dir, slot->progress);
visit(vi);
}
};
@@ -940,7 +947,7 @@ void BeltSystem::forEachVisualItem(QRect viewportTiles,
{
VisualItem vi;
vi.type = te.itemSlots[i].item.type;
vi.worldPos = beltSlotWorldPos(tile, te.direction, te.itemSlots[i].progress);
vi.worldPos = slotWorldPos(tile, te.direction, te.itemSlots[i].progress);
visit(vi);
}
}
@@ -958,7 +965,7 @@ void BeltSystem::forEachVisualItem(QRect viewportTiles,
{
VisualItem vi;
vi.type = tx.itemSlots[i].item.type;
vi.worldPos = beltSlotWorldPos(tile, tx.direction, tx.itemSlots[i].progress);
vi.worldPos = slotWorldPos(tile, tx.direction, tx.itemSlots[i].progress);
visit(vi);
}
}

View File

@@ -10,7 +10,6 @@
#include <QPointF>
#include <QRect>
#include "BeltSlot.h"
#include "Item.h"
#include "ItemType.h"
#include "Port.h"
@@ -52,7 +51,7 @@ public:
// tile are held and routed to one of the two outputs.
void placeSplitter(QPoint tile, Rotation outputA, Rotation outputB);
// Remove a belt or splitter tile (on deconstruct). Items are discarded.
// Remove a belt or splitter tile (on demolish). Items are discarded.
void removeTile(QPoint tile);
// -- Splitter filter configuration (REQ-BLD-SPLITTER) -------------------
@@ -75,10 +74,8 @@ public:
// port.direction = direction items flow on that tile
//
// tryPutItem: place item onto tile.
// Returns false if the tile is not a belt/splitter/tunnel entry, tile full,
// or the item would enter through the tile's output edge (REQ-MAT-ACCEPT-DIR).
// fromDir: travel direction of the item (used for splitter animation and for
// the output-edge check).
// Returns false if the tile is not a belt/splitter, or tile full.
// fromDir: travel direction of the item (used for splitter animation).
bool tryPutItem(QPoint tile, Item item, Rotation fromDir = Rotation::West);
// tryTakeItem: remove and return the leading item from port.tile.
@@ -89,11 +86,6 @@ public:
// Returns nullopt if tile is not a belt, direction mismatches, or tile empty.
std::optional<ItemType> peekItem(Port port) const;
// Progress advanced per tick at the configured belt speed (tile fraction per
// tick). Shared with building output belts so emerging items travel at exactly
// the same speed as real belts (REQ-MAT-OUTPUT-EMERGE).
double getProgressPerTick_tpt() const { return m_progressPerTick_tpt; }
// -- Maintenance ---------------------------------------------------------
void clearTiles(const std::vector<QPoint>& tiles); // REQ-UI-BELT-CLEAR
void tick();
@@ -125,12 +117,15 @@ private:
static std::pair<int, int> key(QPoint tile);
static QPoint adjacentTile(QPoint tile, Rotation dir);
static Rotation oppositeRotation(Rotation dir);
// True if an item travelling in travelDir would enter the transport tile at
// `tile` through one of that tile's output edges (and must therefore be
// refused). Returns false if no transport tile occupies `tile`.
bool entersThroughOutputEdge(QPoint tile, Rotation travelDir) const;
// Returns the world-space centre of a slot given tile origin and progress.
static QPointF slotWorldPos(QPoint tile, Rotation dir, double progress);
struct BeltItemSlot
{
Item item;
double progress; // [0.0, 1.0]: 0 = just entered, 1 = at output edge
};
struct BeltTile
{

View File

@@ -12,7 +12,6 @@
#include "BuildingId.h"
#include "entt/entity/entity.hpp"
#include "BeltSlot.h"
#include "Item.h"
#include "ItemType.h"
#include "Port.h"
@@ -76,51 +75,6 @@ struct Building
OutputBuffer outputBuffer;
std::optional<Production> production;
// Items currently emerging from each output port on its virtual output belt
// (REQ-MAT-OUTPUT-EMERGE); one lane per output port, parallel to outputPorts.
// Each lane holds slots at progress [0.5, 1.0], front (highest progress) first.
// An emerging item still counts as residing in the output buffer until it hands
// off onto a real belt at progress 1.0.
std::vector<std::vector<BeltItemSlot>> emergingItems;
// Total items held on the output side: buffered plus still-emerging. The
// output-buffer capacity rule (REQ-MAT-OUTPUT-BUFFER) counts emerging items,
// since they have not yet left the building.
int getOutputItemCount() const
{
int count = static_cast<int>(outputBuffer.items.size());
for (const std::vector<BeltItemSlot>& lane : emergingItems)
{
count += static_cast<int>(lane.size());
}
return count;
}
// Items currently travelling inward on each input port's virtual input belt
// (REQ-MAT-INPUT-INTAKE); one lane per input port, parallel to inputPorts. Each
// lane holds slots at progress [0.0, 0.5], front (highest progress) first. An
// in-transit item has reserved a slot in its per-material input buffer but is
// not yet consumable — it enters the buffer only on reaching progress 0.5.
std::vector<std::vector<BeltItemSlot>> incomingItems;
// Buffered plus in-transit count of one input material. The acceptance/space
// test (REQ-MAT-INPUT-PORTS, REQ-MAT-INPUT-INTAKE) counts in-transit items, so
// buffered + reserved never exceeds the material's cap (REQ-MAT-INPUT-BUFFER).
int pendingInputCount(const ItemType& type) const
{
int count = 0;
const std::map<ItemType, int>::const_iterator it = inputBuffer.counts.find(type);
if (it != inputBuffer.counts.end()) { count = it->second; }
for (const std::vector<BeltItemSlot>& lane : incomingItems)
{
for (const BeltItemSlot& slot : lane)
{
if (slot.item.type == type) { ++count; }
}
}
return count;
}
// Pre-computed from surface mask at placement; in absolute world coordinates.
std::vector<QPoint> bodyCells;
std::vector<Port> outputPorts;
@@ -129,10 +83,5 @@ struct Building
// Module layout for shipyards (REQ-MOD-LAYOUT).
std::optional<ShipLayoutConfig> shipLayout;
// True while this building sits in the deconstruction queue (REQ-BLD-DECON-QUEUE).
// A queued building stops operating immediately (all tick loops skip it) but keeps
// occupying its tiles until its deconstruction completes.
bool queuedForDeconstruction = false;
};

View File

@@ -1,167 +0,0 @@
#include "BuildingConfig.h"
#include <algorithm>
#include <climits>
#include "BeltSystem.h"
#include "Building.h"
#include "BuildingSystem.h"
#include "Simulation.h"
namespace
{
// The blueprint-relevant geometry shared by operational buildings and construction
// sites. Resolved from whichever of the two a selected id refers to.
struct SelectedBuilding
{
BuildingId id;
BuildingType type;
Rotation rotation;
QPoint anchor;
const std::vector<QPoint>* bodyCells;
};
// Resolves a selected id to a player-placeable building or construction site, if it
// is one. Returns std::nullopt for an unknown id or a non-player-placeable building
// (the HQ and defence stations, per REQ-UI-BLUEPRINT-CREATE).
std::optional<SelectedBuilding> resolvePlaceable(const Simulation& sim, BuildingId id)
{
const Building* building = sim.getBuildings().findBuilding(id);
const ConstructionSite* site = building ? nullptr : sim.getBuildings().findSite(id);
if (!building && !site)
{
return std::nullopt;
}
const BuildingType type = building ? building->type : site->type;
const BuildingDef* def = sim.getConfig().buildings.findBuildingDef(type);
if (!def || !def->playerPlaceable)
{
return std::nullopt;
}
SelectedBuilding resolved;
resolved.id = id;
resolved.type = type;
resolved.rotation = building ? building->rotation : site->rotation;
resolved.anchor = building ? building->anchor : site->anchor;
resolved.bodyCells = building ? &building->bodyCells : &site->bodyCells;
return resolved;
}
} // namespace
std::optional<BuildingConfig> readBuildingConfig(const Simulation& sim, BuildingId id)
{
const Building* building = sim.getBuildings().findBuilding(id);
const ConstructionSite* site = building ? nullptr : sim.getBuildings().findSite(id);
if (!building && !site)
{
return std::nullopt;
}
BuildingConfig config;
config.type = building ? building->type : site->type;
const std::string& recipeId = building ? building->recipeId : site->recipeId;
if (!recipeId.empty())
{
config.recipeId = recipeId;
}
config.shipLayout = building ? building->shipLayout : site->shipLayout;
if (config.type == BuildingType::Splitter)
{
config.isSplitter = true;
if (building)
{
// Operational splitter filters live in the BeltSystem, keyed by tile.
const std::optional<BeltSystem::SplitterInfo> info =
sim.getBelts().getSplitterInfo(building->anchor);
if (info.has_value())
{
config.splitterFilterA = info->filterA;
config.splitterFilterB = info->filterB;
}
}
else
{
// A site keeps its pre-completion filters on the ConstructionSite.
config.splitterFilterA = site->splitterFilterA;
config.splitterFilterB = site->splitterFilterB;
}
}
return config;
}
Blueprint captureBlueprintFromSelection(const Simulation& sim,
const std::vector<BuildingId>& selectedIds)
{
std::vector<SelectedBuilding> entries;
entries.reserve(selectedIds.size());
for (const BuildingId id : selectedIds)
{
const std::optional<SelectedBuilding> resolved = resolvePlaceable(sim, id);
if (resolved.has_value())
{
entries.push_back(*resolved);
}
}
if (entries.empty())
{
return Blueprint{};
}
int minX = INT_MAX, maxX = INT_MIN;
int minY = INT_MAX, maxY = INT_MIN;
for (const SelectedBuilding& e : entries)
{
for (const QPoint& cell : *e.bodyCells)
{
minX = std::min(minX, cell.x());
maxX = std::max(maxX, cell.x());
minY = std::min(minY, cell.y());
maxY = std::max(maxY, cell.y());
}
}
const QPoint center((minX + maxX) / 2, (minY + maxY) / 2);
Blueprint blueprint;
blueprint.buildings.reserve(entries.size());
for (const SelectedBuilding& e : entries)
{
BlueprintBuilding building;
building.type = e.type;
building.rotation = e.rotation;
building.offset = e.anchor - center;
// Recipe / schematic / layout / splitter-filter capture is shared with the
// copy-settings gesture (REQ-BLD-COPY-CONFIG) via readBuildingConfig, which
// handles operational buildings and construction sites alike.
const std::optional<BuildingConfig> config = readBuildingConfig(sim, e.id);
if (config.has_value())
{
building.recipeId = config->recipeId.value_or(std::string());
building.shipLayout = config->shipLayout;
building.splitterFilterA = config->splitterFilterA;
building.splitterFilterB = config->splitterFilterB;
}
blueprint.buildings.push_back(building);
}
return blueprint;
}
bool selectionHasPlaceableBuilding(const Simulation& sim,
const std::vector<BuildingId>& selectedIds)
{
for (const BuildingId id : selectedIds)
{
if (resolvePlaceable(sim, id).has_value())
{
return true;
}
}
return false;
}

View File

@@ -1,54 +0,0 @@
#pragma once
#include <optional>
#include <string>
#include <vector>
#include "Blueprint.h"
#include "BuildingId.h"
#include "BuildingType.h"
#include "ItemType.h"
#include "ShipLayout.h"
class Simulation;
// The user-configurable settings of a single building or construction site: the
// selected recipe / ship schematic, the shipyard module layout, and (for
// splitters) the two output filters. Shared by the copy-settings gesture
// (REQ-BLD-COPY-CONFIG) and blueprint capture (REQ-UI-BLUEPRINT-STORAGE).
struct BuildingConfig
{
BuildingType type = BuildingType::Miner;
// Selected recipe (Miner / Assembler) or ship schematic id (Shipyard); unset
// when nothing is selected.
std::optional<std::string> recipeId;
// Shipyard module layout (REQ-MOD-LAYOUT).
std::optional<ShipLayoutConfig> shipLayout;
// Splitter output filters (empty = accept all). isSplitter distinguishes an
// empty-filter splitter (a valid accept-all configuration) from a building
// type that has no splitter filters at all.
bool isSplitter = false;
std::vector<ItemType> splitterFilterA;
std::vector<ItemType> splitterFilterB;
};
// Reads the current configuration of the building or construction site identified
// by id, handling operational buildings and sites alike. Returns std::nullopt if
// no such building or site exists.
std::optional<BuildingConfig> readBuildingConfig(const Simulation& sim, BuildingId id);
// Captures a blueprint from a selection of building / construction-site ids, keeping
// only player-placeable buildings and recording each one's type, rotation, offset
// from the selection's bounding-box center, and configuration. Operational buildings
// and construction sites are treated identically (REQ-UI-BLUEPRINT-CREATE,
// REQ-UI-BLUEPRINT-STORAGE). The returned blueprint is unnamed.
Blueprint captureBlueprintFromSelection(const Simulation& sim,
const std::vector<BuildingId>& selectedIds);
// True if any selected id refers to a player-placeable building or construction site
// (the enable condition for the Create Blueprint button, REQ-UI-BLUEPRINT-CREATE).
bool selectionHasPlaceableBuilding(const Simulation& sim,
const std::vector<BuildingId>& selectedIds);

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,6 @@
#include <vector>
#include <QPoint>
#include <QPointF>
#include <QVector2D>
#include "BeltSystem.h"
@@ -26,18 +25,6 @@
class Hasher;
// Production state of a building for the UI status light (REQ-UI-STATUS-LIGHT).
// The simulation owns the classification so it stays in sync with the
// production-cycle predicates (REQ-MAT-CYCLE); the UI maps each value to a fill
// color.
enum class ProductionStatus
{
Unconfigured, // no recipe/schematic selected (grey)
Producing, // a production cycle is active (green)
Starved, // idle: a required input is missing / Salvage Bay empty (red)
Blocked, // idle: output buffer full, inputs otherwise present (yellow)
};
// Manages building placement, construction queuing, and the per-tick
// production loop (belt→building pull, production, building→belt push).
// All types including Belt and Splitter are stored as Building instances;
@@ -54,14 +41,14 @@ public:
std::function<bool(const std::string&)> isItemUnlocked,
std::mt19937& rng);
// -- Placement / deconstruct ------------------------------------------------
// Returns the new entity id, or nullopt if the placement falls outside the
// world bounds (vertical extent and asteroid left edge). Belt and Splitter
// register with BeltSystem directly; other types enter the construction
// queue. Terrain type (A vs S) is NOT checked here so that tests can stage
// arbitrary layouts; the player-facing entry point
// -- Placement / demolish ------------------------------------------------
// Returns the new entity id, or kInvalidBuildingId if the placement falls
// outside the world bounds (vertical extent and asteroid left edge). Belt
// and Splitter register with BeltSystem directly; other types enter the
// construction queue. Terrain type (A vs S) is NOT checked here so that
// tests can stage arbitrary layouts; the player-facing entry point
// (Simulation::tryPlaceBuilding) enforces the full rule via isPlacementValid.
std::optional<BuildingId> place(BuildingType type, QPoint anchor, Rotation rotation,
BuildingId place(BuildingType type, QPoint anchor, Rotation rotation,
Tick currentTick);
// Returns true if the placement satisfies REQ-BLD-PLACE-VALID terrain and
@@ -77,22 +64,10 @@ public:
// Defaults to world.regions.asteroid_width_tiles at construction.
void setAsteroidWidth_tiles(int widthTiles) { m_asteroidWidth_tiles = widthTiles; }
// Mark a building or construction site for demolition (REQ-BLD-DECONSTRUCT).
// A construction site is removed instantly and the full cost is returned.
// A fully-built building is instead appended to the deconstruction queue
// (REQ-BLD-DECON-QUEUE) and stops operating at once; its (partial) refund is
// credited later, on completion in tickDeconstruction, so this returns 0 for
// it. Returns 0 for unknown ids and for a building already queued.
int deconstruct(BuildingId id, Tick currentTick);
// Take a building back out of the deconstruction queue before it is removed
// (REQ-BLD-DECON-QUEUE). Clears its queued flag and resumes operation
// (re-registering belt/tunnel/splitter tiles); discards deconstruction
// progress and credits no refund. No-op if the id is not queued.
void cancelDeconstruction(BuildingId id);
// True if the building is currently in the deconstruction queue.
bool isQueuedForDeconstruction(BuildingId id) const;
// Remove a building or construction site by id. Returns the refund in
// building blocks (floor(cost * refundPercentage / 100)). Returns 0 for
// unknown ids.
int demolish(BuildingId id);
// Set the recipe (or schematic id for shipyard) on a building or queued
// construction site. Clears both buffers on an operational building.
@@ -116,17 +91,10 @@ public:
// -- Tick hooks (called from Simulation::tick in the documented order) ---
void tickConstruction(Tick currentTick);
// Advances the deconstruction queue (REQ-BLD-DECON-QUEUE): one building at a
// time, in parallel with tickConstruction. Removes the front building and
// credits its refund when its timer elapses.
void tickDeconstruction(Tick currentTick);
void tickBeltPull();
void tickProduction(Tick currentTick);
void tickShipyardProduction(Tick currentTick);
// Advances each building's virtual output belts, hands finished items off onto
// the adjacent real belt, and feeds new buffered items into them
// (REQ-MAT-OUTPUT-EMERGE).
void tickOutputBelts();
void tickBeltPush();
// -- Queries -------------------------------------------------------------
struct BeltTileInfo
@@ -140,38 +108,19 @@ public:
const Building* findBuilding(BuildingId id) const;
const ConstructionSite* findSite(BuildingId id) const;
std::vector<Building> getAllBuildings() const;
std::vector<ConstructionSite> getAllSites() const;
std::vector<Building> allBuildings() const;
std::vector<ConstructionSite> allSites() const;
// REQ-UI-DEBUG-OVERLAY "Max Factory Production": count of completed
// (operational) Miner/Smelter/Assembler/ReprocessingPlant/Shipyard buildings.
int getProductionBuildingCount() const;
int productionBuildingCount() const;
// REQ-UI-DEBUG-OVERLAY "Current Factory Production": subset of the above
// that currently has an active production cycle.
int getActiveProductionBuildingCount() const;
// Production state for the UI status light (REQ-UI-STATUS-LIGHT). Returns
// nullopt for building types that show no light (belts, splitters, tunnels,
// HQ, defence stations). The Salvage Bay is a two-state special case:
// Producing while its output buffer holds scrap, Starved when empty.
std::optional<ProductionStatus> getProductionStatus(const Building& building) const;
std::vector<BeltTileInfo> getAllBeltTiles() const;
int activeProductionBuildingCount() const;
std::vector<BeltTileInfo> allBeltTiles() const;
bool isTileOccupied(QPoint tile) const;
// Visits every item currently emerging from a building output port on its
// virtual output belt (REQ-MAT-OUTPUT-EMERGE), passing the item type and its
// world-space centre (in tile units). Least-progressed first (drawn bottom) so
// callers can paint in visit order (REQ-GW-TILE-SIZE ordering).
void forEachEmergingItem(
const std::function<void(const ItemType&, QPointF)>& visit) const;
// Visits every item currently travelling inward on a building input port's
// virtual input belt (REQ-MAT-INPUT-INTAKE), passing the item type and its
// world-space centre (in tile units). Least-progressed first (drawn bottom).
void forEachIncomingItem(
const std::function<void(const ItemType&, QPointF)>& visit) const;
// Returns the entity id of the building or construction site whose footprint
// exactly coincides with the ghost (type, anchor, rot) and is of the same
// building type. Returns nullopt otherwise.
@@ -187,12 +136,6 @@ public:
// Find nearest operational building of the given type; nullptr if none.
const Building* findNearestBuilding(QVector2D worldPos, BuildingType type) const;
// Input-capable adjacent tiles for a building or construction site
// (REQ-BLD-BELT-DRAG, REQ-MAT-INPUT-PORTS): each returned Port.tile is the
// outside adjacent tile and Port.direction is the belt facing that points into
// the target. Output-port edges are excluded. Empty for an unknown id.
std::vector<Port> getInputPorts(BuildingId id) const;
// Register / unregister tile occupancy for ECS station entities.
void registerTileOccupancy(const std::vector<QPoint>& cells, BuildingId ownerPlaceholder);
void unregisterTileOccupancy(const std::vector<QPoint>& cells);
@@ -221,67 +164,13 @@ public:
void appendChecksum(Hasher& hasher) const;
private:
// Starts the front deconstruction-queue entry's timer if not yet started
// (mirrors how tickConstruction starts a queued construction site).
void startFrontDeconstruction(Tick currentTick);
// Registers a belt/splitter/tunnel building's tile with the belt subsystem
// (on construction completion, or when un-queuing a deconstruction). No-op for
// non-belt-subsystem types. Splitter filters are (re)applied after placement.
void reregisterBeltTile(const Building& building,
const std::vector<ItemType>& splitterFilterA,
const std::vector<ItemType>& splitterFilterB);
Building* findBuildingMutable(BuildingId id);
// True if the consumer would accept `type` at the given input port right now:
// it is a required input (or a building block for the HQ), the reservation-aware
// buffer has room, and the input belt entry is free (REQ-MAT-INPUT-INTAKE).
bool canAcceptInput(const Building& consumer,
std::size_t inputPortIndex,
const ItemType& type) const;
// Places an accepted item onto the consumer's input belt at progress 0.0,
// reserving a per-material buffer slot (REQ-MAT-INPUT-INTAKE).
void depositToInputBelt(Building& consumer,
std::size_t inputPortIndex,
const Item& item);
// Attempts to hand an emerging output item straight into a directly adjacent
// building whose input edge meets the producer's output port (REQ-MAT-DIRECT-COUPLE).
// Returns true if the item was accepted onto the consumer's input belt.
bool tryDirectCoupleDeposit(BuildingId producerId,
const Port& outputPort,
const Item& item);
// Candidate recipes an idle building would try this tick: an auto-recipe
// building (Smelter, Reprocessing Plant) offers every recipe of its type with
// inputs; other buildings offer only their selected recipe. Shared by
// tickProduction and the status classifier (REQ-MAT-CYCLE, REQ-UI-STATUS-LIGHT).
std::vector<const RecipeDef*> gatherCandidateRecipes(const Building& b) const;
// True if every input of `recipe` is present in `b`'s input buffers in the
// required per-cycle amount (REQ-MAT-CYCLE input check).
bool recipeInputsAvailable(const Building& b,
const RecipeDef& recipe) const;
// Combined base + module materials a shipyard needs per ship (REQ-BLD-SHIPYARD).
std::map<std::string, int> computeShipyardRequiredMaterials(const Building& b) const;
// True if the building currently has all inputs/materials to start a cycle
// (ignoring output-buffer space); drives the Starved/Blocked distinction of
// the status light (REQ-UI-STATUS-LIGHT).
bool hasInputsToStart(const Building& b) const;
const BuildingDef* findBuildingDef(BuildingType type) const;
const RecipeDef* findRecipe(const std::string& id, BuildingType type) const;
const ShipDef* findShipDef(const std::string& id) const;
const ModuleDef* findModuleDef(const std::string& id) const;
void initBuffers(Building& b, const RecipeDef& recipe) const;
// Buffers for an auto-recipe building (Smelter, Reprocessing Plant): input
// caps span the union of every recipe of the building's type; no player
// recipe is selected (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING).
void initAutoBuffers(Building& b) const;
void initShipyardBuffers(Building& b) const;
void initSalvageBayBuffer(Building& b) const;
std::vector<Port> computeInputPorts(const Building& b) const;
// Core input-edge scan shared by operational buildings and construction sites.
std::vector<Port> computeInputPorts(const std::vector<QPoint>& bodyCells,
const std::vector<Port>& outputPorts) const;
std::vector<Item> rollReprocessingOutput(const RecipeDef& recipe);
bool bodyCellsWithinWorldBounds(
const std::vector<QPoint>& bodyCells,
@@ -300,19 +189,6 @@ private:
std::vector<Building> m_buildings;
std::deque<ConstructionSite> m_constructionQueue;
// One pending demolition of a fully-built building (REQ-BLD-DECON-QUEUE).
// completesAt == 0 means "queued but its timer has not started yet"
// (mirrors ConstructionSite). For a Splitter, the filters it had are captured
// here so cancelDeconstruction can restore them on re-registration.
struct DeconstructionEntry
{
BuildingId id = kInvalidBuildingId;
Tick completesAt = 0;
std::vector<ItemType> splitterFilterA;
std::vector<ItemType> splitterFilterB;
};
std::deque<DeconstructionEntry> m_deconstructionQueue;
// Maps every occupied body-cell coordinate to the entity that owns it.
std::map<std::pair<int, int>, BuildingId> m_tileOccupancy;
};

View File

@@ -8,10 +8,8 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/ReplayReader.h
${CMAKE_CURRENT_SOURCE_DIR}/ReplayPlayer.h
${CMAKE_CURRENT_SOURCE_DIR}/TickDriver.h
${CMAKE_CURRENT_SOURCE_DIR}/BeltSlot.h
${CMAKE_CURRENT_SOURCE_DIR}/BeltSystem.h
${CMAKE_CURRENT_SOURCE_DIR}/Building.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingConfig.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingSystem.h
${CMAKE_CURRENT_SOURCE_DIR}/EntityHitTest.h
${CMAKE_CURRENT_SOURCE_DIR}/ShipLayout.h
@@ -32,9 +30,7 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/ReplayReader.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ReplayPlayer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/TickDriver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BeltSlot.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BeltSystem.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildingConfig.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildingSystem.cpp
${CMAKE_CURRENT_SOURCE_DIR}/EntityHitTest.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ShipStatsCalculator.cpp

View File

@@ -27,8 +27,7 @@ class GameConfig;
enum class CommandKind
{
PlaceBuilding,
Deconstruct,
CancelDeconstruction,
Demolish,
RotateInPlace,
SetRecipe,
SetShipLayout,
@@ -73,41 +72,31 @@ struct PlaceBuildingCommand : Command
std::vector<ItemType> splitterFilterB;
};
// Marks a building for demolition: a construction site is removed instantly, a
// built building is queued for deconstruction (REQ-BLD-DECONSTRUCT, REQ-BLD-DECON-QUEUE).
struct DeconstructCommand : Command
struct DemolishCommand : Command
{
DeconstructCommand() : Command(CommandKind::Deconstruct) {}
std::optional<BuildingId> id;
};
// Takes a building back out of the deconstruction queue (REQ-BLD-DECONSTRUCT-CLICK,
// REQ-BLD-DECONSTRUCT-BOX). No-op if the id is not currently queued.
struct CancelDeconstructionCommand : Command
{
CancelDeconstructionCommand() : Command(CommandKind::CancelDeconstruction) {}
std::optional<BuildingId> id;
DemolishCommand() : Command(CommandKind::Demolish) {}
BuildingId id = kInvalidBuildingId;
};
struct RotateInPlaceCommand : Command
{
RotateInPlaceCommand() : Command(CommandKind::RotateInPlace) {}
std::optional<BuildingId> id;
Rotation newRotation = Rotation::East;
BuildingId id = kInvalidBuildingId;
Rotation newRotation = Rotation::East;
};
struct SetRecipeCommand : Command
{
SetRecipeCommand() : Command(CommandKind::SetRecipe) {}
std::optional<BuildingId> id;
std::string recipeId;
BuildingId id = kInvalidBuildingId;
std::string recipeId;
};
struct SetShipLayoutCommand : Command
{
SetShipLayoutCommand() : Command(CommandKind::SetShipLayout) {}
std::optional<BuildingId> id;
ShipLayoutConfig layout;
BuildingId id = kInvalidBuildingId;
ShipLayoutConfig layout;
};
// Splitter filters for a queued / under-construction Splitter site (configured by
@@ -115,8 +104,8 @@ struct SetShipLayoutCommand : Command
struct SetSiteSplitterFiltersCommand : Command
{
SetSiteSplitterFiltersCommand() : Command(CommandKind::SetSiteSplitterFilters) {}
std::optional<BuildingId> id;
std::vector<ItemType> filterA;
BuildingId id = kInvalidBuildingId;
std::vector<ItemType> filterA;
std::vector<ItemType> filterB;
};

View File

@@ -46,18 +46,18 @@ void CommandManager::drain()
{
// Restart is a file boundary: a fresh file with the new seed.
m_recorder->startNewRun(m_simulation.getSeed(),
m_simulation.getRngFingerprint());
m_simulation.rngFingerprint());
}
}
else
{
// Commands drain before the tick batch, so currentTick is the count of
// completed ticks the command is pinned to.
const Tick tick = m_simulation.getCurrentTick();
const Tick tick = m_simulation.currentTick();
m_simulation.apply(*command);
if (m_recorder)
{
m_recorder->recordCommand(tick, *command, m_simulation.getRngFingerprint());
m_recorder->recordCommand(tick, *command, m_simulation.rngFingerprint());
}
}
}
@@ -74,7 +74,7 @@ void CommandManager::setRecorder(std::unique_ptr<ReplayRecorder> recorder)
m_recorder = std::move(recorder);
if (m_recorder)
{
m_recorder->startNewRun(m_simulation.getSeed(), m_simulation.getRngFingerprint());
m_recorder->startNewRun(m_simulation.getSeed(), m_simulation.rngFingerprint());
}
}
@@ -85,8 +85,8 @@ void CommandManager::setReplayMode(bool replayMode)
void CommandManager::recordTickCheckpoint()
{
if (m_recorder && (m_simulation.getCurrentTick() % kChecksumIntervalTicks == 0))
if (m_recorder && (m_simulation.currentTick() % kChecksumIntervalTicks == 0))
{
m_recorder->recordChecksum(m_simulation.getCurrentTick(), m_simulation.getRngFingerprint());
m_recorder->recordChecksum(m_simulation.currentTick(), m_simulation.rngFingerprint());
}
}

View File

@@ -128,29 +128,25 @@ std::string serializeCommand(const Command& command)
}
break;
}
case CommandKind::Deconstruct:
out << "deconstruct " << static_cast<const DeconstructCommand&>(command).id.value();
break;
case CommandKind::CancelDeconstruction:
out << "cancel_deconstruct "
<< static_cast<const CancelDeconstructionCommand&>(command).id.value();
case CommandKind::Demolish:
out << "demolish " << static_cast<const DemolishCommand&>(command).id;
break;
case CommandKind::RotateInPlace:
{
const RotateInPlaceCommand& c = static_cast<const RotateInPlaceCommand&>(command);
out << "rotate " << c.id.value() << ' ' << rotationToChar(c.newRotation);
out << "rotate " << c.id << ' ' << rotationToChar(c.newRotation);
break;
}
case CommandKind::SetRecipe:
{
const SetRecipeCommand& c = static_cast<const SetRecipeCommand&>(command);
out << "setrecipe " << c.id.value() << ' ' << c.recipeId;
out << "setrecipe " << c.id << ' ' << c.recipeId;
break;
}
case CommandKind::SetShipLayout:
{
const SetShipLayoutCommand& c = static_cast<const SetShipLayoutCommand&>(command);
out << "setlayout " << c.id.value() << ' ';
out << "setlayout " << c.id << ' ';
appendLayout(out, c.layout);
break;
}
@@ -158,7 +154,7 @@ std::string serializeCommand(const Command& command)
{
const SetSiteSplitterFiltersCommand& c =
static_cast<const SetSiteSplitterFiltersCommand&>(command);
out << "sitefilters " << c.id.value() << ' ';
out << "sitefilters " << c.id << ' ';
appendFilters(out, c.filterA, c.filterB);
break;
}
@@ -243,47 +239,30 @@ std::shared_ptr<Command> parseCommand(const std::string& tokens)
}
return c;
}
if (verb == "deconstruct")
if (verb == "demolish")
{
std::shared_ptr<DeconstructCommand> c = std::make_shared<DeconstructCommand>();
BuildingId id = 0;
if (!(in >> id)) { return nullptr; }
c->id = id;
return c;
}
if (verb == "cancel_deconstruct")
{
std::shared_ptr<CancelDeconstructionCommand> c =
std::make_shared<CancelDeconstructionCommand>();
BuildingId id = 0;
if (!(in >> id)) { return nullptr; }
c->id = id;
std::shared_ptr<DemolishCommand> c = std::make_shared<DemolishCommand>();
if (!(in >> c->id)) { return nullptr; }
return c;
}
if (verb == "rotate")
{
std::shared_ptr<RotateInPlaceCommand> c = std::make_shared<RotateInPlaceCommand>();
std::string rotToken;
BuildingId id = 0;
if (!(in >> id >> rotToken)) { return nullptr; }
c->id = id;
if (!(in >> c->id >> rotToken)) { return nullptr; }
c->newRotation = rotationFromString(rotToken);
return c;
}
if (verb == "setrecipe")
{
std::shared_ptr<SetRecipeCommand> c = std::make_shared<SetRecipeCommand>();
BuildingId id = 0;
if (!(in >> id >> c->recipeId)) { return nullptr; }
c->id = id;
if (!(in >> c->id >> c->recipeId)) { return nullptr; }
return c;
}
if (verb == "setlayout")
{
std::shared_ptr<SetShipLayoutCommand> c = std::make_shared<SetShipLayoutCommand>();
BuildingId id = 0;
if (!(in >> id)) { return nullptr; }
c->id = id;
if (!(in >> c->id)) { return nullptr; }
c->layout = parseLayout(in, ok);
if (!ok) { return nullptr; }
return c;
@@ -292,9 +271,7 @@ std::shared_ptr<Command> parseCommand(const std::string& tokens)
{
std::shared_ptr<SetSiteSplitterFiltersCommand> c =
std::make_shared<SetSiteSplitterFiltersCommand>();
BuildingId id = 0;
if (!(in >> id)) { return nullptr; }
c->id = id;
if (!(in >> c->id)) { return nullptr; }
parseFilters(in, c->filterA, c->filterB, ok);
if (!ok) { return nullptr; }
return c;

View File

@@ -1,12 +1,9 @@
#include "EntityHitTest.h"
#include <algorithm>
#include <cmath>
#include "EntityAdmin.h"
#include "PositionComponent.h"
#include "ScrapDataComponent.h"
#include "ShipIdentityComponent.h"
#include "StationBodyComponent.h"
#include "HealthComponent.h"
@@ -57,91 +54,3 @@ entt::entity entityAtWorldPos(EntityAdmin& admin, QVector2D worldPos)
return bestShip;
}
entt::entity scrapAtWorldPos(EntityAdmin& admin, QVector2D worldPos)
{
// Slightly larger than the scrap's rendered radius (0.2 tiles) so small piles
// remain easy to click; tunable.
constexpr float kScrapHitRadiusSquared = 0.35f * 0.35f;
entt::entity bestScrap = entt::null;
float bestDistSquared = kScrapHitRadiusSquared;
admin.forEach<ScrapDataComponent, PositionComponent>(
[&](entt::entity entity, const ScrapDataComponent& /*sd*/, const PositionComponent& pos)
{
const float dx = pos.value.x() - worldPos.x();
const float dy = pos.value.y() - worldPos.y();
const float distSquared = dx * dx + dy * dy;
if (distSquared < bestDistSquared)
{
bestDistSquared = distSquared;
bestScrap = entity;
}
});
return bestScrap;
}
std::vector<entt::entity> scrapInBox(EntityAdmin& admin, QPoint tileA, QPoint tileB)
{
const int minX = std::min(tileA.x(), tileB.x());
const int maxX = std::max(tileA.x(), tileB.x());
const int minY = std::min(tileA.y(), tileB.y());
const int maxY = std::max(tileA.y(), tileB.y());
std::vector<entt::entity> result;
admin.forEach<ScrapDataComponent, PositionComponent>(
[&](entt::entity entity, const ScrapDataComponent& /*sd*/, const PositionComponent& pos)
{
const int tileX = static_cast<int>(std::floor(pos.value.x()));
const int tileY = static_cast<int>(std::floor(pos.value.y()));
if (tileX >= minX && tileX <= maxX && tileY >= minY && tileY <= maxY)
{
result.push_back(entity);
}
});
return result;
}
std::vector<entt::entity> actorsInBox(EntityAdmin& admin, QPoint tileA, QPoint tileB)
{
const int minX = std::min(tileA.x(), tileB.x());
const int maxX = std::max(tileA.x(), tileB.x());
const int minY = std::min(tileA.y(), tileB.y());
const int maxY = std::max(tileA.y(), tileB.y());
std::vector<entt::entity> result;
// Stations: included when any occupied body cell lies in the box.
admin.forEach<StationBodyComponent, HealthComponent>(
[&](entt::entity entity, const StationBodyComponent& sb, const HealthComponent& h)
{
if (h.hp <= 0.0f) { return; }
for (const QPoint& cell : sb.bodyCells)
{
if (cell.x() >= minX && cell.x() <= maxX
&& cell.y() >= minY && cell.y() <= maxY)
{
result.push_back(entity);
return;
}
}
});
// Ships: included when the floored position tile lies in the box. Requiring
// ShipIdentityComponent excludes the HQ proxy and any station bodies.
admin.forEach<ShipIdentityComponent, PositionComponent, HealthComponent>(
[&](entt::entity entity, const ShipIdentityComponent& /*id*/,
const PositionComponent& pos, const HealthComponent& h)
{
if (h.hp <= 0.0f) { return; }
const int tileX = static_cast<int>(std::floor(pos.value.x()));
const int tileY = static_cast<int>(std::floor(pos.value.y()));
if (tileX >= minX && tileX <= maxX && tileY >= minY && tileY <= maxY)
{
result.push_back(entity);
}
});
return result;
}

View File

@@ -1,8 +1,5 @@
#pragma once
#include <vector>
#include <QPoint>
#include <QVector2D>
#include "entt/entity/entity.hpp"
@@ -10,19 +7,3 @@
class EntityAdmin;
entt::entity entityAtWorldPos(EntityAdmin& admin, QVector2D worldPos);
// Returns the nearest scrap pile whose center is within the scrap pick radius of
// worldPos, or entt::null if none (REQ-UI-SCRAP-CLICK-SELECT). Scrap is picked only
// after actors: entityAtWorldPos never returns scrap (scrap has no HealthComponent).
entt::entity scrapAtWorldPos(EntityAdmin& admin, QVector2D worldPos);
// Returns every scrap pile whose position falls within the inclusive tile rectangle
// spanned by tileA and tileB, in any corner order (REQ-UI-SCRAP-MULTI-SELECT).
std::vector<entt::entity> scrapInBox(EntityAdmin& admin, QPoint tileA, QPoint tileB);
// Returns every living actor (ship or defence station, player or enemy) that falls
// within the inclusive tile rectangle spanned by tileA and tileB, in any corner order
// (REQ-UI-MULTI-SELECT, REQ-UI-ENTITY-CLICK-SELECT). A ship is included when its floored
// position tile lies in the box; a station is included when any of its body cells does.
// Dead actors (hp <= 0) and the HQ proxy are excluded.
std::vector<entt::entity> actorsInBox(EntityAdmin& admin, QPoint tileA, QPoint tileB);

View File

@@ -48,7 +48,7 @@ void ReplayPlayer::processEntriesAt(Tick tick)
{
m_simulation.apply(*entry.command);
}
else if (m_simulation.getRngFingerprint() != entry.fingerprint)
else if (m_simulation.rngFingerprint() != entry.fingerprint)
{
m_desyncTick = tick;
}

View File

@@ -19,7 +19,7 @@ class Simulation;
// each frame, for each tick to run:
// if (player.isFinished()) break;
// sim.tick();
// player.advanceTo(sim.getCurrentTick());
// player.advanceTo(sim.currentTick());
class ReplayPlayer
{
public:

View File

@@ -58,7 +58,7 @@ std::string computeReplayConfigHash(const std::string& configDir)
hasher.appendBytes(bytes.constData(), static_cast<std::size_t>(bytes.size()));
}
}
return toHex(hasher.getValue());
return toHex(hasher.value());
}
void ReplayRecorder::startNewRun(unsigned int seed, std::uint64_t initialRngFingerprint)
@@ -124,7 +124,7 @@ bool ReplayRecorder::isOpen() const
return m_stream.is_open();
}
const std::string& ReplayRecorder::getCurrentFilePath() const
const std::string& ReplayRecorder::currentFilePath() const
{
return m_filePath;
}

View File

@@ -44,7 +44,7 @@ public:
void close();
bool isOpen() const;
const std::string& getCurrentFilePath() const;
const std::string& currentFilePath() const;
private:
std::string m_configDir;

View File

@@ -40,6 +40,7 @@ Simulation::Simulation(GameConfig config, unsigned int seed)
, m_nextBuildingId(1)
, m_buildingBlocksStock(m_config.world.startingBuildingBlocks)
, m_gameOver(false)
, m_hqBuildingId(kInvalidBuildingId)
, m_hqProxyEntity(entt::null)
, m_playerStation1Entity(entt::null)
, m_playerStation2Entity(entt::null)
@@ -75,7 +76,34 @@ Simulation::Simulation(GameConfig config, unsigned int seed)
m_waveSystem = std::make_unique<WaveSystem>(m_config, m_rng);
m_combatSystem = std::make_unique<CombatSystem>(m_config);
initializeUnlockState();
// Initialize ship schematic unlock state.
for (const ShipDef& def : m_config.ships.ships)
{
SchematicState state;
state.unlocked = (def.unlockAtStationLevel == -1);
m_schematicLevels[def.id] = state;
}
// Initialize module schematic unlock state.
for (const ModuleDef& def : m_config.modules.modules)
{
SchematicState state;
state.unlocked = (def.unlockAtStationLevel == -1);
m_moduleSchematicLevels[def.id] = state;
}
// Initialize assembler recipe schematic unlock state.
for (const RecipeDef& def : m_config.recipes.recipes)
{
if (def.building == BuildingType::Assembler
&& def.unlockAtStationLevel.has_value()
&& def.unlockAtStationLevel.value() == -1)
{
m_unlockedRecipeSchematicIds.insert(def.id);
}
}
recomputeUnlocked();
placeInitialStructures();
registerForEvents();
}
@@ -85,7 +113,7 @@ Simulation::~Simulation()
unregisterForEvents();
}
const GameConfig& Simulation::getConfig() const
const GameConfig& Simulation::config() const
{
return m_config;
}
@@ -109,7 +137,7 @@ void Simulation::reset(unsigned int seed)
m_gameOver = false;
m_isWon = false;
m_artifactCount = 0;
m_hqBuildingId = std::nullopt;
m_hqBuildingId = kInvalidBuildingId;
m_hqProxyEntity = entt::null;
m_playerStation1Entity = entt::null;
m_playerStation2Entity = entt::null;
@@ -147,33 +175,11 @@ void Simulation::reset(unsigned int seed)
m_waveSystem = std::make_unique<WaveSystem>(m_config, m_rng);
m_combatSystem = std::make_unique<CombatSystem>(m_config);
initializeUnlockState();
placeInitialStructures();
}
void Simulation::initializeUnlockState()
{
// Cache the ids granted by some unlock group (REQ-LOCK-EXPLICIT); an item
// starts locked iff it is granted by a group.
m_grantedShipIds.clear();
m_grantedModuleIds.clear();
m_grantedBuildingIds.clear();
m_grantedRecipeIds.clear();
for (const UnlockGroupDef& group : m_config.unlocks.groups)
{
m_grantedShipIds.insert(group.ships.begin(), group.ships.end());
m_grantedModuleIds.insert(group.modules.begin(), group.modules.end());
m_grantedBuildingIds.insert(group.buildings.begin(), group.buildings.end());
m_grantedRecipeIds.insert(group.recipes.begin(), group.recipes.end());
}
m_awardedUnlockGroupIds.clear();
m_schematicLevels.clear();
for (const ShipDef& def : m_config.ships.ships)
{
SchematicState state;
state.unlocked = (m_grantedShipIds.count(def.id) == 0);
state.unlocked = (def.unlockAtStationLevel == -1);
m_schematicLevels[def.id] = state;
}
@@ -181,23 +187,23 @@ void Simulation::initializeUnlockState()
for (const ModuleDef& def : m_config.modules.modules)
{
SchematicState state;
state.unlocked = (m_grantedModuleIds.count(def.id) == 0);
state.unlocked = (def.unlockAtStationLevel == -1);
m_moduleSchematicLevels[def.id] = state;
}
m_buildingLevels.clear();
for (const BuildingDef& def : m_config.buildings.buildings)
m_unlockedRecipeSchematicIds.clear();
for (const RecipeDef& def : m_config.recipes.recipes)
{
SchematicState state;
state.unlocked = (m_grantedBuildingIds.count(def.id) == 0);
m_buildingLevels[def.id] = state;
if (def.building == BuildingType::Assembler
&& def.unlockAtStationLevel.has_value()
&& def.unlockAtStationLevel.value() == -1)
{
m_unlockedRecipeSchematicIds.insert(def.id);
}
}
// Gated assembler recipes start locked; unlocked_at_start recipes are handled
// in the REQ-LOCK-IMPLICIT traversal, not tracked here.
m_unlockedRecipeSchematicIds.clear();
recomputeUnlocked();
placeInitialStructures();
}
// ---------------------------------------------------------------------------
@@ -211,12 +217,11 @@ void Simulation::apply(const Command& command)
case CommandKind::PlaceBuilding:
{
const PlaceBuildingCommand& c = static_cast<const PlaceBuildingCommand&>(command);
const std::optional<BuildingId> placed = tryPlaceBuilding(c.type, c.anchor, c.rotation);
if (!placed.has_value())
const BuildingId id = tryPlaceBuilding(c.type, c.anchor, c.rotation);
if (id == kInvalidBuildingId)
{
break;
}
const BuildingId id = *placed;
if (c.recipeId.has_value())
{
m_buildingSystem->setRecipe(id, *c.recipeId);
@@ -231,35 +236,32 @@ void Simulation::apply(const Command& command)
}
break;
}
case CommandKind::Deconstruct:
deconstruct(*static_cast<const DeconstructCommand&>(command).id);
break;
case CommandKind::CancelDeconstruction:
cancelDeconstruction(*static_cast<const CancelDeconstructionCommand&>(command).id);
case CommandKind::Demolish:
demolish(static_cast<const DemolishCommand&>(command).id);
break;
case CommandKind::RotateInPlace:
{
const RotateInPlaceCommand& c = static_cast<const RotateInPlaceCommand&>(command);
m_buildingSystem->rotateInPlace(*c.id, c.newRotation);
m_buildingSystem->rotateInPlace(c.id, c.newRotation);
break;
}
case CommandKind::SetRecipe:
{
const SetRecipeCommand& c = static_cast<const SetRecipeCommand&>(command);
m_buildingSystem->setRecipe(*c.id, c.recipeId);
m_buildingSystem->setRecipe(c.id, c.recipeId);
break;
}
case CommandKind::SetShipLayout:
{
const SetShipLayoutCommand& c = static_cast<const SetShipLayoutCommand&>(command);
m_buildingSystem->setShipLayout(*c.id, c.layout);
m_buildingSystem->setShipLayout(c.id, c.layout);
break;
}
case CommandKind::SetSiteSplitterFilters:
{
const SetSiteSplitterFiltersCommand& c =
static_cast<const SetSiteSplitterFiltersCommand&>(command);
m_buildingSystem->setSiteSplitterFilters(*c.id, c.filterA, c.filterB);
m_buildingSystem->setSiteSplitterFilters(c.id, c.filterA, c.filterB);
break;
}
case CommandKind::SetSplitterFilters:
@@ -310,11 +312,10 @@ void Simulation::tick()
// Construction + production pipeline
m_buildingSystem->tickConstruction(m_currentTick);
m_buildingSystem->tickDeconstruction(m_currentTick); // parallel to construction
m_buildingSystem->tickBeltPull(); // step 3
m_buildingSystem->tickProduction(m_currentTick); // step 4
m_buildingSystem->tickShipyardProduction(m_currentTick); // step 4b
m_buildingSystem->tickOutputBelts(); // step 5
m_buildingSystem->tickBeltPush(); // step 5
m_beltSystem.tick(); // step 6
// Step 7: ship behavior systems (movement arbitration via intent priority)
@@ -578,7 +579,7 @@ void Simulation::tickDeathsAndLoot()
}
else
{
const double genD = static_cast<double>(m_waveSystem->getGeneration());
const double genD = static_cast<double>(m_waveSystem->generation());
scrap = static_cast<int>(
m_config.stations.enemyStation.scrapDropFormula.evaluate(genD));
}
@@ -618,25 +619,52 @@ void Simulation::tickDeathsAndLoot()
if (es0Gone && es1Gone &&
m_currentEnemyStationEntities[0] != entt::null)
{
const int destroyedLevel = m_waveSystem->getGeneration();
const int destroyedLevel = m_waveSystem->generation();
m_waveSystem->onEnemyStationsDestroyed();
placeEnemyStationSet(m_waveSystem->getGeneration());
placeEnemyStationSet(m_waveSystem->generation());
generateSchematicChoices(destroyedLevel);
}
}
void Simulation::generateSchematicChoices(int destroyedStationLevel)
{
// Build the eligible pool of unlock groups (REQ-DEF-SCHEMATIC-DROP,
// REQ-LOCK-EXPLICIT, REQ-LOCK-PREREQ): not yet awarded, station level in
// range, and every prerequisite group already awarded.
std::vector<const UnlockGroupDef*> pool;
for (const UnlockGroupDef& group : m_config.unlocks.groups)
enum class DropType { Ship, Module, Recipe };
struct PoolEntry { std::string id; DropType type; };
std::vector<PoolEntry> pool;
// Owned schematics leave the pool (REQ-DEF-SCHEMATIC-DROP): only offer
// ship/module schematics that are gated to a station level in range and not
// yet unlocked. Schematics with unlock_at_station_level -1 start unlocked, so
// they are always owned and never eligible.
for (const ShipDef& def : m_config.ships.ships)
{
if (m_awardedUnlockGroupIds.count(group.id) > 0) { continue; }
if (group.stationLevel < 0 || group.stationLevel > destroyedStationLevel) { continue; }
if (!prerequisitesSatisfied(group.requiredGroupIds)) { continue; }
pool.push_back(&group);
if (def.unlockAtStationLevel < 0 || def.unlockAtStationLevel > destroyedStationLevel) { continue; }
if (m_schematicLevels.at(def.id).unlocked) { continue; }
if (!prerequisitesSatisfied(def.unlockRequires)) { continue; }
pool.push_back({def.id, DropType::Ship});
}
for (const ModuleDef& def : m_config.modules.modules)
{
if (def.unlockAtStationLevel < 0 || def.unlockAtStationLevel > destroyedStationLevel) { continue; }
if (m_moduleSchematicLevels.at(def.id).unlocked) { continue; }
if (!prerequisitesSatisfied(def.unlockRequires)) { continue; }
pool.push_back({def.id, DropType::Module});
}
for (const RecipeDef& def : m_config.recipes.recipes)
{
if (def.building != BuildingType::Assembler) { continue; }
if (!def.unlockAtStationLevel.has_value()) { continue; }
const int level = def.unlockAtStationLevel.value();
if (level < 0 || level > destroyedStationLevel) { continue; }
if (m_unlockedRecipeSchematicIds.count(def.id) > 0) { continue; }
bool outputUnlocked = false;
for (const RecipeOutput& out : def.outputs)
{
if (m_unlockedItemIds.count(out.item) > 0) { outputUnlocked = true; break; }
}
if (!outputUnlocked) { continue; }
if (!prerequisitesSatisfied(def.unlockRequires)) { continue; }
pool.push_back({def.id, DropType::Recipe});
}
if (pool.empty()) { return; }
@@ -651,6 +679,9 @@ void Simulation::generateSchematicChoices(int destroyedStationLevel)
const int numChoices = std::min(static_cast<int>(pool.size()), artifactRolled ? 2 : 3);
m_pendingSchematicChoices.clear();
const std::set<std::string> currentShipIds = getUnlockedShipSchematicIds();
const std::set<std::string> currentModuleIds = getUnlockedModuleSchematicIds();
for (int i = 0; i < numChoices; ++i)
{
std::uniform_int_distribution<int> dist(0, static_cast<int>(pool.size()) - 1 - i);
@@ -658,67 +689,75 @@ void Simulation::generateSchematicChoices(int destroyedStationLevel)
const std::size_t rollIdx = static_cast<std::size_t>(roll);
const std::size_t endIdx = pool.size() - 1 - static_cast<std::size_t>(i);
std::swap(pool[rollIdx], pool[endIdx]);
const PoolEntry& entry = pool[endIdx];
m_pendingSchematicChoices.push_back(makeUnlockOption(*pool[endIdx]));
SchematicChoiceOption option;
option.schematicId = entry.id;
if (entry.type == DropType::Ship)
{
option.type = SchematicType::Ship;
option.displayName = toDisplayName(entry.id);
}
else if (entry.type == DropType::Module)
{
option.type = SchematicType::Module;
option.displayName = toDisplayName(entry.id);
}
else
{
option.type = SchematicType::Recipe;
for (const RecipeDef& def : m_config.recipes.recipes)
{
if (def.id == entry.id && !def.outputs.empty())
{
option.displayName = toDisplayName(def.outputs[0].item);
break;
}
}
}
// REQ-DEF-SCHEMATIC-DROP: preview recipes newly implicitly unlocked by this option.
std::set<std::string> hypotheticalShipIds = currentShipIds;
std::set<std::string> hypotheticalModuleIds = currentModuleIds;
std::set<std::string> hypotheticalRecipeSchematicIds = m_unlockedRecipeSchematicIds;
if (entry.type == DropType::Ship)
{
hypotheticalShipIds.insert(entry.id);
}
else if (entry.type == DropType::Module)
{
hypotheticalModuleIds.insert(entry.id);
}
else if (entry.type == DropType::Recipe)
{
hypotheticalRecipeSchematicIds.insert(entry.id);
}
const UnlockedSets hypothetical = computeUnlockedSets(
hypotheticalShipIds, hypotheticalModuleIds, hypotheticalRecipeSchematicIds);
option.newlyUnlockedItemNames = computeNewlyUnlockedItemNames(hypothetical);
m_pendingSchematicChoices.push_back(option);
}
if (artifactRolled)
{
SchematicChoiceOption artifactOption;
artifactOption.isArtifact = true;
artifactOption.displayName = "Artifact";
artifactOption.schematicId = "";
artifactOption.type = SchematicType::Artifact;
artifactOption.displayName = "Artifact";
m_pendingSchematicChoices.push_back(std::move(artifactOption));
}
}
SchematicChoiceOption Simulation::makeUnlockOption(const UnlockGroupDef& group) const
{
SchematicChoiceOption option;
option.isArtifact = false;
option.unlockGroupId = group.id;
option.displayName = toDisplayName(group.id);
for (const std::string& id : group.ships)
{
option.grantedItems.push_back({SchematicType::Ship, id, toDisplayName(id)});
}
for (const std::string& id : group.modules)
{
option.grantedItems.push_back({SchematicType::Module, id, toDisplayName(id)});
}
for (const std::string& id : group.buildings)
{
option.grantedItems.push_back({SchematicType::Building, id, toDisplayName(id)});
}
for (const std::string& id : group.recipes)
{
option.grantedItems.push_back({SchematicType::Recipe, id, toDisplayName(id)});
}
// REQ-DEF-SCHEMATIC-DROP: preview recipes newly implicitly unlocked by
// awarding this whole group. Seed the hypothetical explicit-unlock sets with
// every grant (ship + module materials via step 1a, recipe outputs via step
// 1b), then diff against the current implicit set.
std::set<std::string> hypotheticalShipIds = getUnlockedShipSchematicIds();
std::set<std::string> hypotheticalModuleIds = getUnlockedModuleSchematicIds();
std::set<std::string> hypotheticalRecipeSchematicIds = m_unlockedRecipeSchematicIds;
for (const std::string& id : group.ships) { hypotheticalShipIds.insert(id); }
for (const std::string& id : group.modules) { hypotheticalModuleIds.insert(id); }
for (const std::string& id : group.recipes) { hypotheticalRecipeSchematicIds.insert(id); }
const UnlockedSets hypothetical = computeUnlockedSets(
hypotheticalShipIds, hypotheticalModuleIds, hypotheticalRecipeSchematicIds);
option.newlyUnlockedRecipeIds = computeNewlyUnlockedRecipeIds(hypothetical);
return option;
}
void Simulation::applySchematicChoice(int choiceIndex)
{
assert(choiceIndex >= 0 && choiceIndex < static_cast<int>(m_pendingSchematicChoices.size()));
const SchematicChoiceOption& chosen = m_pendingSchematicChoices[static_cast<std::size_t>(choiceIndex)];
if (chosen.isArtifact)
if (chosen.type == SchematicType::Artifact)
{
m_artifactCount += 1;
if (m_artifactCount >= m_config.world.artifacts.artifactWinCount)
@@ -729,18 +768,16 @@ void Simulation::applySchematicChoice(int choiceIndex)
return;
}
// Award the whole unlock group (REQ-DEF-SCHEMATIC-DROP): unlock every granted
// ship, module, building, and assembler recipe at once.
m_awardedUnlockGroupIds.insert(chosen.unlockGroupId);
for (const GrantedSchematic& grant : chosen.grantedItems)
if (chosen.type == SchematicType::Recipe)
{
switch (grant.type)
{
case SchematicType::Ship: m_schematicLevels.at(grant.id).unlocked = true; break;
case SchematicType::Module: m_moduleSchematicLevels.at(grant.id).unlocked = true; break;
case SchematicType::Building: m_buildingLevels.at(grant.id).unlocked = true; break;
case SchematicType::Recipe: m_unlockedRecipeSchematicIds.insert(grant.id); break;
}
m_unlockedRecipeSchematicIds.insert(chosen.schematicId);
}
else
{
SchematicState& state = (chosen.type == SchematicType::Module)
? m_moduleSchematicLevels.at(chosen.schematicId)
: m_schematicLevels.at(chosen.schematicId);
state.unlocked = true;
}
recomputeUnlocked();
@@ -779,13 +816,28 @@ std::set<std::string> Simulation::getUnlockedModuleSchematicIds() const
return ids;
}
bool Simulation::prerequisitesSatisfied(const std::vector<std::string>& requiredGroupIds) const
bool Simulation::isSchematicIdExplicitlyUnlocked(const std::string& schematicId) const
{
// A prerequisite is satisfied only once the named unlock group has been
// awarded (REQ-LOCK-PREREQ).
for (const std::string& groupId : requiredGroupIds)
// A prerequisite is satisfied only by an explicitly-unlocked schematic
// (REQ-LOCK-PREREQ): a ship or module schematic marked unlocked, or a recipe
// schematic in the explicit-unlock set. Cross-type ids are looked up with
// find/count so an id from one namespace never throws against another.
const std::map<std::string, SchematicState>::const_iterator shipIt =
m_schematicLevels.find(schematicId);
if (shipIt != m_schematicLevels.end() && shipIt->second.unlocked) { return true; }
const std::map<std::string, SchematicState>::const_iterator moduleIt =
m_moduleSchematicLevels.find(schematicId);
if (moduleIt != m_moduleSchematicLevels.end() && moduleIt->second.unlocked) { return true; }
return m_unlockedRecipeSchematicIds.count(schematicId) > 0;
}
bool Simulation::prerequisitesSatisfied(const std::vector<std::string>& unlockRequires) const
{
for (const std::string& requiredId : unlockRequires)
{
if (m_awardedUnlockGroupIds.count(groupId) == 0) { return false; }
if (!isSchematicIdExplicitlyUnlocked(requiredId)) { return false; }
}
return true;
}
@@ -815,11 +867,9 @@ Simulation::UnlockedSets Simulation::computeUnlockedSets(
}
for (const RecipeDef& def : m_config.recipes.recipes)
{
// An assembler recipe seeds the base set when it is explicitly available:
// flagged unlocked_at_start (base recipes the graph can't reach), or a
// gated recipe whose unlock group has been awarded (REQ-LOCK-EXPLICIT).
if (def.building == BuildingType::Assembler
&& (def.unlockedAtStart || unlockedRecipeSchematicIds.count(def.id) > 0))
&& def.unlockAtStationLevel.has_value()
&& unlockedRecipeSchematicIds.count(def.id) > 0)
{
for (const RecipeOutput& out : def.outputs)
{
@@ -840,10 +890,8 @@ Simulation::UnlockedSets Simulation::computeUnlockedSets(
{
continue;
}
// Skip a gated assembler recipe (granted by an unlock group) whose
// group has not yet been awarded (REQ-LOCK-IMPLICIT step 2).
if (recipe.building == BuildingType::Assembler
&& m_grantedRecipeIds.count(recipe.id) > 0
&& recipe.unlockAtStationLevel.has_value()
&& unlockedRecipeSchematicIds.count(recipe.id) == 0)
{
continue;
@@ -877,20 +925,23 @@ Simulation::UnlockedSets Simulation::computeUnlockedSets(
return result;
}
std::vector<std::string> Simulation::computeNewlyUnlockedRecipeIds(const UnlockedSets& hypothetical) const
std::vector<std::string> Simulation::computeNewlyUnlockedItemNames(const UnlockedSets& hypothetical) const
{
std::vector<std::string> recipeIds;
std::set<std::string> itemNames;
for (const std::string& recipeId : hypothetical.recipeIds)
{
if (m_unlockedRecipeIds.count(recipeId) > 0) { continue; }
recipeIds.push_back(recipeId);
for (const RecipeDef& def : m_config.recipes.recipes)
{
if (def.id != recipeId) { continue; }
for (const RecipeOutput& out : def.outputs)
{
itemNames.insert(toDisplayName(out.item));
}
break;
}
}
std::sort(recipeIds.begin(), recipeIds.end(),
[](const std::string& lhs, const std::string& rhs)
{
return toDisplayName(lhs) < toDisplayName(rhs);
});
return recipeIds;
return std::vector<std::string>(itemNames.begin(), itemNames.end());
}
bool Simulation::isRecipeUnlocked(const std::string& recipeId) const
@@ -927,7 +978,7 @@ void Simulation::appendStringSet(Hasher& hasher, const std::set<std::string>& id
}
}
unsigned long long Simulation::getRngFingerprint() const
unsigned long long Simulation::rngFingerprint() const
{
return fingerprintRng(m_rng);
}
@@ -950,17 +1001,15 @@ unsigned long long Simulation::computeStateChecksum() const
hasher.append(m_expansionsPurchased);
// WaveSystem scalar state, reached through existing accessors.
hasher.append(getThreatLevel());
hasher.append(getThreatAccumulationRate());
hasher.append(getBossWaveCounter());
hasher.append(getBossCountdownTicks());
hasher.append(getNormalGapRemainingTicks());
hasher.append(threatLevel());
hasher.append(threatAccumulationRate());
hasher.append(bossWaveCounter());
hasher.append(bossCountdownTicks());
hasher.append(normalGapRemainingTicks());
// Schematic / unlock state (std::map and std::set iterate in sorted order).
appendSchematicMap(hasher, m_schematicLevels);
appendSchematicMap(hasher, m_moduleSchematicLevels);
appendSchematicMap(hasher, m_buildingLevels);
appendStringSet(hasher, m_awardedUnlockGroupIds);
appendStringSet(hasher, m_unlockedRecipeSchematicIds);
appendStringSet(hasher, m_unlockedRecipeIds);
appendStringSet(hasher, m_unlockedItemIds);
@@ -1013,7 +1062,7 @@ unsigned long long Simulation::computeStateChecksum() const
hasher.append(c.schematicId);
});
return hasher.getValue();
return hasher.value();
}
// ---------------------------------------------------------------------------
@@ -1042,7 +1091,7 @@ bool Simulation::hasSchematicChoicesPending() const
// Accessors
// ---------------------------------------------------------------------------
Tick Simulation::getCurrentTick() const
Tick Simulation::currentTick() const
{
return m_currentTick;
}
@@ -1052,18 +1101,18 @@ unsigned int Simulation::getSeed() const
return m_seed;
}
int Simulation::getBuildingBlocksStock() const
int Simulation::buildingBlocksStock() const
{
return m_buildingBlocksStock;
}
int Simulation::getCurrentAsteroidWidth_tiles() const
int Simulation::currentAsteroidWidth_tiles() const
{
return m_config.world.regions.asteroidWidth_tiles
+ m_expansionsPurchased * m_config.world.expansion.columnsPerExpansion_tiles;
}
int Simulation::getCurrentExpansionCost() const
int Simulation::currentExpansionCost() const
{
const double cost = m_config.world.expansion.costBuildingBlocksFormula.evaluate(
static_cast<double>(m_expansionsPurchased));
@@ -1072,14 +1121,14 @@ int Simulation::getCurrentExpansionCost() const
void Simulation::tryExpandAsteroid()
{
const int cost = getCurrentExpansionCost();
const int cost = currentExpansionCost();
if (m_buildingBlocksStock < cost)
{
return;
}
m_buildingBlocksStock -= cost;
++m_expansionsPurchased;
m_buildingSystem->setAsteroidWidth_tiles(getCurrentAsteroidWidth_tiles());
m_buildingSystem->setAsteroidWidth_tiles(currentAsteroidWidth_tiles());
}
bool Simulation::isGameOver() const
@@ -1092,44 +1141,44 @@ bool Simulation::isWon() const
return m_isWon;
}
int Simulation::getArtifactCount() const
int Simulation::artifactCount() const
{
return m_artifactCount;
}
double Simulation::getThreatLevel() const
double Simulation::threatLevel() const
{
return m_waveSystem->getThreatLevel();
return m_waveSystem->threatLevel();
}
double Simulation::getThreatAccumulationRate() const
double Simulation::threatAccumulationRate() const
{
return m_waveSystem->getThreatAccumulationRate();
return m_waveSystem->threatAccumulationRate();
}
double Simulation::getMaxFactoryProductionThreatRate() const
double Simulation::maxFactoryProductionThreatRate() const
{
return static_cast<double>(m_buildingSystem->getProductionBuildingCount());
return static_cast<double>(m_buildingSystem->productionBuildingCount());
}
double Simulation::getCurrentFactoryProductionThreatRate() const
double Simulation::currentFactoryProductionThreatRate() const
{
return static_cast<double>(m_buildingSystem->getActiveProductionBuildingCount());
return static_cast<double>(m_buildingSystem->activeProductionBuildingCount());
}
int Simulation::getBossWaveCounter() const
int Simulation::bossWaveCounter() const
{
return m_waveSystem->getBossWaveCounter();
return m_waveSystem->bossWaveCounter();
}
Tick Simulation::getBossCountdownTicks() const
Tick Simulation::bossCountdownTicks() const
{
return m_waveSystem->getBossCountdownTicks();
return m_waveSystem->bossCountdownTicks();
}
Tick Simulation::getNormalGapRemainingTicks() const
Tick Simulation::normalGapRemainingTicks() const
{
return m_waveSystem->getNormalGapRemainingTicks();
return m_waveSystem->normalGapRemainingTicks();
}
bool Simulation::isSchematicUnlocked(const std::string& shipId) const
@@ -1154,31 +1203,11 @@ bool Simulation::isModuleSchematicUnlocked(const std::string& moduleId) const
return it->second.unlocked;
}
bool Simulation::isBuildingUnlocked(BuildingType type) const
BuildingId Simulation::tryPlaceBuilding(BuildingType type, QPoint anchor, Rotation rotation)
{
const BuildingDef* def = m_config.buildings.findBuildingDef(type);
if (def == nullptr)
{
// Types without a config entry (e.g. HQ, defence stations) are unrestricted.
return true;
}
const std::map<std::string, SchematicState>::const_iterator it =
m_buildingLevels.find(def->id);
return it == m_buildingLevels.end() ? true : it->second.unlocked;
}
std::optional<BuildingId> Simulation::tryPlaceBuilding(BuildingType type, QPoint anchor, Rotation rotation)
{
// Locked building types cannot be placed (REQ-LOCK-BUILDING); the build menu
// hides them, this is the simulation-side backstop (e.g. blueprint placement).
if (!isBuildingUnlocked(type))
{
return std::nullopt;
}
if (!m_buildingSystem->isPlacementValid(type, anchor, rotation))
{
return std::nullopt;
return kInvalidBuildingId;
}
int cost = 0;
@@ -1192,68 +1221,63 @@ std::optional<BuildingId> Simulation::tryPlaceBuilding(BuildingType type, QPoint
}
if (m_buildingBlocksStock < cost)
{
return std::nullopt;
return kInvalidBuildingId;
}
m_buildingBlocksStock -= cost;
return m_buildingSystem->place(type, anchor, rotation, m_currentTick);
}
void Simulation::deconstruct(BuildingId id)
void Simulation::demolish(BuildingId id)
{
m_buildingBlocksStock += m_buildingSystem->deconstruct(id, m_currentTick);
m_buildingBlocksStock += m_buildingSystem->demolish(id);
}
void Simulation::cancelDeconstruction(BuildingId id)
{
m_buildingSystem->cancelDeconstruction(id);
}
BuildingSystem& Simulation::getBuildingsMutable()
BuildingSystem& Simulation::buildingsMutable()
{
return *m_buildingSystem;
}
const BuildingSystem& Simulation::getBuildings() const
const BuildingSystem& Simulation::buildings() const
{
return *m_buildingSystem;
}
BeltSystem& Simulation::getBeltsMutable()
BeltSystem& Simulation::beltsMutable()
{
return m_beltSystem;
}
const BeltSystem& Simulation::getBelts() const
const BeltSystem& Simulation::belts() const
{
return m_beltSystem;
}
ShipSystem& Simulation::getShips()
ShipSystem& Simulation::ships()
{
return *m_shipSystem;
}
const ShipSystem& Simulation::getShips() const
const ShipSystem& Simulation::ships() const
{
return *m_shipSystem;
}
ScrapSystem& Simulation::getScraps()
ScrapSystem& Simulation::scraps()
{
return *m_scrapSystem;
}
const ScrapSystem& Simulation::getScraps() const
const ScrapSystem& Simulation::scraps() const
{
return *m_scrapSystem;
}
EntityAdmin& Simulation::getAdmin()
EntityAdmin& Simulation::admin()
{
return m_admin;
}
const EntityAdmin& Simulation::getAdmin() const
const EntityAdmin& Simulation::admin() const
{
return m_admin;
}

View File

@@ -2,7 +2,6 @@
#include <map>
#include <memory>
#include <optional>
#include <random>
#include <set>
#include <string>
@@ -42,7 +41,7 @@ public:
explicit Simulation(GameConfig config, unsigned int seed = 0);
~Simulation();
const GameConfig& getConfig() const;
const GameConfig& config() const;
// Reinitializes all simulation state as if constructed fresh.
void reset(unsigned int seed = 0);
@@ -69,26 +68,26 @@ public:
// Returns true if there are pending schematic choices waiting for player input.
bool hasSchematicChoicesPending() const;
Tick getCurrentTick() const;
Tick currentTick() const;
// The seed this run was (re)initialized with; written to the replay header.
unsigned int getSeed() const;
int getBuildingBlocksStock() const;
int buildingBlocksStock() const;
// Current asteroid width in tiles = base width + purchased expansions
// (REQ-EXP-UNLOCK, REQ-GW-ASTEROID-EXPAND).
int getCurrentAsteroidWidth_tiles() const;
int currentAsteroidWidth_tiles() const;
// Building block cost of the next expansion, floored to an integer
// (REQ-EXP-COST); x = number of expansions already purchased.
int getCurrentExpansionCost() const;
int currentExpansionCost() const;
bool isGameOver() const;
bool isWon() const;
int getArtifactCount() const;
double getThreatLevel() const;
double getThreatAccumulationRate() const;
double getMaxFactoryProductionThreatRate() const;
double getCurrentFactoryProductionThreatRate() const;
int getBossWaveCounter() const;
Tick getBossCountdownTicks() const;
Tick getNormalGapRemainingTicks() const;
int artifactCount() const;
double threatLevel() const;
double threatAccumulationRate() const;
double maxFactoryProductionThreatRate() const;
double currentFactoryProductionThreatRate() const;
int bossWaveCounter() const;
Tick bossCountdownTicks() const;
Tick normalGapRemainingTicks() const;
// Ship schematic state query.
bool isSchematicUnlocked(const std::string& shipId) const;
@@ -100,32 +99,28 @@ public:
bool isRecipeUnlocked(const std::string& recipeId) const;
bool isItemUnlocked(const std::string& itemId) const;
// Building unlock query (REQ-LOCK-BUILDING). True if the building type is not
// gated by any unlock group, or its granting group has been awarded.
bool isBuildingUnlocked(BuildingType type) const;
// -- Determinism (see docs/replay_design.md) -----------------------------
// 64-bit fingerprint of the RNG stream state. Cheap; written to the replay
// file periodically + after each command for desync detection.
unsigned long long getRngFingerprint() const;
unsigned long long rngFingerprint() const;
// 64-bit fingerprint of the full simulation state (RNG, scalars, buildings,
// belts, and ECS component state). Used by the double-run determinism test;
// a superset of getRngFingerprint().
// a superset of rngFingerprint().
unsigned long long computeStateChecksum() const;
// Const subsystem accessors (queries only). The mutable counterparts are
// private and reachable only through Simulation::apply (the command
// chokepoint) or, in tests, SimulationTestAccess — so production code cannot
// mutate the factory outside the recorded command path (docs/replay_design.md).
const BuildingSystem& getBuildings() const;
const BeltSystem& getBelts() const;
ShipSystem& getShips();
const ShipSystem& getShips() const;
ScrapSystem& getScraps();
const ScrapSystem& getScraps() const;
EntityAdmin& getAdmin();
const EntityAdmin& getAdmin() const;
const BuildingSystem& buildings() const;
const BeltSystem& belts() const;
ShipSystem& ships();
const ShipSystem& ships() const;
ScrapSystem& scraps();
const ScrapSystem& scraps() const;
EntityAdmin& admin();
const EntityAdmin& admin() const;
private:
// Grants tests access to the private player-action mutators below without
@@ -136,16 +131,11 @@ private:
// Reached during play exclusively via apply(); never called by UI/app code.
// Checks affordability, deducts building blocks, and places the building.
// Returns the new entity id, or nullopt if blocks are insufficient.
std::optional<BuildingId> tryPlaceBuilding(BuildingType type, QPoint anchor, Rotation rotation);
// Returns the new entity id, or kInvalidBuildingId if blocks are insufficient.
BuildingId tryPlaceBuilding(BuildingType type, QPoint anchor, Rotation rotation);
// Marks the building with the given id for demolition: a construction site is
// removed instantly (full refund), a built building is queued for timed
// deconstruction (REQ-BLD-DECON-QUEUE), refunded on completion.
void deconstruct(BuildingId id);
// Takes a queued building back out of the deconstruction queue (REQ-BLD-DECON-QUEUE).
void cancelDeconstruction(BuildingId id);
// Demolishes the building with the given id and refunds building blocks.
void demolish(BuildingId id);
// Applies the player's chosen schematic from the pending choices.
// choiceIndex must be in [0, pendingChoices.size()).
@@ -158,8 +148,8 @@ private:
void tryExpandAsteroid();
// Mutable subsystem accessors; same chokepoint rule as the mutators above.
BuildingSystem& getBuildingsMutable();
BeltSystem& getBeltsMutable();
BuildingSystem& buildingsMutable();
BeltSystem& beltsMutable();
void handleEvent(std::shared_ptr<const TracePrintRequestedEvent> event) override;
@@ -192,7 +182,7 @@ private:
int m_artifactCount = 0;
// Pre-placed structure IDs.
std::optional<BuildingId> m_hqBuildingId; // Building id (for belt integration)
BuildingId m_hqBuildingId; // Building id (for belt integration)
entt::entity m_hqProxyEntity; // ECS entity (HP, targeting)
entt::entity m_playerStation1Entity;
entt::entity m_playerStation2Entity;
@@ -205,24 +195,6 @@ private:
};
std::map<std::string, SchematicState> m_schematicLevels;
std::map<std::string, SchematicState> m_moduleSchematicLevels;
std::map<std::string, SchematicState> m_buildingLevels;
// Unlock groups awarded so far (REQ-LOCK-EXPLICIT). Group ids.
std::set<std::string> m_awardedUnlockGroupIds;
// Ids granted by some unlock group, per kind — cached from config at init.
// An item starts locked iff it appears in the corresponding set.
std::set<std::string> m_grantedShipIds;
std::set<std::string> m_grantedModuleIds;
std::set<std::string> m_grantedBuildingIds;
std::set<std::string> m_grantedRecipeIds;
// Builds the granted-id sets and initializes all per-item unlock maps from
// them (shared by the constructor and reset). Ends with recomputeUnlocked().
void initializeUnlockState();
// Builds a schematic choice option for one unlock group (REQ-DEF-SCHEMATIC-DROP).
SchematicChoiceOption makeUnlockOption(const UnlockGroupDef& group) const;
// Determinism helpers — fold sub-state into the hasher in deterministic order.
static void appendSchematicMap(Hasher& hasher,
@@ -255,12 +227,15 @@ private:
std::set<std::string> getUnlockedShipSchematicIds() const;
std::set<std::string> getUnlockedModuleSchematicIds() const;
// True if every prerequisite unlock group has been awarded (REQ-LOCK-PREREQ).
bool prerequisitesSatisfied(const std::vector<std::string>& requiredGroupIds) const;
// True if schematicId names a currently explicitly-unlocked ship, module, or
// assembler recipe schematic (REQ-LOCK-PREREQ satisfaction basis).
bool isSchematicIdExplicitlyUnlocked(const std::string& schematicId) const;
// True if every prerequisite in unlockRequires is explicitly unlocked (REQ-LOCK-PREREQ).
bool prerequisitesSatisfied(const std::vector<std::string>& unlockRequires) const;
// Ids (sorted alphabetically by display name) of the recipes in
// Display names (deduplicated, alphabetical) of output items of recipes in
// hypothetical.recipeIds that are not yet in m_unlockedRecipeIds.
std::vector<std::string> computeNewlyUnlockedRecipeIds(const UnlockedSets& hypothetical) const;
std::vector<std::string> computeNewlyUnlockedItemNames(const UnlockedSets& hypothetical) const;
EntityAdmin m_admin;
BeltSystem m_beltSystem;

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