Allinea i giorni degli eventi a quelli annunciati, toglie le sovrapposizioni
di zona e impedisce che l'IA trasformi un effetto temporaneo in un
investimento permanente.
- Un evento è in vigore nei giorni [inizio, fine) per tutti: le
interrogazioni di WorldEventState contano solo gli eventi in vigore nel
giorno dell'orologio, l'usura conta il maltempo del giorno del traffico.
Il maltempo non rallenta più i treni il giorno dell'estrazione e agisce
per intero l'ultimo giorno; l'evento esce dall'elenco il mattino del
primo giorno libero, con la notizia di fine. {until} è l'ultimo giorno.
- Niente zone sovrapposte tra due maltempi o tra due eventi sulla domanda
dello stesso bene (né due boom né boom e crollo insieme): nessuna città
e nessun arco ricevono due volte lo stesso effetto.
- IA: stime dei candidati sulla domanda senza eventi, sui posti scoperti
senza le assenze di epidemie e scioperi (PresentWithoutEvents) e
sull'efficienza senza il moltiplicatore di capacità (ADR 0017 §9).
- Client: conto alla rovescia dalla durata a 1 e «da domani» per gli
eventi estratti oggi; avviso anche nelle città della zona e nel Registro
officina del deposito in sciopero; dal resoconto il notiziario prende
solo le notizie di fine, le altre arrivano già come Notification.
ADR 0017, STATE, ARCHITECTURE e PROTOCOL aggiornati; 2 test nuovi e
3 adattati alla nuova finestra.
Refs #33.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
9.4 KiB
C#
246 lines
9.4 KiB
C#
using RailEnterprise.Core.Commands;
|
|
using RailEnterprise.Core.Common;
|
|
using RailEnterprise.Core.Data;
|
|
using RailEnterprise.Core.Economy;
|
|
using RailEnterprise.Core.Map;
|
|
using RailEnterprise.Core.Rail;
|
|
using RailEnterprise.Core.Time;
|
|
|
|
namespace RailEnterprise.Core.Simulation;
|
|
|
|
/// <summary>
|
|
/// Il mondo di gioco: tutto lo stato della simulazione e il ciclo dei sistemi.
|
|
/// Single-thread: chi lo usa da più thread (il server) deve serializzare gli accessi.
|
|
/// </summary>
|
|
public sealed class World
|
|
{
|
|
private readonly Dictionary<string, Rng> _streams = new(StringComparer.Ordinal);
|
|
private readonly Queue<GameCommand> _commands = new();
|
|
private readonly List<CommandResult> _results = [];
|
|
|
|
public World(GameData data, WorldSettings settings, Terrain terrain, MapSide seaSide)
|
|
{
|
|
Data = data;
|
|
Settings = settings;
|
|
Calendar = new Calendar(data.Balance.Time, settings.StartYear);
|
|
Clock = new GameClock(Calendar);
|
|
WorldEvents = new WorldEventState(Clock);
|
|
Rng = new Rng(settings.Seed);
|
|
Terrain = terrain;
|
|
Sampler = new TerrainSampler(terrain);
|
|
SeaSide = seaSide;
|
|
Market = new Market(data);
|
|
Goods = new GoodsCounters(data.GoodCount);
|
|
Money = new MoneyLedger(id => Companies[id.Value], id => Industries[id.Value]);
|
|
Context = new WorldContext(this);
|
|
Pipeline = SystemPipeline.CreateDefault();
|
|
TerrainHash = terrain.ComputeHash();
|
|
}
|
|
|
|
public GameData Data { get; }
|
|
public WorldSettings Settings { get; }
|
|
public DifficultyDef Difficulty => Settings.Difficulty;
|
|
public Calendar Calendar { get; }
|
|
public GameClock Clock { get; }
|
|
|
|
/// <summary>Generatore radice: non estrae mai, serve solo a derivare i flussi dei sottosistemi.</summary>
|
|
public Rng Rng { get; }
|
|
|
|
public Terrain Terrain { get; }
|
|
public TerrainSampler Sampler { get; }
|
|
public MapSide SeaSide { get; }
|
|
public ulong TerrainHash { get; internal set; }
|
|
|
|
public List<ResourceSite> Sites { get; } = [];
|
|
public List<Town> Towns { get; } = [];
|
|
public List<Industry> Industries { get; } = [];
|
|
public List<Hub> Hubs { get; } = [];
|
|
public List<Company> Companies { get; } = [];
|
|
public List<CommuteContract> Commutes { get; } = [];
|
|
|
|
/// <summary>Convenzioni di pendolarismo (proposte, attive e concluse di recente).</summary>
|
|
public List<CommuteAgreement> Agreements { get; } = [];
|
|
|
|
/// <summary>Offerte pubbliche di acquisto (in corso e concluse di recente).</summary>
|
|
public List<TakeoverBid> Bids { get; } = [];
|
|
|
|
/// <summary>Aste degli attivi delle compagnie fallite.</summary>
|
|
public List<Auction> Auctions { get; } = [];
|
|
|
|
/// <summary>Fine della partita del giocatore (null finché gioca): poi si osserva il mondo.</summary>
|
|
public GameOverState? GameOver { get; set; }
|
|
|
|
/// <summary>Stato degli agenti delle compagnie IA, in ordine di compagnia.</summary>
|
|
public List<Ai.AiState> AiStates { get; } = [];
|
|
|
|
/// <summary>Agenti IA sospesi (le compagnie IA esistono ma non agiscono): test e scenari didattici.</summary>
|
|
public bool AiPaused { get; set; }
|
|
|
|
/// <summary>Ultimo anno in cui è entrato un nuovo concorrente (12.1).</summary>
|
|
public int LastCompetitorYear { get; set; } = int.MinValue;
|
|
|
|
/// <summary>Rete ferroviaria di tutte le compagnie.</summary>
|
|
public RailNetwork Network { get; } = new();
|
|
public List<Vehicle> Vehicles { get; } = [];
|
|
public List<Train> Trains { get; } = [];
|
|
public List<Line> Lines { get; } = [];
|
|
|
|
/// <summary>Ricerca dei percorsi (buffer riutilizzati, non salvati).</summary>
|
|
public Pathfinder Pathfinder { get; } = new();
|
|
|
|
/// <summary>Grafo delle linee per compagnia (cache, non salvata).</summary>
|
|
public LineGraphCache LineGraphs { get; } = new();
|
|
|
|
public Market Market { get; }
|
|
public MoneyLedger Money { get; }
|
|
public GoodsCounters Goods { get; }
|
|
public EventLog Events { get; } = new();
|
|
|
|
/// <summary>Eventi del mondo in corso con i loro effetti temporanei (ADR 0017).</summary>
|
|
public WorldEventState WorldEvents { get; }
|
|
|
|
/// <summary>Avvisi di manutenzione del giorno (non salvati): il server li inoltra come MaintenanceAlert.</summary>
|
|
public List<FleetAlert> Alerts { get; } = [];
|
|
|
|
public WorldContext Context { get; }
|
|
public SystemPipeline Pipeline { get; }
|
|
|
|
/// <summary>Contatori per l'assegnazione di nuovi id (mai riutilizzati).</summary>
|
|
public IdCounters NextIds { get; } = new();
|
|
|
|
/// <summary>Hash di stato dell'ultimo giorno calcolato dal sistema Hash.</summary>
|
|
public ulong LastStateHash { get; internal set; }
|
|
public long LastHashDay { get; internal set; } = -1;
|
|
|
|
/// <summary>Nuove industrie nate nell'anno corrente (limite annuo).</summary>
|
|
public int SpawnedThisYear { get; internal set; }
|
|
|
|
/// <summary>Registro dei comandi applicati (tick, comando), se attivo: serve al replay.</summary>
|
|
public List<(long Tick, GameCommand Command)>? CommandLog { get; set; }
|
|
|
|
public Company Player => Companies.First(c => c.IsPlayer);
|
|
|
|
/// <summary>Flusso pseudo-casuale nominato di un sottosistema (derivato dalla radice, persistito nei salvataggi).</summary>
|
|
public Rng Stream(string name)
|
|
{
|
|
if (!_streams.TryGetValue(name, out var rng))
|
|
{
|
|
rng = Rng.Fork(name);
|
|
_streams[name] = rng;
|
|
}
|
|
return rng;
|
|
}
|
|
|
|
/// <summary>Flussi creati finora, in ordine di nome (per salvataggio e hash).</summary>
|
|
public IEnumerable<KeyValuePair<string, Rng>> Streams => _streams.OrderBy(kv => kv.Key, StringComparer.Ordinal);
|
|
|
|
internal void RestoreStream(string name, Rng rng) => _streams[name] = rng;
|
|
|
|
/// <summary>Accoda un comando: verrà eseguito dal sistema Commands del prossimo tick.</summary>
|
|
public void Enqueue(GameCommand command) => _commands.Enqueue(command);
|
|
|
|
internal bool TryDequeueCommand(out GameCommand command) => _commands.TryDequeue(out command!);
|
|
|
|
internal void AddResult(CommandResult result) => _results.Add(result);
|
|
|
|
/// <summary>Restituisce e azzera gli esiti dei comandi eseguiti.</summary>
|
|
public List<CommandResult> DrainResults()
|
|
{
|
|
var list = new List<CommandResult>(_results);
|
|
_results.Clear();
|
|
return list;
|
|
}
|
|
|
|
/// <summary>Esegue un tick: tutti i sistemi in ordine, poi avanza l'orologio.</summary>
|
|
public void Tick()
|
|
{
|
|
Pipeline.Run(Context);
|
|
Clock.Advance();
|
|
}
|
|
|
|
/// <summary>Esegue n tick.</summary>
|
|
public void RunTicks(long n)
|
|
{
|
|
for (long i = 0; i < n; i++) Tick();
|
|
}
|
|
|
|
/// <summary>Esegue un numero intero di giorni di calendario.</summary>
|
|
public void RunDays(int days) => RunTicks((long)days * Calendar.TicksPerDay);
|
|
|
|
/// <summary>Esegue un numero intero di anni di calendario.</summary>
|
|
public void RunYears(int years) => RunDays(years * Calendar.DaysPerYear);
|
|
|
|
public Town Town(TownId id) => Towns[id.Value];
|
|
public Industry Industry(IndustryId id) => Industries[id.Value];
|
|
public Company Company(CompanyId id) => Companies[id.Value];
|
|
|
|
/// <summary>Distanza in km tra un punto e il bordo della città.</summary>
|
|
public double TownEdgeDistanceKm(Town town, Vec2 p) =>
|
|
Math.Max(0, (Vec2.Distance(town.Position, p) - town.RadiusCells * Terrain.CellSizeM) / 1000.0);
|
|
|
|
/// <summary>Giacenza totale di un bene in tutti i depositi tracciati (invariante delle merci).</summary>
|
|
public long TotalStock(int good)
|
|
{
|
|
long sum = 0;
|
|
foreach (var s in Network.Stations)
|
|
{
|
|
foreach (var p in s.Waiting)
|
|
{
|
|
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
|
}
|
|
sum += s.StockOf(good);
|
|
}
|
|
foreach (var tr in Trains)
|
|
{
|
|
foreach (var p in tr.Cargo)
|
|
{
|
|
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
|
}
|
|
}
|
|
foreach (var t in Towns) sum += t.Stock[good];
|
|
if (good == Data.SparePartsGood)
|
|
{
|
|
foreach (var d in Network.Depots) sum += d.SpareParts;
|
|
}
|
|
foreach (var ind in Industries)
|
|
{
|
|
if (good == Data.SparePartsGood) sum += ind.SpareParts;
|
|
if (good == Data.MachineryGood) sum += ind.Machinery;
|
|
int i = ind.InputIndexOf(good);
|
|
if (i >= 0) sum += ind.InputStock[i];
|
|
int o = ind.OutputIndexOf(good);
|
|
if (o >= 0) sum += ind.OutputStock[o];
|
|
}
|
|
return sum;
|
|
}
|
|
|
|
/// <summary>Somma di tutti i saldi (deve essere zero: invariante del denaro).</summary>
|
|
public long MoneyBalanceSum()
|
|
{
|
|
long sum = Money.External.Cents;
|
|
foreach (var c in Companies) sum += c.Cash.Cents;
|
|
foreach (var i in Industries) sum += i.Cash.Cents;
|
|
return sum;
|
|
}
|
|
}
|
|
|
|
/// <summary>Prossimi id liberi per tipo di entità.</summary>
|
|
public sealed class IdCounters
|
|
{
|
|
public int Contract { get; set; }
|
|
public int Loan { get; set; }
|
|
public int Industry { get; set; }
|
|
public int Station { get; set; }
|
|
public int Node { get; set; }
|
|
public int Edge { get; set; }
|
|
public int Signal { get; set; }
|
|
public int Train { get; set; }
|
|
public int Vehicle { get; set; }
|
|
public int Line { get; set; }
|
|
public int Packet { get; set; }
|
|
public int Depot { get; set; }
|
|
public int Work { get; set; }
|
|
public int Bid { get; set; }
|
|
public int Agreement { get; set; }
|
|
}
|