feat(simulation): implement economics integration sprint — #810 #821 #822 #823

Implements the full D-180/D-181 economics pipeline:

**#810 — Event input port (D-180)**
- Add EconEvent struct with Target/Effect/Duration/Visibility variants
- Implement EventPort as typed input queue for external disruptions
- Apply events in simulation step; D-179 Test 3 now uses real shock injection

**#821 — Integrate econ-sim into server tick loop**
- Extract econ-sim as library crate (lib.rs + sim.rs, Cargo.toml [lib] section)
- Add Simulation stateful runner; step() advances one economy tick
- Add EconSimResource, EconStateResource (7 D-181 signals), tick_economy_simulation
- Economy loads once at startup; graceful no-op when systems.db absent
- Server advances economy 1 tick per 10 game ticks (D-031)

**#822 — Expose economy state over IPC bridge**
- Protocol version 20 → 21
- Add EconomySnapshot, EconNodeSnapshot wire types
- Add EconStateQuery PlayerAction variant; response in economy_snapshot field
- Add EconQueryBuffer resource + serve_econ_state_query system

**#823 — Economics debug commands**
- Add InjectEconEvent, SetEconParam, GetEconState to DebugCommandKind
- Add EconDebugEffect, EconParamKind enums
- SetEconParam mutates α/β at runtime (α/β promoted to pub const + Simulation fields)
- ALPHA and BETA constants threaded through step_inner/trade_step signatures

All 1147 unit tests pass; zero warnings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-10 13:13:52 +02:00
co-authored by Claude Sonnet 4.6
parent 9d9ea96be1
commit 5f4139bc9e
19 changed files with 1471 additions and 122 deletions
+133 -1
View File
@@ -8,7 +8,11 @@
use bevy_ecs::prelude::*;
use crate::bridge::types::{DebugCommandKind, DebugEnabled, DebugResponsePayload, SnapshotBuffer};
use crate::bridge::types::{
DebugCommandKind, DebugEnabled, DebugResponsePayload, EconDebugEffect, EconParamKind,
SnapshotBuffer,
};
use crate::simulation::economy::{EconSimResource, EconStateResource};
use crate::knowledge::EntityRegistry;
use crate::npc::Npc;
use crate::simulation::conversation::NpcName;
@@ -69,6 +73,8 @@ pub fn handle_debug_commands(
(Entity, &TilePosition, Option<&NpcName>),
(With<Npc>, With<ActiveSim>, Without<PlayerCharacter>),
>,
mut econ_sim: Option<ResMut<EconSimResource>>,
econ_state: Option<Res<EconStateResource>>,
) {
// Gate: debug must be enabled
let enabled = debug_enabled.as_ref().is_some_and(|d| d.0);
@@ -325,6 +331,132 @@ pub fn handle_debug_commands(
}
}
}
DebugCommandKind::InjectEconEvent {
ref target,
ref effect,
magnitude,
duration_ticks,
} => {
use econ_sim::events::{EconEvent, EconEventEffect, EconEventTarget, EconEventVisibility};
if let Some(ref mut sim) = econ_sim {
let econ_effect = match effect {
EconDebugEffect::CapacityMultiplier => {
EconEventEffect::CapacityMultiplier(magnitude)
}
EconDebugEffect::ProductivityMultiplier => {
EconEventEffect::ProductivityMultiplier(magnitude)
}
EconDebugEffect::DemandShock => {
EconEventEffect::DemandShock(magnitude)
}
EconDebugEffect::ExchangeShock => {
EconEventEffect::ExchangeShock(magnitude)
}
};
sim.sim.events.push(EconEvent {
target: EconEventTarget::Node(target.clone()),
effect: econ_effect,
duration: duration_ticks,
visibility: EconEventVisibility::Global,
});
DebugResponsePayload {
command: format!("InjectEconEvent({}, {:?}, {}×{})", target, effect, magnitude, duration_ticks),
text: format!(
"Event injected: {:?} ×{} on node '{}' for {} ticks.\nTakes effect on next economy tick.",
effect, magnitude, target, duration_ticks
),
success: true,
}
} else {
DebugResponsePayload {
command: "InjectEconEvent".to_string(),
text: "Economy simulation not loaded.".to_string(),
success: false,
}
}
}
DebugCommandKind::SetEconParam { ref param, value } => {
if let Some(ref mut sim) = econ_sim {
match param {
EconParamKind::TatonnementStep => {
let old = sim.sim.alpha;
sim.sim.alpha = value;
DebugResponsePayload {
command: format!("SetEconParam(TatonnementStep, {})", value),
text: format!("α (tâtonnement step): {} → {}", old, value),
success: true,
}
}
EconParamKind::DampingFactor => {
let old = sim.sim.beta;
sim.sim.beta = value;
DebugResponsePayload {
command: format!("SetEconParam(DampingFactor, {})", value),
text: format!("β (damping factor): {} → {}", old, value),
success: true,
}
}
EconParamKind::CorridorFriction { ref corridor_id } => {
DebugResponsePayload {
command: format!("SetEconParam(CorridorFriction({}))", corridor_id),
text: "Per-corridor friction override not yet implemented (requires corridor friction model in trade.rs).".to_string(),
success: false,
}
}
}
} else {
DebugResponsePayload {
command: "SetEconParam".to_string(),
text: "Economy simulation not loaded.".to_string(),
success: false,
}
}
}
DebugCommandKind::GetEconState { ref system_id } => {
if let Some(ref state) = econ_state {
let signals: Vec<_> = state
.signals
.iter()
.filter(|((sys, _), _)| sys == system_id)
.collect();
if signals.is_empty() {
DebugResponsePayload {
command: format!("GetEconState({})", system_id),
text: format!("System '{}' not found in economy state.", system_id),
success: false,
}
} else {
let mut lines = vec![
format!("=== Economy state for '{}' (econ_tick={}) ===", system_id, state.econ_tick),
format!(" FX rate (Tractus/Mark): {:.4}", state.tractus_mark_rate),
];
for ((_, commodity_id), sig) in &signals {
lines.push(format!(
" {} | price={:.2} trend={:+.2} flow={:.1} corps={} stockpile_wks={:.1} prod_vs_base={:.3} coverage={:.2}",
commodity_id,
sig.price_current,
sig.price_trend,
sig.trade_flow_volume,
sig.corporate_presence,
sig.stockpile_weeks,
sig.production_vs_baseline,
sig.official_coverage_ratio,
));
}
DebugResponsePayload {
command: format!("GetEconState({})", system_id),
text: lines.join("\n"),
success: true,
}
}
} else {
DebugResponsePayload {
command: format!("GetEconState({})", system_id),
text: "Economy simulation not loaded.".to_string(),
success: false,
}
}
}
}
};
+2
View File
@@ -320,6 +320,7 @@ mod tests {
debug_response: None,
current_ticker: None,
settings_response: None,
economy_snapshot: None,
}
}
@@ -461,6 +462,7 @@ mod tests {
debug_response: None,
current_ticker: None,
settings_response: None,
economy_snapshot: None,
};
let text = format_snapshot_text(&snap);
assert!(text.contains("Tick 0"));
+98 -1
View File
@@ -17,7 +17,7 @@ pub use crate::simulation::time::{DayPhase, TickRate};
/// negotiation is unnecessary. Client should reject snapshots with version !=
/// PROTOCOL_VERSION. New fields use #[serde(default)] only during the migration
/// period, then the default is removed once both sides are updated.
pub const PROTOCOL_VERSION: u8 = 20;
pub const PROTOCOL_VERSION: u8 = 21;
/// Handshake message sent as the very first framed message after connection (#555).
/// Client reads this before entering the normal tick loop and validates
@@ -81,6 +81,8 @@ pub struct StartupMessage {
/// v18 adds: debug_response (#580, debug console server — command/response wire).
/// v19 adds: character_archetype on StartupMessage (#587), current_ticker (#591).
/// v20 adds: settings_response (#627, SQLite settings IPC).
/// v21 adds: economy_snapshot (#822, D-181 7-signal snapshot per queried system),
/// EconStateQuery PlayerAction variant (#822).
/// Future fields: ambient sound events, HUD state (D-020 expansion).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObserverSnapshot {
@@ -216,6 +218,12 @@ pub struct ObserverSnapshot {
/// Client reads to confirm setting changes or to populate the settings UI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub settings_response: Option<crate::settings::types::SettingsResponseWire>,
/// Economy snapshot (#822, D-181 7-signal snapshot).
/// Present for exactly one tick after an `EconStateQuery` is processed.
/// Contains all 7 D-181 signals for each commodity in the queried system.
/// None during normal gameplay; client queries explicitly via `EconStateQuery`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub economy_snapshot: Option<EconomySnapshot>,
}
/// A single news ticker headline crossing the wire boundary (#591).
@@ -550,6 +558,12 @@ pub enum PlayerAction {
DeleteSetting {
key: String,
},
/// Query economy state for a named system (#822, D-181).
/// Server responds with `ObserverSnapshot.economy_snapshot` for one tick.
/// Absent when economy is not loaded or `system_id` is unknown.
EconStateQuery {
system_id: String,
},
}
impl PlayerAction {
@@ -595,6 +609,21 @@ pub enum DebugCommandKind {
ListPopulation,
/// Return `ContaminationActive` status and current tick.
GetContaminationStatus,
/// Inject a D-180 economic event into the running simulation (#823).
/// The event fires at the next economy tick and lasts for `duration_ticks`.
/// `target` is a system_id (node-level events only in v0.1).
InjectEconEvent {
target: String,
effect: EconDebugEffect,
magnitude: f64,
duration_ticks: u32,
},
/// Mutate a simulation parameter at runtime (#823, D-178).
/// Changes take effect on the next `Simulation::step()` call.
SetEconParam { param: EconParamKind, value: f64 },
/// Return all 7 D-181 signals for the named system (#823).
/// Equivalent to `EconStateQuery` but via the debug console.
GetEconState { system_id: String },
}
/// Debug response payload included in `ObserverSnapshot` (#580).
@@ -612,6 +641,72 @@ pub struct DebugResponsePayload {
pub success: bool,
}
/// Wire type for a single commodity's 7 D-181 signals at a node (#822).
///
/// Compact snapshot used in `EconomySnapshot.nodes`. Mirrors `EconNodeSignals`
/// in `simulation::economy` but is Serializable for wire transmission.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EconNodeSnapshot {
pub commodity_id: String,
/// Signal 1: current market price in Tractus (Public).
pub price_current: f64,
/// Signal 2: price delta over last TREND_WINDOW economy ticks (Public).
pub price_trend: f64,
/// Signal 3: trade flow volume proxy (Observable).
pub trade_flow_volume: f64,
/// Signal 4: number of corporations at this node (Observable).
pub corporate_presence: u32,
/// Signal 5: stockpile in weeks at current demand rate (Semi-private).
pub stockpile_weeks: f64,
/// Signal 6: supply vs. baseline supply from first tick (Private).
pub production_vs_baseline: f64,
/// Signal 7: ratio of formal to total activity (Meta-signal).
pub official_coverage_ratio: f64,
}
/// Wire type for economy state snapshot (#822, D-181).
///
/// Returned in `ObserverSnapshot.economy_snapshot` for one tick after an
/// `EconStateQuery` is processed. Contains signals for all commodities in the
/// queried system. None when economy is not loaded or system_id is unknown.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EconomySnapshot {
/// The system this snapshot covers.
pub system_id: String,
/// Economy tick at which this snapshot was produced.
pub econ_tick: u64,
/// Current Tractus/Mark exchange rate (1.0 = parity).
pub tractus_mark_rate: f64,
/// Signals for each commodity active in this system.
pub nodes: Vec<EconNodeSnapshot>,
}
/// Effect type for `InjectEconEvent` debug command (#823, D-180).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EconDebugEffect {
/// Multiply production capacity of the target node by `magnitude`.
/// < 1.0 = capacity shock; > 1.0 = capacity boost.
CapacityMultiplier,
/// Multiply productivity of all operations at the target node by `magnitude`.
ProductivityMultiplier,
/// Add `magnitude` to demand for all commodities at the target node.
DemandShock,
/// Apply a one-time exchange rate shock of `magnitude` to the FX rate.
ExchangeShock,
}
/// Parameter selector for `SetEconParam` debug command (#823, D-178).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EconParamKind {
/// Tâtonnement step size (α, D-178 Layer 2). Default: 0.03.
TatonnementStep,
/// Trade flow damping factor (β, D-178). Default: 0.4.
DampingFactor,
/// Per-corridor friction override (not yet implemented in simulation).
#[allow(dead_code)] // Used by future corridor friction model (#TODO)
CorridorFriction { corridor_id: String },
}
/// Whether the debug console is enabled (#580).
///
/// Set at server startup. Cannot be toggled mid-session via IPC.
@@ -941,6 +1036,8 @@ pub struct SnapshotBuffer {
pub pending_debug_response: Option<DebugResponsePayload>,
/// Pending settings response, consumed once by `compute_observer_snapshot` (#627).
pub pending_settings_response: Option<crate::settings::types::SettingsResponseWire>,
/// Pending economy snapshot, consumed once by `compute_observer_snapshot` (#822).
pub pending_economy_response: Option<EconomySnapshot>,
}
#[cfg(test)]
+1
View File
@@ -328,6 +328,7 @@ fn send_panic_error(app: &App, panic_msg: &str) {
debug_response: None,
current_ticker: None,
settings_response: None,
economy_snapshot: None,
sim_errors: vec![SimError {
kind: SimErrorKind::Panic,
message: format!("Simulation panic: {}", panic_msg),
+4
View File
@@ -394,6 +394,9 @@ pub fn compute_observer_snapshot(
None
};
// Consume pending economy snapshot for this tick (#822).
let economy_snapshot = buffer.pending_economy_response.take();
// Consume pending save/load result for this tick (#553).
let save_result = buffer.pending_save_result.take();
@@ -489,6 +492,7 @@ pub fn compute_observer_snapshot(
debug_response,
current_ticker,
settings_response,
economy_snapshot,
});
}
+382
View File
@@ -0,0 +1,382 @@
//! Economy simulation integration — runs econ-sim inside the server tick loop.
//!
//! Bridges the standalone `econ_sim` library into the Bevy ECS tick loop.
//! The simulation advances one economy tick every `ECON_TICK_RATE` game ticks.
//!
//! ## Architecture
//!
//! - [`EconSimResource`] — holds the running `Simulation` + price history for trends.
//! Loaded once at startup from `server/data/systems.db`. Never reloaded mid-session.
//!
//! - [`EconStateResource`] — all 7 D-181 signals per active (system_id, commodity_id).
//! Updated every `ECON_TICK_RATE` game ticks by `tick_economy_simulation`.
//! Queryable by the IPC bridge (#822) and debug commands (#823).
//!
//! - `tick_economy_simulation` — bevy System registered in `SimulationPlugin`.
//! Advances one economy tick, then rebuilds `EconStateResource`.
//!
//! ## Rate (D-031)
//!
//! `ECON_TICK_RATE = 10` game ticks per economy tick.
//! At 10 game ticks/game-minute (D-031), this means the economy advances once
//! per game-minute — a reasonable granularity for macro-scale price dynamics.
//!
//! ## D-181 signals
//!
//! 1. `price_current` — current market price (Public)
//! 2. `price_trend` — Δprice over the last `TREND_WINDOW` economy ticks (Public)
//! 3. `trade_flow_volume` — supply volume proxy (Observable; Phase 3 will refine)
//! 4. `corporate_presence` — corp count at this node (Observable)
//! 5. `stockpile_weeks` — stockpile ÷ weekly demand rate (Semi-private)
//! 6. `production_vs_baseline` — supply ÷ initial baseline supply (Private)
//! 7. `official_coverage_ratio` — 1 shadow_intensity (Meta-signal)
use std::collections::BTreeMap;
use bevy_ecs::prelude::*;
use econ_sim::Simulation;
use crate::bridge::types::{EconNodeSnapshot, EconomySnapshot, SnapshotBuffer};
use crate::simulation::time::SimulationTime;
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Game ticks between each economy tick (D-031: 10 ticks/game-minute).
pub const ECON_TICK_RATE: u64 = 10;
/// Number of economy ticks to average for price trend signal 2 (D-181).
const TREND_WINDOW: usize = 5;
// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------
/// The running economics simulation (loaded once at startup).
///
/// Never reinitialize mid-session — the economy state is continuous.
#[derive(Resource)]
pub struct EconSimResource {
pub sim: Simulation,
/// Price history for signal 2 (price_trend) computation.
/// Ring-buffer keyed by (system_id, commodity_id) → last TREND_WINDOW prices.
price_history: BTreeMap<(String, String), Vec<f64>>,
/// Baseline supply from first economy tick for signal 6 (production_vs_baseline).
baseline_supply: BTreeMap<(String, String), f64>,
}
impl EconSimResource {
pub fn new(sim: Simulation) -> Self {
Self {
sim,
price_history: BTreeMap::new(),
baseline_supply: BTreeMap::new(),
}
}
}
/// The 7 D-181 signals for a single active (system_id, commodity_id) pair.
///
/// Updated every `ECON_TICK_RATE` game ticks. All fields present when the
/// node is active; queries for inactive nodes return nothing.
#[derive(Debug, Clone)]
pub struct EconNodeSignals {
pub system_id: String,
pub commodity_id: String,
/// Signal 1: current market price in Tractus (Public).
pub price_current: f64,
/// Signal 2: price delta over last `TREND_WINDOW` economy ticks (Public).
/// Positive = price rising; negative = falling. Absolute delta, not percentage.
pub price_trend: f64,
/// Signal 3: trade flow volume proxy — supply volume this tick (Observable).
/// Phase 2 proxy: actual inter-node flow tracking is Phase 3.
pub trade_flow_volume: f64,
/// Signal 4: number of corporations operating at this node (Observable).
pub corporate_presence: u32,
/// Signal 5: estimated stockpile in weeks at current demand rate (Semi-private).
pub stockpile_weeks: f64,
/// Signal 6: supply vs. baseline supply from first tick (Private).
/// 1.0 = at baseline; < 1.0 = below baseline; > 1.0 = above.
pub production_vs_baseline: f64,
/// Signal 7: ratio of formal to total (formal + shadow) activity (Meta-signal).
/// Derived from `shadow_intensity`: 1.0 = fully formal, 0.0 = fully shadow.
pub official_coverage_ratio: f64,
}
/// Current economy state — all 7 D-181 signals for all active nodes.
///
/// Updated every `ECON_TICK_RATE` game ticks. Queryable by the IPC bridge
/// (#822) and debug command handler (#823). Absent when the economy DB is
/// not loaded (graceful degradation).
#[derive(Resource, Default)]
pub struct EconStateResource {
/// Economy tick at which this snapshot was produced.
pub econ_tick: u64,
/// Current Tractus/Mark exchange rate (1.0 = parity).
pub tractus_mark_rate: f64,
/// Signal map: (system_id, commodity_id) → 7-signal snapshot.
pub signals: BTreeMap<(String, String), EconNodeSignals>,
}
// ---------------------------------------------------------------------------
// System
// ---------------------------------------------------------------------------
/// System: advance the economy simulation one tick every `ECON_TICK_RATE` game ticks.
///
/// Runs after `time::advance_tick` (needs current game tick) and before
/// `compute_observer_snapshot` (so signals are fresh for the snapshot).
///
/// No-op when the game tick is not divisible by `ECON_TICK_RATE`.
/// Both `EconSimResource` and `EconStateResource` must be present (inserted
/// at startup only when the economy DB loaded successfully).
pub fn tick_economy_simulation(
time: Res<SimulationTime>,
econ_sim_opt: Option<ResMut<EconSimResource>>,
econ_state_opt: Option<ResMut<EconStateResource>>,
) {
let (mut econ_sim, mut econ_state) = match (econ_sim_opt, econ_state_opt) {
(Some(s), Some(st)) => (s, st),
_ => return, // economy not loaded — no-op
};
if time.tick % ECON_TICK_RATE != 0 {
return;
}
// Step the simulation one economy tick
econ_sim.sim.step();
let econ_tick = econ_sim.sim.tick();
let fx_rate = econ_sim.sim.tractus_mark_rate();
// Rebuild signal map from updated node states
rebuild_signals(&mut econ_sim, &mut econ_state, econ_tick, fx_rate);
}
// ---------------------------------------------------------------------------
// Signal computation
// ---------------------------------------------------------------------------
fn rebuild_signals(
econ_sim: &mut EconSimResource,
econ_state: &mut EconStateResource,
econ_tick: u64,
fx_rate: f64,
) {
econ_state.econ_tick = econ_tick;
econ_state.tractus_mark_rate = fx_rate;
econ_state.signals.clear();
// Collect shadow intensities and corp counts once (avoid repeated borrows)
let shadow_intensities: BTreeMap<String, f64> = econ_sim
.sim
.shadow()
.intensity
.iter()
.map(|(k, v)| (k.clone(), *v))
.collect();
let corp_counts: BTreeMap<String, u32> = econ_sim
.sim
.economy()
.presences_by_system
.iter()
.map(|(sys, corps)| (sys.clone(), corps.len() as u32))
.collect();
// Snapshot current node states into the price_history and baseline_supply maps,
// then build signals. We need to separate the borrow from the iteration.
let node_snapshots: Vec<(String, Vec<(String, f64, f64)>)> = econ_sim
.sim
.nodes
.iter()
.map(|(system_id, node)| {
let commodities: Vec<(String, f64, f64)> = node
.commodities
.iter()
.map(|(commodity_id, state)| {
(commodity_id.clone(), state.price, state.supply)
})
.collect();
(system_id.clone(), commodities)
})
.collect();
for (system_id, commodities) in &node_snapshots {
let shadow_intensity = shadow_intensities.get(system_id).copied().unwrap_or(0.0);
let corp_count = corp_counts.get(system_id).copied().unwrap_or(0);
for (commodity_id, price, supply) in commodities {
let key = (system_id.clone(), commodity_id.clone());
// Signal 6 baseline: record first-tick supply
econ_sim
.baseline_supply
.entry(key.clone())
.or_insert(*supply);
let baseline = *econ_sim.baseline_supply.get(&key).unwrap_or(supply);
// Signal 2: price trend via ring buffer
let history = econ_sim.price_history.entry(key.clone()).or_default();
history.push(*price);
if history.len() > TREND_WINDOW {
history.remove(0);
}
let price_trend = if history.len() >= 2 {
price - history[0]
} else {
0.0
};
// Signal 5: stockpile in weeks (7 economy ticks per week approximation)
let stockpile = econ_sim
.sim
.nodes
.get(system_id)
.and_then(|n| n.commodities.get(commodity_id))
.map(|s| s.stockpile)
.unwrap_or(0.0);
let demand = econ_sim
.sim
.nodes
.get(system_id)
.and_then(|n| n.commodities.get(commodity_id))
.map(|s| s.demand)
.unwrap_or(0.0);
let weekly_demand = demand * 7.0; // 7 econ ticks ≈ 1 week
let stockpile_weeks = if weekly_demand > 1e-9 {
stockpile / weekly_demand
} else {
0.0
};
// Signal 6: production vs baseline
let production_vs_baseline = if baseline > 1e-9 {
supply / baseline
} else {
1.0
};
// Signal 7: official coverage ratio
let official_coverage_ratio = 1.0 - shadow_intensity;
econ_state.signals.insert(
key,
EconNodeSignals {
system_id: system_id.clone(),
commodity_id: commodity_id.clone(),
price_current: *price,
price_trend,
trade_flow_volume: *supply, // Phase 2 proxy
corporate_presence: corp_count,
stockpile_weeks,
production_vs_baseline,
official_coverage_ratio,
},
);
}
}
}
// ---------------------------------------------------------------------------
// Startup helper
// ---------------------------------------------------------------------------
/// Attempt to load the economy simulation.
///
/// Returns `Some((EconSimResource, EconStateResource))` on success, `None` on
/// failure (with the error logged at warn level). The server inserts these as
/// resources when present; the economy features degrade gracefully when absent.
// ---------------------------------------------------------------------------
// IPC query buffer (#822)
// ---------------------------------------------------------------------------
/// Pending system_id from an `EconStateQuery` PlayerAction.
///
/// Populated by `process_player_input`; consumed by `serve_econ_state_query`.
/// `None` on ticks when no query was received.
#[derive(Resource, Default)]
pub struct EconQueryBuffer {
pub pending: Option<String>,
}
/// System: serve a pending `EconStateQuery` by building an `EconomySnapshot`
/// and storing it in `SnapshotBuffer.pending_economy_response`.
///
/// Runs after `tick_economy_simulation` (signals must be fresh) and before
/// `compute_observer_snapshot` (which consumes the response).
/// No-op when `EconStateResource` is absent or no query is pending.
pub fn serve_econ_state_query(
mut query_buf: ResMut<EconQueryBuffer>,
econ_state: Option<Res<EconStateResource>>,
mut snapshot_buf: ResMut<SnapshotBuffer>,
) {
let system_id = match query_buf.pending.take() {
Some(s) => s,
None => return,
};
let econ_state = match econ_state {
Some(s) => s,
None => {
// Economy not loaded — no response (client receives None in snapshot)
tracing::debug!(system_id = %system_id, "EconStateQuery: economy not loaded");
return;
}
};
// Collect signals for all commodities in the requested system
let nodes: Vec<EconNodeSnapshot> = econ_state
.signals
.iter()
.filter(|((sys, _), _)| sys == &system_id)
.map(|((_, commodity_id), sig)| EconNodeSnapshot {
commodity_id: commodity_id.clone(),
price_current: sig.price_current,
price_trend: sig.price_trend,
trade_flow_volume: sig.trade_flow_volume,
corporate_presence: sig.corporate_presence,
stockpile_weeks: sig.stockpile_weeks,
production_vs_baseline: sig.production_vs_baseline,
official_coverage_ratio: sig.official_coverage_ratio,
})
.collect();
if nodes.is_empty() {
tracing::debug!(system_id = %system_id, "EconStateQuery: system not found in economy state");
return;
}
snapshot_buf.pending_economy_response = Some(EconomySnapshot {
system_id,
econ_tick: econ_state.econ_tick,
tractus_mark_rate: econ_state.tractus_mark_rate,
nodes,
});
}
// ---------------------------------------------------------------------------
// Startup helper
// ---------------------------------------------------------------------------
pub fn try_load_economy(run_seed: u64) -> Option<(EconSimResource, EconStateResource)> {
match Simulation::load_auto(run_seed) {
Ok(sim) => {
tracing::info!(
commodities = sim.economy().commodities.len(),
active_nodes = sim.nodes.len(),
"Economy simulation loaded"
);
Some((EconSimResource::new(sim), EconStateResource::default()))
}
Err(e) => {
tracing::warn!(
error = %e,
"Economy simulation not loaded — economics features disabled for this session"
);
None
}
}
}
+10
View File
@@ -4,6 +4,7 @@
use crate::bridge::debug::DebugCommandBuffer;
use crate::bridge::types::{FacingDirection, ObjectType, PlayerAction, PlayerInput};
use crate::simulation::economy::EconQueryBuffer;
use crate::knowledge::{EntityRegistry, StableId};
use crate::perception::vision_cone::{facing_from_delta, Facing};
use crate::settings::{SettingsCommand, SettingsCommandBuffer};
@@ -102,6 +103,7 @@ pub fn process_player_input(
mut save_load: Option<ResMut<SaveLoadPending>>,
mut debug_cmd_buffer: Option<ResMut<DebugCommandBuffer>>,
mut settings_cmd_buffer: Option<ResMut<SettingsCommandBuffer>>,
mut econ_query_buf: Option<ResMut<EconQueryBuffer>>,
door_states: Query<&DoorState>,
object_types: Query<&ObjectType>,
) {
@@ -127,6 +129,7 @@ pub fn process_player_input(
| PlayerAction::ChangeSetting { .. }
| PlayerAction::RequestAllSettings
| PlayerAction::DeleteSetting { .. }
| PlayerAction::EconStateQuery { .. }
)
{
continue;
@@ -410,6 +413,13 @@ pub fn process_player_input(
);
}
}
PlayerAction::EconStateQuery { system_id } => {
if let Some(ref mut buf) = econ_query_buf {
buf.pending = Some(system_id);
} else {
tracing::debug!("EconStateQuery received but EconQueryBuffer not registered — economy not loaded");
}
}
}
}
+24
View File
@@ -8,6 +8,7 @@ pub mod chunk_streaming;
pub mod contraband;
pub mod conversation;
pub mod dialogue;
pub mod economy;
pub mod examine;
pub mod follow;
pub mod generator;
@@ -166,6 +167,29 @@ impl Plugin for SimulationPlugin {
// Initialize TickerPool with empty default; populated by ContentPlugin at Startup.
app.init_resource::<ticker::TickerPool>();
// Economy simulation (#821, D-031) — loaded once at startup, no-op when DB absent.
// Uses seed 0 for now; will be threaded through StartupMessage world seed (#TODO).
if let Some((econ_sim, econ_state)) = economy::try_load_economy(0) {
app.insert_resource(econ_sim)
.insert_resource(econ_state);
}
// EconQueryBuffer: always registered so EconStateQuery PlayerActions are accepted
// even when the economy DB is absent (queries just produce no response).
app.init_resource::<economy::EconQueryBuffer>();
// tick_economy_simulation + serve_econ_state_query use Option<ResMut<...>> — safe to
// register unconditionally. They no-op when EconSimResource / EconStateResource absent.
app.add_systems(
Update,
(
economy::tick_economy_simulation
.after(time::advance_tick)
.before(crate::perception::observer::compute_observer_snapshot),
economy::serve_econ_state_query
.after(economy::tick_economy_simulation)
.before(crate::perception::observer::compute_observer_snapshot),
),
);
tracing::debug!("SimulationPlugin initialized");
}
}