F6: eventi del mondo con effetti temporanei e notizie
Aggiunge gli eventi della F6: fatti del mondo che cambiano il gioco per un periodo limitato, leggibili nel notiziario e reversibili. - Catalogo data/events.json con schema e validazione: incidente e boom di un'industria, fiera ed epidemia, boom e crollo della domanda di un bene in una zona, maltempo su un'area, sciopero di città o deposito. - Effetti come moltiplicatori letti da un'unica sorgente (World.WorldEvents) dai sistemi esistenti: capacità delle industrie, consumi delle città, presenze dei pendolari, velocità dei treni e usura del binario. A evento finito il moltiplicatore torna 1. - EventSystem tra le IA e l'hash, con flusso Rng dedicato «events», bersaglio in ordine di id, frequenza per mappa scalata dalla difficoltà (eventFrequencyMultiplier), tetto di 6, niente doppioni, notizie di inizio e fine in italiano (EventKind.World). - Salvataggio corpo versione 5 con gli eventi nell'hash; le versioni 1-4 si caricano senza eventi e con la frequenza del preset. - Protocollo: eventi in corso nel DailyDigest e nel MarketReport; client con il riquadro «Eventi in corso», avvisi nelle schede e «evento in corso» nel Mercato globale. - Lo scenario Valdoria disattiva gli eventi: con gli eventi attivi la flotta F4 senza linea dei ricambi non scendeva più sotto 40, e l'accettazione deve misurare la manutenzione, non la fortuna (ADR 0017). Accettazione F4 invariata: 35 / 20 guasti senza linea, 75 / 2 con. Decisioni in docs/adr/0017-eventi-del-mondo.md; 17 test nuovi. Refs #33. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b258e0858a
commit
1f8da87e51
41 files changed
+1892
-41
No files matched your search
@@ -537,4 +537,14 @@ unità,,units
|
||||
di cui,,of which
|
||||
Vuoto,,Empty
|
||||
Scegli una stazione di arrivo diversa da quella di partenza,,Choose a destination station different from the departure one
|
||||
Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra.,,"You have goods in your warehouses: you can sell or ship them, but not buy more."
|
||||
"Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra.",,"You have goods in your warehouses: you can sell or ship them, but not buy more."
|
||||
Eventi in corso,,Current events
|
||||
altri,,more
|
||||
Capacità produttiva,,Production capacity
|
||||
Consumi della città,,Town consumption
|
||||
Domanda di,,Demand for
|
||||
Presenze al lavoro,,Attendance at work
|
||||
Velocità dei treni,,Train speed
|
||||
Usura dei binari,,Track wear
|
||||
entro,,within
|
||||
fino al,,until
|
||||
|
@@ -0,0 +1,41 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>
|
||||
/// Riquadro «Eventi in corso» del pannello destro, sopra la minimappa (ADR 0017): gli eventi del
|
||||
/// mondo attivi dal resoconto giornaliero, con luogo, effetti e scadenza. Nascosto se non ce ne sono.
|
||||
/// </summary>
|
||||
public partial class WorldEventsBox : PanelContainer
|
||||
{
|
||||
private readonly VBoxContainer _list = new();
|
||||
private readonly Label _title = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 10));
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 6);
|
||||
AddChild(col);
|
||||
col.AddChild(_title);
|
||||
_list.AddThemeConstantOverride("separation", 8);
|
||||
col.AddChild(_list);
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Ridisegna l'elenco (a ogni resoconto giornaliero).</summary>
|
||||
public void Update(ClientWorld w)
|
||||
{
|
||||
var events = w.LastDigest?.WorldEvents ?? [];
|
||||
Visible = events.Count > 0;
|
||||
foreach (var c in _list.GetChildren()) c.QueueFree();
|
||||
_title.Text = $"{T("Eventi in corso")} ({events.Count})";
|
||||
// al massimo quattro righe: il riquadro non deve schiacciare la minimappa
|
||||
foreach (var e in events.OrderBy(e => e.EndDay).Take(4)) _list.AddChild(WorldEventText.Row(w, e));
|
||||
if (events.Count > 4) _list.AddChild(UiTheme.Text($"+ {events.Count - 4} {T("altri")}", 12, Palette.TextSecondary));
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,7 @@ public partial class InfoPanel : VBoxContainer
|
||||
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
|
||||
}
|
||||
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
|
||||
WorldEventText.AddNotices(w, this, WorldEventText.Industry, ind.Id);
|
||||
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
@@ -180,6 +181,7 @@ public partial class InfoPanel : VBoxContainer
|
||||
AddChild(PanelKit.Pair(T("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
|
||||
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
|
||||
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
|
||||
WorldEventText.AddNotices(w, this, WorldEventText.Town, town.Id);
|
||||
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
|
||||
if (w.Employment is { } report)
|
||||
{
|
||||
|
||||
@@ -485,15 +485,22 @@ public partial class MarketPanel : VBoxContainer
|
||||
{
|
||||
var card = Card(Palette.Inner, Palette.Inner);
|
||||
var col = (VBoxContainer)card.GetChild(0);
|
||||
if (report.EventGood < 0)
|
||||
if (report.EventGood < 0 && report.GoodEvents.Count == 0)
|
||||
{
|
||||
col.AddChild(UiTheme.Text(T("Nessun evento in corso"), 13, Palette.TextSecondary, bold: true));
|
||||
col.AddChild(Wrapped(T("I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse."), 13, Palette.TextSecondary));
|
||||
return card;
|
||||
}
|
||||
col.AddChild(UiTheme.Text(T("Evento in corso"), 13, Palette.AmberLight, bold: true));
|
||||
// eventi del mondo sulla domanda di un bene in una zona (ADR 0017)
|
||||
foreach (var e in report.GoodEvents)
|
||||
{
|
||||
col.AddChild(Wrapped($"{GoodName(w, e.Good)}: {WorldEventText.Name(w, e).ToLowerInvariant()} {WorldEventText.Where(w, e)}", 17, Palette.Text, bold: true));
|
||||
col.AddChild(Wrapped($"{WorldEventText.Effects(w, e)}, {WorldEventText.Until(w, e)}.", 13, Palette.Text));
|
||||
}
|
||||
if (report.EventGood < 0) return card;
|
||||
bool up = report.EventShock > 0;
|
||||
string good = GoodName(w, report.EventGood);
|
||||
col.AddChild(UiTheme.Text(T("Evento in corso"), 13, Palette.AmberLight, bold: true));
|
||||
col.AddChild(Wrapped(up ? $"{good}: {T("prezzo mondiale in rialzo")}" : $"{good}: {T("prezzo mondiale in calo")}", 17, Palette.Text, bold: true));
|
||||
int months = Math.Max(1, (int)Math.Ceiling(report.EventMonths));
|
||||
col.AddChild(Wrapped($"{T("Il prezzo mondiale di")} {good.ToLowerInvariant()} {(up ? T("è più alto del") : T("è più basso del"))} {Fmt.Pct(Math.Abs(report.EventShock), 0)} " +
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Testi degli eventi del mondo in corso (ADR 0017) per l'elenco «Eventi in corso», le schede delle
|
||||
/// entità e il Mercato globale. Solo presentazione: i valori dei moltiplicatori arrivano dal server.
|
||||
/// </summary>
|
||||
public static class WorldEventText
|
||||
{
|
||||
// codici di EntityKind del protocollo
|
||||
private const byte TownEntity = 1, IndustryEntity = 2, DepotEntity = 7;
|
||||
|
||||
private static bool English => TranslationServer.GetLocale().StartsWith("en");
|
||||
|
||||
public static WorldEventDef? Def(ClientWorld w, WorldEventInfo e) => w.Data.Events.Events.FirstOrDefault(d => d.Id == e.Type);
|
||||
|
||||
/// <summary>Nome del tipo di evento nella lingua dell'interfaccia.</summary>
|
||||
public static string Name(ClientWorld w, WorldEventInfo e) =>
|
||||
Def(w, e) is { } d ? (English ? d.NameEn : d.NameIt) : e.Type;
|
||||
|
||||
/// <summary>Nome dell'entità coinvolta (città, industria, deposito).</summary>
|
||||
public static string Target(ClientWorld w, WorldEventInfo e) => e.Entity switch
|
||||
{
|
||||
TownEntity => w.Towns.TryGetValue(e.EntityIndex, out var t) ? t.Name : "?",
|
||||
IndustryEntity => w.Industries.TryGetValue(e.EntityIndex, out var i) ? i.Name : "?",
|
||||
DepotEntity => w.Depots.TryGetValue(e.EntityIndex, out var d) ? d.Name : "?",
|
||||
_ => "?",
|
||||
};
|
||||
|
||||
public static string GoodName(ClientWorld w, int good)
|
||||
{
|
||||
if (good < 0 || good >= w.Data.Goods.Count) return "";
|
||||
var def = w.Data.Goods[good];
|
||||
return English ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
/// <summary>Effetti con il loro valore («Produzione 25%», «Velocità dei treni 80%»).</summary>
|
||||
public static string Effects(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var def = Def(w, e);
|
||||
if (def is null) return "";
|
||||
var parts = new List<string>();
|
||||
for (int i = 0; i < def.Effects.Count && i < e.Effects.Length; i++)
|
||||
{
|
||||
string label = def.Effects[i].Kind switch
|
||||
{
|
||||
EventEffectKind.IndustryCapacity => T("Capacità produttiva"),
|
||||
EventEffectKind.TownDemand => T("Consumi della città"),
|
||||
EventEffectKind.GoodDemand => $"{T("Domanda di")} {GoodName(w, e.Good).ToLowerInvariant()}",
|
||||
EventEffectKind.Attendance => T("Presenze al lavoro"),
|
||||
EventEffectKind.TrainSpeed => T("Velocità dei treni"),
|
||||
EventEffectKind.TrackWear => T("Usura dei binari"),
|
||||
_ => "",
|
||||
};
|
||||
parts.Add($"{label} {Fmt.Pct(e.Effects[i], 0)}");
|
||||
}
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
|
||||
/// <summary>Zona dell'evento («entro 12 km da Valdoria») per area e domanda di un bene.</summary>
|
||||
public static string Where(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var def = Def(w, e);
|
||||
string target = Target(w, e);
|
||||
return def?.RadiusKm is { } km ? $"{T("entro")} {Fmt.Number(km, 0)} km {T("da")} {target}" : target;
|
||||
}
|
||||
|
||||
public static string Until(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
long left = Math.Max(0, e.EndDay - Fmt.Today(w));
|
||||
return $"{T("fino al")} {Fmt.Date(w, e.EndDay - 1)} ({left} {(left == 1 ? T("giorno") : T("giorni"))})";
|
||||
}
|
||||
|
||||
/// <summary>Colore della gravità: opportunità in verde, avvisi in ambra, critici in rosso.</summary>
|
||||
public static Color Color(WorldEventInfo e) => e.Severity switch
|
||||
{
|
||||
1 => Palette.Ok,
|
||||
2 => Palette.AmberLight,
|
||||
3 => Palette.Danger,
|
||||
_ => Palette.Text,
|
||||
};
|
||||
|
||||
/// <summary>Riga compatta: titolo, luogo, effetti e scadenza.</summary>
|
||||
public static Control Row(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var col = PanelKit.Column(2);
|
||||
col.AddChild(UiTheme.Text($"{Name(w, e)} · {Where(w, e)}", 14, Color(e), bold: true));
|
||||
var effects = UiTheme.Text(Effects(w, e), 12, Palette.Text);
|
||||
effects.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(effects);
|
||||
col.AddChild(UiTheme.Text(Until(w, e), 12, Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
/// <summary>Eventi che riguardano un'entità: bersaglio diretto oppure città centro della zona.</summary>
|
||||
public static IEnumerable<WorldEventInfo> For(ClientWorld w, byte entity, int index) =>
|
||||
(w.LastDigest?.WorldEvents ?? []).Where(e => e.Entity == entity && e.EntityIndex == index);
|
||||
|
||||
/// <summary>Avvisi «Evento in corso» per la scheda dell'entità.</summary>
|
||||
public static void AddNotices(ClientWorld w, Control into, byte entity, int index)
|
||||
{
|
||||
foreach (var e in For(w, entity, index))
|
||||
into.AddChild(UiTheme.Notice($"{T("Evento in corso")}: {Name(w, e)} · {Effects(w, e)} · {Until(w, e)}"));
|
||||
}
|
||||
|
||||
public const byte Town = TownEntity, Industry = IndustryEntity, Depot = DepotEntity;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public partial class GameScreen : Node
|
||||
private readonly Toolbar _toolbar = new();
|
||||
private readonly Ticker _ticker = new();
|
||||
private readonly Minimap _minimap = new();
|
||||
private readonly WorldEventsBox _worldEvents = new();
|
||||
private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
|
||||
private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
|
||||
private readonly VBoxContainer _toasts = new();
|
||||
@@ -206,6 +207,7 @@ public partial class GameScreen : Node
|
||||
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
|
||||
miniHeader.AddChild(miniTitle);
|
||||
miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary));
|
||||
sideCol.AddChild(_worldEvents);
|
||||
sideCol.AddChild(miniHeader);
|
||||
sideCol.AddChild(_minimap);
|
||||
root.AddChild(_ticker);
|
||||
@@ -231,6 +233,9 @@ public partial class GameScreen : Node
|
||||
|
||||
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
|
||||
|
||||
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
|
||||
private const byte WorldEventKind = 10;
|
||||
|
||||
/// <summary>Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata.</summary>
|
||||
private void BuildObserverBanner(Control mapArea)
|
||||
{
|
||||
@@ -304,7 +309,9 @@ public partial class GameScreen : Node
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||||
break;
|
||||
case DailyDigest d:
|
||||
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
|
||||
// gli eventi del mondo (inizio e fine) vanno sempre nel notiziario
|
||||
foreach (var e in d.Events.Where(e => e.Severity >= 2 || e.Kind == WorldEventKind)) _ticker.Add(e);
|
||||
_worldEvents.Update(_session.World);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,25 +6,25 @@
|
||||
"presets": [
|
||||
{ "id": "apprendista", "name_it": "Apprendista", "name_en": "Apprentice",
|
||||
"initialCapital": 50000000, "initialCredit": 50000000, "baseInterestRate": 0.03,
|
||||
"constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6,
|
||||
"constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6, "eventFrequencyMultiplier": 0.7,
|
||||
"aiCompetitors": 1, "aiCapitalMultiplier": 0.7, "aiCostDiscount": 0.0,
|
||||
"playerTakeover": "disabled", "takeoverRansomYears": 0, "bankruptcyDays": 180,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "no", "depletion": "slow" },
|
||||
{ "id": "imprenditore", "name_it": "Imprenditore", "name_en": "Entrepreneur",
|
||||
"initialCapital": 25000000, "initialCredit": 30000000, "baseInterestRate": 0.05,
|
||||
"constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0,
|
||||
"constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0, "eventFrequencyMultiplier": 1.0,
|
||||
"aiCompetitors": 2, "aiCapitalMultiplier": 1.0, "aiCostDiscount": 0.0,
|
||||
"playerTakeover": "ransom", "takeoverRansomYears": 3, "bankruptcyDays": 90,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "normal" },
|
||||
{ "id": "magnate", "name_it": "Magnate", "name_en": "Tycoon",
|
||||
"initialCapital": 15000000, "initialCredit": 15000000, "baseInterestRate": 0.07,
|
||||
"constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3,
|
||||
"constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3, "eventFrequencyMultiplier": 1.2,
|
||||
"aiCompetitors": 3, "aiCapitalMultiplier": 1.5, "aiCostDiscount": 0.10,
|
||||
"playerTakeover": "ransom", "takeoverRansomYears": 1, "bankruptcyDays": 60,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "fast" },
|
||||
{ "id": "ferro_e_sangue", "name_it": "Ferro e sangue", "name_en": "Iron and blood",
|
||||
"initialCapital": 10000000, "initialCredit": 10000000, "baseInterestRate": 0.09,
|
||||
"constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6,
|
||||
"constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6, "eventFrequencyMultiplier": 1.4,
|
||||
"aiCompetitors": 5, "aiCapitalMultiplier": 2.0, "aiCostDiscount": 0.20,
|
||||
"playerTakeover": "immediate", "takeoverRansomYears": 0, "bankruptcyDays": 30,
|
||||
"publicFromStart": true, "playerShareAtStart": 0.6, "ironman": "yes", "depletion": "fast" }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"$schema": "schema/events.schema.json",
|
||||
"version": 1,
|
||||
"maxActive": 6,
|
||||
"events": [
|
||||
{ "id": "industry_accident", "name_it": "Incidente in un impianto", "name_en": "Plant accident",
|
||||
"target": "industry", "chancePerYear": 1.2, "durationDays": [ 10, 45 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "industryCapacity", "min": 0.0, "max": 0.5 } ],
|
||||
"news_it": "Incidente a {target}: produzione al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: la produzione riprende dopo l'incidente" },
|
||||
{ "id": "industry_boom", "name_it": "Boom di produzione", "name_en": "Production boom",
|
||||
"target": "industry", "chancePerYear": 1.0, "durationDays": [ 30, 120 ], "minYear": 1850, "severity": "opportunity",
|
||||
"effects": [ { "kind": "industryCapacity", "min": 1.2, "max": 1.5 } ],
|
||||
"news_it": "Boom di produzione a {target}: capacità al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito il boom di produzione" },
|
||||
{ "id": "town_fair", "name_it": "Fiera cittadina", "name_en": "Town fair",
|
||||
"target": "town", "chancePerYear": 1.0, "durationDays": [ 7, 20 ], "minYear": 1850, "minPopulation": 1500, "severity": "opportunity",
|
||||
"effects": [ { "kind": "townDemand", "min": 1.3, "max": 1.8 } ],
|
||||
"news_it": "Fiera a {target}: consumi della città al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: chiusa la fiera, i consumi tornano normali" },
|
||||
{ "id": "epidemic", "name_it": "Epidemia", "name_en": "Epidemic",
|
||||
"target": "town", "chancePerYear": 0.4, "durationDays": [ 30, 90 ], "minYear": 1850, "minPopulation": 2000, "severity": "warning",
|
||||
"effects": [ { "kind": "townDemand", "min": 0.7, "max": 0.9 }, { "kind": "attendance", "min": 0.5, "max": 0.8 } ],
|
||||
"news_it": "Epidemia a {target}: consumi al {pct} e lavoratori assenti per {days} giorni",
|
||||
"newsEnd_it": "{target}: l'epidemia è finita" },
|
||||
{ "id": "good_demand_boom", "name_it": "Domanda in crescita", "name_en": "Demand boom",
|
||||
"target": "townGood", "radiusKm": 15, "chancePerYear": 0.8, "durationDays": [ 60, 180 ], "minYear": 1850, "severity": "opportunity",
|
||||
"effects": [ { "kind": "goodDemand", "min": 1.4, "max": 2.0 } ],
|
||||
"news_it": "Domanda di {good} in forte crescita intorno a {target}: consumi al {pct} per {days} giorni",
|
||||
"newsEnd_it": "Intorno a {target} la domanda di {good} torna normale" },
|
||||
{ "id": "good_demand_slump", "name_it": "Crollo della domanda", "name_en": "Demand slump",
|
||||
"target": "townGood", "radiusKm": 15, "chancePerYear": 0.8, "durationDays": [ 60, 180 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "goodDemand", "min": 0.3, "max": 0.7 } ],
|
||||
"news_it": "Crolla la domanda di {good} intorno a {target}: consumi al {pct} per {days} giorni",
|
||||
"newsEnd_it": "Intorno a {target} la domanda di {good} torna normale" },
|
||||
{ "id": "storm", "name_it": "Maltempo", "name_en": "Storm",
|
||||
"target": "area", "radiusKm": 12, "chancePerYear": 1.5, "durationDays": [ 3, 12 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "trainSpeed", "min": 0.5, "max": 0.8 }, { "kind": "trackWear", "min": 2.0, "max": 4.0 } ],
|
||||
"news_it": "Maltempo intorno a {target}: treni al {pct} della velocità e binari che si consumano di più per {days} giorni",
|
||||
"newsEnd_it": "Torna il sereno intorno a {target}" },
|
||||
{ "id": "strike_town", "name_it": "Sciopero dei lavoratori", "name_en": "Workers' strike",
|
||||
"target": "town", "chancePerYear": 0.5, "durationDays": [ 5, 20 ], "minYear": 1850, "minPopulation": 1000, "severity": "warning",
|
||||
"effects": [ { "kind": "attendance", "min": 0.2, "max": 0.6 } ],
|
||||
"news_it": "Sciopero dei lavoratori di {target}: presenze al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito lo sciopero, i lavoratori tornano al lavoro" },
|
||||
{ "id": "strike_depot", "name_it": "Sciopero in deposito", "name_en": "Depot strike",
|
||||
"target": "depot", "chancePerYear": 0.5, "durationDays": [ 5, 20 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "attendance", "min": 0.0, "max": 0.5 } ],
|
||||
"news_it": "Sciopero del personale a {target}: presenze al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito lo sciopero del personale" }
|
||||
]
|
||||
}
|
||||
@@ -87,6 +87,11 @@
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"eventFrequencyMultiplier": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"aiCompetitors": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
@@ -156,6 +161,7 @@
|
||||
"tariffMultiplier",
|
||||
"wearMultiplier",
|
||||
"marketVolatilityMultiplier",
|
||||
"eventFrequencyMultiplier",
|
||||
"aiCompetitors",
|
||||
"aiCapitalMultiplier",
|
||||
"aiCostDiscount",
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Eventi del mondo (events.json)",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxActive": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 64
|
||||
},
|
||||
"events": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"name_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"name_en": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"target": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"industry",
|
||||
"town",
|
||||
"townGood",
|
||||
"area",
|
||||
"depot"
|
||||
]
|
||||
},
|
||||
"radiusKm": {
|
||||
"type": "number",
|
||||
"minimum": 0.5,
|
||||
"maximum": 200
|
||||
},
|
||||
"chancePerYear": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 100
|
||||
},
|
||||
"durationDays": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 3600
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"minYear": {
|
||||
"type": "integer",
|
||||
"minimum": 1800,
|
||||
"maximum": 2200
|
||||
},
|
||||
"minPopulation": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"goods": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"industryKinds": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"primary",
|
||||
"processing",
|
||||
"manufacturing"
|
||||
]
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"severity": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"info",
|
||||
"opportunity",
|
||||
"warning",
|
||||
"critical"
|
||||
]
|
||||
},
|
||||
"effects": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"industryCapacity",
|
||||
"townDemand",
|
||||
"goodDemand",
|
||||
"attendance",
|
||||
"trainSpeed",
|
||||
"trackWear"
|
||||
]
|
||||
},
|
||||
"min": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"max": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"kind",
|
||||
"min",
|
||||
"max"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"news_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"newsEnd_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name_it",
|
||||
"name_en",
|
||||
"target",
|
||||
"chancePerYear",
|
||||
"durationDays",
|
||||
"minYear",
|
||||
"severity",
|
||||
"effects",
|
||||
"news_it",
|
||||
"newsEnd_it"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"version",
|
||||
"maxActive",
|
||||
"events"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -30,7 +30,7 @@ Regole:
|
||||
| `RailEnterprise.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. |
|
||||
| `RailEnterprise.Core.Rail` | `TrackGeometry` (raccordi), `TrackPlanner` (profilo a 25 m, opere, costi, tempi, vincoli per era), `RailNetwork` (nodi, archi campionati, stazioni, depositi, cantieri, indice spaziale), `Pathfinder` (A* sugli archi orientati), veicoli, treni, linee, pacchetti, `LineGraph` con maschere dei carichi (ADR 0007, 0008). |
|
||||
| `RailEnterprise.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. |
|
||||
| `RailEnterprise.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita. |
|
||||
| `RailEnterprise.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita, `WorldEvents` (eventi del mondo attivi e loro moltiplicatori, ADR 0017). |
|
||||
| `RailEnterprise.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. |
|
||||
|
||||
## 3. Il tick
|
||||
@@ -63,6 +63,7 @@ Sistemi implementati (F1–F5), nella loro posizione:
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `StockMarketSystem` | giorno/mese/anno | prezzi e sentiment, valore delle partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate, amministrazione controllata del giocatore, fallimenti e aste, storico annuale, nuovi concorrenti (ADR 0012) |
|
||||
| `AiSystem` | giorno/mese | agenti delle compagnie IA: progetti, stalli, offerte; una volta al mese (giorno diverso per IA) finanza, treni aggiuntivi, borsa, industrie, linee dei ricambi e nuovi progetti, tutto con i comandi (ADR 0013) |
|
||||
| `EventSystem` | giorno | eventi del mondo (F6, ADR 0017): chiude quelli scaduti, estrae i nuovi dal catalogo `events.json` con il flusso «events» e la frequenza della difficoltà, notizie d'inizio e di fine (posto di «Events») |
|
||||
| `HashSystem` | giorno | hash dello stato dinamico |
|
||||
|
||||
- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`.
|
||||
@@ -86,6 +87,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
- File in `data/*.json`, schema in `data/schema/*.schema.json` (sottoinsieme di JSON Schema validato da Core senza librerie esterne), deserializzazione rigorosa (proprietà sconosciute vietate, proprietà `required`), validazione semantica (id univoci, riferimenti risolti, limiti) in `DataValidator` (ADR 0002).
|
||||
- Caricamento con `System.Text.Json` e source generator (`DataJsonContext`), nessuna reflection.
|
||||
- `events.json` (F6, ADR 0017) è il catalogo degli eventi del mondo: bersaglio, zona, probabilità annua per mappa, durata, effetti come moltiplicatori con ampiezza min/max e testi delle notizie; `DataValidator` controlla anche che ogni effetto sia compatibile con il bersaglio.
|
||||
- `GameData.Hash` (XxHash64 dei file normalizzati) viaggia nel `Welcome`: client e server devono avere gli stessi dati.
|
||||
|
||||
## 6. Economia e contabilità
|
||||
@@ -94,6 +96,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
|
||||
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, magazzini delle compagnie nelle stazioni, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
|
||||
- Compravendita in proprio (F6, ADR 0016): `TradingCommandHandlers` esegue `BuyGoods`, `SellGoods` e `ShipGoods` con il prezzo locale marginale di `Systems/TradingMath` (unità per unità, controparti ordinate per prezzo). La merce comprata sta in `Station.Stock`; quella spedita viaggia in pacchetti con `Packet.Owned`, senza tariffa né consumatore, ed entra nel magazzino della stazione d'arrivo. Gli scambi con le industrie passano dal registro sulla voce «Commercio», quelli con gli hub contano come importazione ed esportazione; `StationSystem` addebita ogni mese la giacenza dei magazzini.
|
||||
- Eventi del mondo (F6, ADR 0017): `World.WorldEvents` (`WorldEventState`) è l'unica sorgente dei loro effetti. I sistemi chiedono un moltiplicatore per entità (1 senza eventi): `IndustryCapacity` in `IndustrySystem` e nella domanda di input di `DemandSystem`, `TownDemand` in `DemandSystem.TownDemand`, `Attendance` nelle presenze dei pendolari di `EmploymentSystem`, `EdgeSpeed` in `TrainSystem` ed `EdgeWear` nell'usura del binario di `ConstructionSystem`. Nessuno stato di base viene modificato: a evento finito il moltiplicatore torna 1.
|
||||
- Interpretazioni delle formule della guida: ADR 0004.
|
||||
|
||||
## 7. Salvataggi
|
||||
@@ -104,13 +107,14 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010).
|
||||
- Corpo versione 3 (F5): `CorporateSerializer` aggiunge manutenzione e proprietà delle industrie, libro dei soci, prezzi, controllo e storico delle compagnie, offerte, aste, fine partita e stato degli agenti IA (progetti, candidati scartati); i salvataggi precedenti si migrano (ADR 0012).
|
||||
- Corpo versione 4 (F6): `TradingSerializer` aggiunge i magazzini delle compagnie nelle stazioni (beni per id testuale) e gli id dei pacchetti di merce propria in stazione e a bordo; i salvataggi precedenti si caricano con i magazzini vuoti. `WorldSerializer.Write(w, s, versione)` scrive un corpo di una versione precedente per i test di migrazione (ADR 0016).
|
||||
- Corpo versione 5 (F6): `EventSerializer` aggiunge il prossimo id e gli eventi del mondo attivi (tipo e bene per id testuale, bersaglio, giorni, intensità; la zona si ricalcola dal catalogo); le impostazioni salvano `eventFrequencyMultiplier`. I salvataggi precedenti si caricano senza eventi e con la frequenza del preset (ADR 0017).
|
||||
|
||||
## 8. Server
|
||||
|
||||
- `ServerProgram`: Kestrel minimale, log JSON su stdout, configurazione da ambiente (`ServerConfig`: `RE_PORT`, `RE_TOKEN`, `RE_DATA_DIR`, `RE_TICK_MS`, `RE_AUTOSAVE_MIN`, `RE_SEED`, `RE_MAP_SIZE`, `RE_DIFFICULTY`, `RE_LOG_LEVEL`) e argomenti `--local` (127.0.0.1 su porta casuale, stampa `LISTENING porta`), `--healthcheck`, `--token`, `--port`, `--data`.
|
||||
- `GameHost`: possiede il mondo su un thread dedicato. Ogni giro drena la coda delle azioni (messaggi delle sessioni, richieste HTTP), esegue i tick dovuti con un accumulatore (velocità 0/1/2/4/8, budget `RE_TICK_MS`), adegua la velocità effettiva se i tick costano troppo (`slow`), pubblica e fa l'autosave a rotazione.
|
||||
- `Session` / `SessionEndpoint`: WebSocket su `/ws`, primo frame `Hello`, coda d'invio a due classi (affidabili e moti scartabili), ripresa con `sessionId` entro 120 s.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti, cartelle di manutenzione, registri officina, Registro degli impieghi); i delta per sessione si calcolano con gli hash dei record; i dettagli F4 si mandano su `RequestDetail`, gli avvisi di manutenzione (`World.Alerts`) come `MaintenanceAlert`.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti con gli eventi del mondo in corso, cartelle di manutenzione, registri officina, Registro degli impieghi); i delta per sessione si calcolano con gli hash dei record; i dettagli F4 si mandano su `RequestDetail`, gli avvisi di manutenzione (`World.Alerts`) come `MaintenanceAlert`.
|
||||
- `SaveStore`: salvataggi `.vfsave` in `$RE_DATA_DIR/saves`, ultimi cinque automatici; all'avvio si riprende il più recente.
|
||||
- HTTP: `/health`, `/metrics` (Prometheus), `GET/POST /api/saves`, `GET /api/saves/{id}`.
|
||||
- Docker: `docker/Dockerfile` (build in due stadi, utente non root, healthcheck), `docker-compose.yml`, `unraid-template.xml`; `scripts/publish-image.sh` per il registry Gitea.
|
||||
@@ -121,7 +125,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
|
||||
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze, scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti).
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze, scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+4
-3
@@ -146,7 +146,7 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
|
||||
| 112 | EntityDelta | `tick: i64`, `EntityLists` (nuovi o cambiati), `removed: [(type: u8, id: i32)]` |
|
||||
| 113 | TrackWorks | `edges: [EdgeInfo]`, `removed: [i32]` (lotti sotto 1 MB) |
|
||||
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
|
||||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
|
||||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32`; blocco 1 (F6): `worldEvents: [WorldEventInfo]` (eventi del mondo in corso su tutta la mappa, solo se ce ne sono; ADR 0017) |
|
||||
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
|
||||
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]`; blocco 1: `agreements: [AgreementInfo]` (mensile, su richiesta e dopo Accept/RejectAgreement) |
|
||||
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
|
||||
@@ -155,7 +155,7 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
|
||||
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
|
||||
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
|
||||
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
|
||||
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool`; blocco 1: `warehouses: [WarehouseInfo]` (magazzini della compagnia, solo se ne ha; ADR 0016) (su richiesta, F6; ADR 0015) |
|
||||
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool`; blocco 1: `warehouses: [WarehouseInfo]` (magazzini della compagnia, solo se ne ha; ADR 0016); blocco 2: `goodEvents: [WorldEventInfo]` (eventi del mondo sulla domanda di un bene, mostrati come «evento in corso»; ADR 0017). I due blocchi sono indipendenti: `flags` bit 0 e bit 1, in quest'ordine (su richiesta, F6; ADR 0015) |
|
||||
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
|
||||
| 131 | Notification | `EventInfo` |
|
||||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||||
@@ -180,7 +180,8 @@ Record (ognuno chiude con `flags`):
|
||||
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
|
||||
`nextDueDays: i32`, `maintenanceDepot: i32`
|
||||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6)
|
||||
- `WorldEventInfo { id: i32, type: string (id di events.json), entity: u8 (1 città, 2 industria, 7 deposito), entityIndex: i32, good: i32 (−1 se nessuno), startDay: i64, endDay: i64 (primo giorno senza l'evento), severity: u8, effects: [f32] }`: `effects` sono i moltiplicatori nell'ordine degli effetti del tipo nel catalogo (ADR 0017)
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
|
||||
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
|
||||
(0 nessuno, 1 nessuna stazione, 2 nessuna città entro il tempo massimo, 3 nessun lavoratore libero, 4 città senza servizi
|
||||
|
||||
+12
-2
@@ -110,11 +110,20 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- le IA non commerciano ancora (ADR 0016 §9);
|
||||
- correzioni della revisione: la merce propria segue i flag carico/scarico delle fermate (`LineGraph` con `stopFlags`), la scadenza riparte al trasbordo, ricalcolo giornaliero del tratto in attesa, scarico della merce a bordo dei treni che lasciano la linea o il cui tratto non è più sulla linea, niente demolizione con merce propria in partenza o in arrivo, merce propria nel valore contabile al prezzo globale, vendita e spedizione senza lo sblocco del livello (solo l'acquisto lo richiede), stazione di arrivo predefinita diversa dalla partenza nel riquadro;
|
||||
- test (`Economy/TradingTests.cs`, 17): acquisto dal produttore e dall'hub, vendita al consumatore e all'hub, rifiuti senza effetti, spedizione senza tariffa, un anno di commercio con gli invarianti, determinismo e salvataggio con merce in magazzino e in viaggio, migrazione dalla versione 3, magazzini nel quadro del mercato, round-trip del comando 40, flag delle fermate, treno tolto dalla linea, linea modificata con la merce a bordo, scadenza al trasbordo, demolizione bloccata, valore contabile. 143 test (126 senza i lenti).
|
||||
- Restano della F6: eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **Eventi del mondo (issue #33, ADR 0017)**:
|
||||
- catalogo `data/events.json` con schema e validazione (effetti compatibili con il bersaglio): incidente e boom di un'industria, fiera ed epidemia in una città, boom e crollo della domanda di un bene nella zona di una città, maltempo su un'area (treni più lenti, usura del binario più rapida), sciopero dei lavoratori di una città o del personale di un deposito; probabilità annua per mappa × `eventFrequencyMultiplier` della difficoltà (0,7 / 1,0 / 1,2 / 1,4; 0 li disattiva), al massimo 6 eventi insieme, nessun doppione dello stesso tipo sullo stesso bersaglio;
|
||||
- effetti come moltiplicatori letti da un'unica sorgente (`World.WorldEvents`): capacità delle industrie (produzione e domanda di input), consumi delle città, presenze dei pendolari, velocità dei treni e usura del binario; a evento finito tutto torna come prima;
|
||||
- `EventSystem` tra le IA e l'hash, flusso pseudo-casuale dedicato «events», bersaglio in ordine di id, notizie d'inizio e di fine in italiano (`EventKind.World` = 10); `EventSystem.Force` per test e scenari;
|
||||
- salvataggio: corpo versione 5 (`EventSerializer`) con gli eventi attivi nell'hash e la frequenza nelle impostazioni; le versioni 1–4 si caricano senza eventi e con la frequenza del preset;
|
||||
- protocollo: blocco 1 di `DailyDigest` con gli eventi in corso (`WorldEventInfo`), blocco 2 di `MarketReport` con quelli sulla domanda di un bene; client: riquadro «Eventi in corso» sopra la minimappa, avvisi nelle schede di industria e città, «evento in corso» nel Mercato globale, notizie degli eventi sempre nel notiziario, testi in `strings.csv` (corretta anche una chiave con la virgola non tra virgolette);
|
||||
- scenari: campo facoltativo `eventFrequencyMultiplier`; `valdoria.json` lo mette a 0, così l'accettazione F2 e F4 resta invariata (35 / 20 guasti senza la linea, 75 / 2 con la linea). Con gli eventi a frequenza «Imprenditore» la rete senza linea si fermava a 41 con 10 guasti e il criterio «sotto 40 entro 3 anni» non valeva più (ADR 0017 §8);
|
||||
- le IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi;
|
||||
- test (`Simulation/EventTests.cs`, 17): catalogo e validazione, effetti di ogni tipo e loro fine, solo la zona per domanda e maltempo, treni rallentati, officina senza personale, durata, niente doppioni, frequenza 0, stesso seme stessi eventi, salvataggio con eventi attivi, migrazione dalla versione 4, un anno di eventi frequenti con gli invarianti (lento), eventi nel `DailyDigest` e nel `MarketReport`. 160 test (142 senza i lenti).
|
||||
- Restano della F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
- F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
@@ -123,6 +132,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
|
||||
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
|
||||
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
# ADR 0017 — Eventi del mondo con effetti temporanei e notizie (F6)
|
||||
|
||||
Stato: accettato (F6, issue #33).
|
||||
|
||||
## Contesto
|
||||
|
||||
La roadmap F6 (guida, sezione 16) chiede gli «eventi»: fatti del mondo che cambiano per un po' il
|
||||
gioco e che il giocatore legge nel notiziario. Fino alla F5 esistevano solo gli shock mondiali dei
|
||||
prezzi di `MarketSystem` (ADR 0004 e 0015), che fanno parte del modello dei prezzi. La guida non dice
|
||||
quali eventi, con che frequenza, come agiscono sui sistemi, come si salvano né come arrivano al
|
||||
client. Servono effetti leggibili (si sa cosa succede, dove e fino a quando), reversibili (a evento
|
||||
finito tutto torna come prima) e deterministici.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Catalogo in `data/events.json`** (schema `data/schema/events.schema.json`, caricato in
|
||||
`GameData.Events`, validato da `DataValidator`). Ogni tipo ha id, nomi it/en, bersaglio
|
||||
(`industry`, `town`, `townGood`, `area`, `depot`), raggio della zona in km (solo `area` e
|
||||
`townGood`), probabilità annua, durata min/max in giorni, anno minimo, popolazione minima della
|
||||
città, beni o tipi di industria ammessi (facoltativi), gravità, effetti con ampiezza min/max e le
|
||||
notizie d'inizio e di fine con i segnaposti `{target}`, `{good}`, `{pct}` (effetto principale),
|
||||
`{days}`, `{until}`. Il validatore controlla id univoci, intervalli non invertiti, beni esistenti e
|
||||
di consumo delle città, raggio presente solo dove serve ed effetti compatibili con il bersaglio.
|
||||
`maxActive` (6) limita gli eventi attivi insieme su tutta la mappa: il notiziario resta leggibile.
|
||||
2. **Tipi.** Nove tipi, adattati a ciò che il motore permette senza riscritture:
|
||||
- industria: *incidente* (capacità × 0–0,5 per 10–45 giorni) e *boom di produzione* (× 1,2–1,5
|
||||
per 30–120 giorni);
|
||||
- città: *fiera* (consumi della città × 1,3–1,8 per 7–20 giorni, città da 1.500 abitanti) ed
|
||||
*epidemia* (consumi × 0,7–0,9 e presenze dei suoi lavoratori × 0,5–0,8 per 30–90 giorni, da 2.000
|
||||
abitanti). Il motore non ha passeggeri occasionali, solo pendolari: la «domanda di passeggeri»
|
||||
della richiesta diventa la domanda di beni della città (fiera) e le presenze al lavoro
|
||||
(epidemia);
|
||||
- bene: *boom* (× 1,4–2,0) e *crollo* (× 0,3–0,7) della domanda di un bene di consumo nelle città
|
||||
entro 15 km da una città, per 60–180 giorni;
|
||||
- maltempo: velocità dei treni × 0,5–0,8 e usura del binario dovuta al traffico × 2–4 (8.3) sugli
|
||||
archi il cui punto medio cade entro 12 km da una città, per 3–12 giorni;
|
||||
- sciopero: dei lavoratori di una città (presenze × 0,2–0,6, città da 1.000 abitanti) o del
|
||||
personale di un deposito (presenze × 0–0,5, sezione 9: l'officina rallenta come senza
|
||||
personale), per 5–20 giorni.
|
||||
Gli shock mondiali dei prezzi restano in `MarketSystem` con i loro parametri in `balance.json`
|
||||
(`market.world`): sono parte della formula del prezzo (6.3), non un moltiplicatore temporaneo su
|
||||
un'entità, e spostarli avrebbe cambiato i numeri. Non hanno quindi una voce nel catalogo.
|
||||
3. **Una sola sorgente degli effetti.** Lo stato è `World.WorldEvents` (`WorldEventState`): elenco
|
||||
degli eventi attivi (`ActiveWorldEvent`: tipo, bersaglio, bene, giorno d'inizio e di fine,
|
||||
intensità in [0, 1]) con le interrogazioni per entità che restituiscono il prodotto degli effetti
|
||||
attivi, 1 senza eventi: `IndustryCapacity` (letta da `IndustrySystem` per produzione, capacità
|
||||
installata ed efficienza, e da `DemandSystem` per la domanda di input), `TownDemand`
|
||||
(`DemandSystem.TownDemand`, quindi anche stime e IA), `Attendance` (presenze dei pendolari in
|
||||
`EmploymentSystem`: città d'origine e deposito di destinazione; contratti e coperture del
|
||||
trasporto non cambiano), `EdgeSpeed` (fattore di condizione del binario in `TrainSystem`, anche
|
||||
nell'anticipo dei limiti) ed `EdgeWear` (`ConstructionSystem`). Nessun sistema modifica uno stato
|
||||
«di base»: a evento scaduto il moltiplicatore torna 1 e tutto torna come prima. Le medie mobili
|
||||
esistenti (coperture a 30 giorni, margini) si riprendono con i loro tempi, come dopo ogni altro
|
||||
cambiamento. Un valore per ogni effetto = min + intensità·(max − min); l'intensità è una sola per
|
||||
evento, così gli effetti di uno stesso evento sono coerenti.
|
||||
4. **Frequenza per mappa, non per bersaglio.** `chancePerYear` è il numero atteso di eventi di quel
|
||||
tipo all'anno sull'intera mappa, moltiplicato per `eventFrequencyMultiplier` della difficoltà
|
||||
(nuovo campo di `difficulty.json`: 0,7 / 1,0 / 1,2 / 1,4, ritoccabile come «Personalizzata»;
|
||||
0 disattiva gli eventi). Il bersaglio si sceglie poi a caso tra quelli ammessi. Così il flusso di
|
||||
notizie non cresce con la dimensione della mappa (con «Imprenditore» circa 7,7 eventi l'anno
|
||||
prima del tetto) e ogni giorno costa una estrazione per tipo, non una per entità.
|
||||
5. **Sistema `EventSystem`**, tra le IA e l'hash, al posto di «Events» nell'ordine della guida
|
||||
(… → AiAgents → Events → Contracts → Hash). Ogni giorno chiude gli eventi giunti all'ultimo giorno
|
||||
o con il bersaglio sparito (industria chiusa o a livello 0, deposito demolito: senza notizia di
|
||||
fine), poi per ogni tipo, in ordine di catalogo, dall'anno minimo: un'estrazione `Chance` con il
|
||||
flusso dedicato `World.Stream("events")` (derivato con `Rng.Fork`, salvato con gli altri); se il
|
||||
tetto non è raggiunto, i candidati in ordine di id (industrie aperte di livello > 0, depositi vivi,
|
||||
città sopra la popolazione minima; per `townGood` le coppie città–bene con domanda nell'anno) senza
|
||||
quelli che hanno già un evento dello stesso tipo, poi bersaglio, durata e intensità dallo stesso
|
||||
flusso. Stessi tipi diversi sullo stesso bersaglio si sommano (prodotto dei moltiplicatori).
|
||||
Posizione e date: girando dopo i sistemi giornalieri, un evento estratto il giorno S inizia il
|
||||
giorno S + 1 e agisce sui sistemi giornalieri nei giorni [inizio, fine), cioè esattamente per la
|
||||
durata estratta; si chiude la sera del suo ultimo giorno con la notizia di fine. I treni, che si
|
||||
muovono a ogni tick, sentono il maltempo dal tick successivo all'estrazione. Inizio e fine danno un
|
||||
`GameEvent` di tipo nuovo `EventKind.World` (10), in italiano, con l'entità coinvolta, per
|
||||
notiziario e Cronaca. `EventSystem.Force` fa iniziare un evento scelto (test, scenari, strumenti),
|
||||
senza numeri casuali.
|
||||
6. **Salvataggio, versione 5.** `EventSerializer` aggiunge in coda allo stato dinamico il prossimo id
|
||||
e gli eventi attivi (tipo e bene per id testuale, bersaglio, giorni, intensità); la zona si
|
||||
ricalcola dal catalogo al caricamento. Entra nell'hash giornaliero. Le impostazioni salvano anche
|
||||
`eventFrequencyMultiplier`. I salvataggi delle versioni 1–4 si caricano senza eventi attivi e con la
|
||||
frequenza del preset con lo stesso id nei dati correnti (1 se l'id non esiste): una partita salvata
|
||||
prima della F6 riceve gli eventi da quel momento. Un tipo o un bene tolti dai dati fanno finire
|
||||
l'evento al caricamento.
|
||||
7. **Protocollo e client.** `DailyDigest` (120) porta nel blocco 1 l'elenco compatto degli eventi in
|
||||
corso (`WorldEventInfo`: id, tipo, entità, bene, giorni, gravità e valori dei moltiplicatori);
|
||||
`MarketReport` (129) porta nel blocco 2 quelli sulla domanda di un bene, che il pannello «Mercato
|
||||
globale» mostra come «evento in corso» insieme allo shock mondiale (`MarketOutlook.GoodEvents`).
|
||||
Il client mostra il riquadro «Eventi in corso» sopra la minimappa (fino a quattro righe, i più
|
||||
vicini alla fine), l'avviso dell'evento nelle schede di industria e città coinvolte e manda sempre
|
||||
al notiziario le notizie `EventKind.World`, anche le opportunità. Testi con `T()` e chiavi in
|
||||
`strings.csv`; i nomi dei tipi vengono dal catalogo nella lingua dell'interfaccia.
|
||||
8. **Accettazione con gli eventi disattivati.** Lo scenario di riferimento `valdoria.json` mette
|
||||
`eventFrequencyMultiplier` a 0 (nuovo campo facoltativo degli scenari, che sostituisce quello della
|
||||
difficoltà): l'accettazione F2 e F4 e tutti i test sulla rete di Valdoria misurano il sistema che
|
||||
provano, non la fortuna. Con gli eventi attivi alla frequenza di «Imprenditore» la rete F4 senza
|
||||
linea dei ricambi resta a 41 di condizione minima con 10 guasti (19,7 per milione di km) invece di
|
||||
35 con 20 guasti: scioperi e maltempo riducono i km di servizio e l'usura, e il criterio della
|
||||
guida «sotto 40 entro 3 anni» non sarebbe più vero; con la linea resta 75 con 2 guasti. I numeri
|
||||
dell'accettazione F4 con gli eventi disattivati restano 35 / 20 guasti senza la linea e 75 / 2 con
|
||||
la linea. I mondi generati (`WorldFactory`) hanno gli eventi della difficoltà scelta.
|
||||
9. **IA.** Le compagnie IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi
|
||||
(le stime di domanda leggono `TownDemand`).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Ogni effetto è un moltiplicatore in un punto noto di un sistema esistente: aggiungere un tipo con
|
||||
un effetto già previsto è solo una voce del catalogo; un effetto nuovo richiede un caso in
|
||||
`EventEffectKind`, l'interrogazione in `WorldEventState`, la riga di compatibilità nel validatore e
|
||||
il punto del sistema che lo legge.
|
||||
- Le interrogazioni scorrono l'elenco degli eventi attivi (al massimo `maxActive`): per i treni il
|
||||
maltempo controlla prima un contatore e, senza eventi d'area, non costa nulla.
|
||||
- L'area del maltempo si misura sul punto medio dell'arco: un arco molto lungo è dentro o fuori
|
||||
per intero.
|
||||
- Una partita con eventi ha numeri diversi da una senza: per confronti e scenari didattici la
|
||||
frequenza si mette a 0 nella difficoltà o nello scenario.
|
||||
@@ -29,5 +29,6 @@ namespace RailEnterprise.Core.Data;
|
||||
[JsonSerializable(typeof(AiFile))]
|
||||
[JsonSerializable(typeof(ContractsFile))]
|
||||
[JsonSerializable(typeof(RegionsFile))]
|
||||
[JsonSerializable(typeof(EventsFile))]
|
||||
[JsonSerializable(typeof(DifficultyDef))]
|
||||
public sealed partial class DataJsonContext : JsonSerializerContext;
|
||||
@@ -229,6 +229,7 @@ public static class DataValidator
|
||||
if (t.Kind is ContractKind.Deliver or ContractKind.Service && t.Quantity is null) Err("contracts.json", $"{t.Id}: richiede quantity");
|
||||
if (t.Kind == ContractKind.GreatWork && t.LengthKm is null) Err("contracts.json", $"{t.Id}: una grande opera richiede lengthKm");
|
||||
}
|
||||
ValidateEvents(d, goodIds, errors);
|
||||
Unique("regions.json", d.Regions.Regions.Select(r => r.Id), errors);
|
||||
Unique("regions.json", d.Regions.NamePools.Select(r => r.Id), errors);
|
||||
var pools = d.Regions.NamePools.Select(p => p.Id).ToHashSet(StringComparer.Ordinal);
|
||||
@@ -238,6 +239,44 @@ public static class DataValidator
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Effetti ammessi per ogni bersaglio (ADR 0017).</summary>
|
||||
public static bool EffectFits(EventTarget target, EventEffectKind effect) => effect switch
|
||||
{
|
||||
EventEffectKind.IndustryCapacity => target == EventTarget.Industry,
|
||||
EventEffectKind.TownDemand => target == EventTarget.Town,
|
||||
EventEffectKind.GoodDemand => target == EventTarget.TownGood,
|
||||
EventEffectKind.Attendance => target is EventTarget.Town or EventTarget.Depot,
|
||||
EventEffectKind.TrainSpeed or EventEffectKind.TrackWear => target == EventTarget.Area,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static void ValidateEvents(GameData d, HashSet<string> goodIds, List<string> errors)
|
||||
{
|
||||
const string file = "events.json";
|
||||
Unique(file, d.Events.Events.Select(e => e.Id), errors);
|
||||
foreach (var e in d.Events.Events)
|
||||
{
|
||||
string p = $"{e.Id}:";
|
||||
if (e.DurationDays[0] > e.DurationDays[1]) errors.Add($"{file}: {p} durationDays [min, max] invertito");
|
||||
bool zone = e.Target is EventTarget.Area or EventTarget.TownGood;
|
||||
if (zone && e.RadiusKm is null) errors.Add($"{file}: {p} il bersaglio «{e.Target}» richiede radiusKm");
|
||||
if (!zone && e.RadiusKm is not null) errors.Add($"{file}: {p} radiusKm vale solo per area e townGood");
|
||||
if (e.Goods is not null && e.Target != EventTarget.TownGood) errors.Add($"{file}: {p} goods vale solo per townGood");
|
||||
if (e.IndustryKinds is not null && e.Target != EventTarget.Industry) errors.Add($"{file}: {p} industryKinds vale solo per industry");
|
||||
foreach (string g in e.Goods ?? [])
|
||||
{
|
||||
if (!goodIds.Contains(g)) errors.Add($"{file}: {p} bene sconosciuto «{g}»");
|
||||
else if (d.Goods.First(x => x.Id == g).Town is null) errors.Add($"{file}: {p} «{g}» non è un bene di consumo delle città");
|
||||
}
|
||||
Unique(file, e.Effects.Select(x => x.Kind.ToString()), errors, $"{p} effetti");
|
||||
foreach (var x in e.Effects)
|
||||
{
|
||||
if (x.Min > x.Max) errors.Add($"{file}: {p} effetto {x.Kind} con min > max");
|
||||
if (!EffectFits(e.Target, x.Kind)) errors.Add($"{file}: {p} l'effetto {x.Kind} non si applica al bersaglio {e.Target}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckCarComponents(VehicleDef v, HashSet<string> carComponents, List<string> errors)
|
||||
{
|
||||
foreach (string c in v.Components.Keys)
|
||||
|
||||
@@ -42,6 +42,8 @@ public sealed record DifficultyDef
|
||||
public required double TariffMultiplier { get; init; }
|
||||
public required double WearMultiplier { get; init; }
|
||||
public required double MarketVolatilityMultiplier { get; init; }
|
||||
/// <summary>Frequenza degli eventi del mondo (events.json): 0 li disattiva (ADR 0017).</summary>
|
||||
public required double EventFrequencyMultiplier { get; init; }
|
||||
public required int AiCompetitors { get; init; }
|
||||
public required double AiCapitalMultiplier { get; init; }
|
||||
public required double AiCostDiscount { get; init; }
|
||||
|
||||
@@ -9,7 +9,7 @@ public static class DifficultyOverrides
|
||||
public static readonly string[] Keys =
|
||||
[
|
||||
"initialCapital", "initialCredit", "baseInterestRate", "constructionCostMultiplier", "tariffMultiplier", "wearMultiplier",
|
||||
"marketVolatilityMultiplier", "aiCompetitors", "aiCapitalMultiplier", "aiCostDiscount", "playerTakeover", "takeoverRansomYears",
|
||||
"marketVolatilityMultiplier", "eventFrequencyMultiplier", "aiCompetitors", "aiCapitalMultiplier", "aiCostDiscount", "playerTakeover", "takeoverRansomYears",
|
||||
"bankruptcyDays", "publicFromStart", "playerShareAtStart", "ironman", "depletion",
|
||||
];
|
||||
|
||||
@@ -29,6 +29,7 @@ public static class DifficultyOverrides
|
||||
"tariffMultiplier" => d with { TariffMultiplier = Range(key, value, 0.1, 10) },
|
||||
"wearMultiplier" => d with { WearMultiplier = Range(key, value, 0, 10) },
|
||||
"marketVolatilityMultiplier" => d with { MarketVolatilityMultiplier = Range(key, value, 0, 10) },
|
||||
"eventFrequencyMultiplier" => d with { EventFrequencyMultiplier = Range(key, value, 0, 10) },
|
||||
"aiCompetitors" => d with { AiCompetitors = (int)Range(key, value, 0, 8) },
|
||||
"aiCapitalMultiplier" => d with { AiCapitalMultiplier = Range(key, value, 0, 10) },
|
||||
"aiCostDiscount" => d with { AiCostDiscount = Range(key, value, 0, 0.9) },
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RailEnterprise.Core.Data;
|
||||
|
||||
// Contenuto di events.json: catalogo degli eventi del mondo (F6, ADR 0017).
|
||||
|
||||
/// <summary>Bersaglio di un evento del mondo.</summary>
|
||||
public enum EventTarget
|
||||
{
|
||||
/// <summary>Un'industria aperta di livello > 0.</summary>
|
||||
Industry,
|
||||
/// <summary>Una città.</summary>
|
||||
Town,
|
||||
/// <summary>Un bene di consumo nelle città entro <c>radiusKm</c> da una città.</summary>
|
||||
TownGood,
|
||||
/// <summary>Un'area circolare di raggio <c>radiusKm</c> intorno a una città.</summary>
|
||||
Area,
|
||||
/// <summary>Un deposito di una compagnia.</summary>
|
||||
Depot,
|
||||
}
|
||||
|
||||
/// <summary>Effetto di un evento: un moltiplicatore temporaneo letto da un sistema esistente.</summary>
|
||||
public enum EventEffectKind
|
||||
{
|
||||
/// <summary>Capacità produttiva dell'industria (IndustrySystem, DemandSystem).</summary>
|
||||
IndustryCapacity,
|
||||
/// <summary>Domanda di tutti i beni di consumo della città (DemandSystem).</summary>
|
||||
TownDemand,
|
||||
/// <summary>Domanda di un bene nelle città della zona (DemandSystem).</summary>
|
||||
GoodDemand,
|
||||
/// <summary>Presenze dei lavoratori della città o del personale del deposito (EmploymentSystem).</summary>
|
||||
Attendance,
|
||||
/// <summary>Velocità dei treni sugli archi dell'area (TrainSystem).</summary>
|
||||
TrainSpeed,
|
||||
/// <summary>Usura del binario dovuta al traffico sugli archi dell'area (ConstructionSystem).</summary>
|
||||
TrackWear,
|
||||
}
|
||||
|
||||
/// <summary>Gravità della notizia (stessi valori di <c>EventSeverity</c>).</summary>
|
||||
public enum NewsSeverity { Info, Opportunity, Warning, Critical }
|
||||
|
||||
public sealed class EventsFile
|
||||
{
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
/// <summary>Numero massimo di eventi attivi insieme su tutta la mappa (leggibilità).</summary>
|
||||
public required int MaxActive { get; init; }
|
||||
public required List<WorldEventDef> Events { get; init; }
|
||||
}
|
||||
|
||||
public sealed class WorldEventDef
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
[JsonPropertyName("name_it")] public required string NameIt { get; init; }
|
||||
[JsonPropertyName("name_en")] public required string NameEn { get; init; }
|
||||
public required EventTarget Target { get; init; }
|
||||
/// <summary>Raggio della zona (TownGood, Area), in km dal centro della città.</summary>
|
||||
public double? RadiusKm { get; init; }
|
||||
/// <summary>Eventi attesi all'anno sull'intera mappa (difficoltà «Imprenditore»), non per bersaglio.</summary>
|
||||
public required double ChancePerYear { get; init; }
|
||||
/// <summary>Durata in giorni [min, max], estremi compresi.</summary>
|
||||
public required int[] DurationDays { get; init; }
|
||||
public required int MinYear { get; init; }
|
||||
/// <summary>Città bersaglio (Town, TownGood, Area) solo da questa popolazione.</summary>
|
||||
public int MinPopulation { get; init; }
|
||||
/// <summary>Beni ammessi per TownGood (assente = tutti i beni di consumo delle città).</summary>
|
||||
public List<string>? Goods { get; init; }
|
||||
/// <summary>Tipi di industria ammessi (assente = tutti).</summary>
|
||||
public List<IndustryKind>? IndustryKinds { get; init; }
|
||||
public required NewsSeverity Severity { get; init; }
|
||||
/// <summary>Effetti: il primo è quello principale, mostrato come {pct} nella notizia.</summary>
|
||||
public required List<EventEffectDef> Effects { get; init; }
|
||||
/// <summary>Notizia d'inizio: segnaposti {target}, {good}, {pct}, {days}, {until}.</summary>
|
||||
[JsonPropertyName("news_it")] public required string NewsIt { get; init; }
|
||||
/// <summary>Notizia di fine, con gli stessi segnaposti.</summary>
|
||||
[JsonPropertyName("newsEnd_it")] public required string NewsEndIt { get; init; }
|
||||
|
||||
/// <summary>Posizione nel catalogo (assegnata al caricamento).</summary>
|
||||
[JsonIgnore] public int Index { get; internal set; }
|
||||
|
||||
/// <summary>Indici dei beni ammessi (TownGood), risolti al caricamento.</summary>
|
||||
[JsonIgnore] public int[] GoodIndices { get; internal set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Moltiplicatore di un effetto: min + intensità·(max − min), con l'intensità dell'evento in [0, 1].</summary>
|
||||
public sealed class EventEffectDef
|
||||
{
|
||||
public required EventEffectKind Kind { get; init; }
|
||||
public required double Min { get; init; }
|
||||
public required double Max { get; init; }
|
||||
|
||||
public double At(double intensity) => Min + intensity * (Max - Min);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ public sealed class GameData
|
||||
[
|
||||
"goods.json", "industries.json", "vehicles.json", "eras.json", "tiers.json", "balance.json",
|
||||
"difficulty.json", "construction.json", "maintenance.json", "ai.json", "contracts.json", "regions.json",
|
||||
"events.json",
|
||||
];
|
||||
|
||||
public required IReadOnlyList<GoodDef> Goods { get; init; }
|
||||
@@ -31,6 +32,7 @@ public sealed class GameData
|
||||
public required AiFile Ai { get; init; }
|
||||
public required ContractsFile Contracts { get; init; }
|
||||
public required RegionsFile Regions { get; init; }
|
||||
public required EventsFile Events { get; init; }
|
||||
|
||||
/// <summary>XxHash64 del contenuto canonico (minificato) di tutti i file: client e server devono coincidere.</summary>
|
||||
public ulong Hash { get; private init; }
|
||||
@@ -72,6 +74,9 @@ public sealed class GameData
|
||||
return def is not null;
|
||||
}
|
||||
|
||||
/// <summary>Tipo di evento del mondo per id (null se assente dai dati).</summary>
|
||||
public WorldEventDef? EventType(string id) => Events.Events.FirstOrDefault(e => e.Id == id);
|
||||
|
||||
/// <summary>Preset di difficoltà per id.</summary>
|
||||
public DifficultyDef DifficultyPreset(string id) =>
|
||||
Difficulty.Presets.FirstOrDefault(p => p.Id == id) ?? throw new KeyNotFoundException($"Difficoltà sconosciuta: {id}");
|
||||
@@ -100,6 +105,7 @@ public sealed class GameData
|
||||
AiFile? ai = Read(source, "ai.json", DataJsonContext.Default.AiFile, errors, canonical);
|
||||
ContractsFile? contracts = Read(source, "contracts.json", DataJsonContext.Default.ContractsFile, errors, canonical);
|
||||
RegionsFile? regions = Read(source, "regions.json", DataJsonContext.Default.RegionsFile, errors, canonical);
|
||||
EventsFile? events = Read(source, "events.json", DataJsonContext.Default.EventsFile, errors, canonical);
|
||||
|
||||
if (errors.Count > 0) throw new DataValidationException(errors);
|
||||
|
||||
@@ -117,6 +123,7 @@ public sealed class GameData
|
||||
Ai = ai!,
|
||||
Contracts = contracts!,
|
||||
Regions = regions!,
|
||||
Events = events!,
|
||||
Hash = XxHash64.Hash(canonical.WrittenSpan),
|
||||
};
|
||||
|
||||
@@ -191,6 +198,13 @@ public sealed class GameData
|
||||
def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? [];
|
||||
}
|
||||
for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i;
|
||||
for (int i = 0; i < Events.Events.Count; i++)
|
||||
{
|
||||
var e = Events.Events[i];
|
||||
e.Index = i;
|
||||
e.GoodIndices = (e.Goods ?? Goods.Where(g => g.Town is not null).Select(g => g.Id))
|
||||
.Select(id => _goodIndex[id]).ToArray();
|
||||
}
|
||||
SparePartsGood = _goodIndex["spare_parts"];
|
||||
MachineryGood = _goodIndex["machinery"];
|
||||
}
|
||||
|
||||
@@ -81,6 +81,8 @@ public sealed class MarketOutlookReport
|
||||
public required List<GoodOutlook> Goods { get; init; }
|
||||
public required List<HubOutlook> Hubs { get; init; }
|
||||
public required MarketEvent Event { get; init; }
|
||||
/// <summary>Eventi del mondo in corso sulla domanda di un bene in una zona (ADR 0017), in ordine d'inizio.</summary>
|
||||
public required List<ActiveWorldEvent> GoodEvents { get; init; }
|
||||
public required TradingProgress Trading { get; init; }
|
||||
}
|
||||
|
||||
@@ -107,6 +109,7 @@ public static class MarketOutlook
|
||||
Goods = goods,
|
||||
Hubs = Hubs(w, company, stationLines),
|
||||
Event = StrongestEvent(w),
|
||||
GoodEvents = GoodEvents(w),
|
||||
Trading = Trading(w, company),
|
||||
};
|
||||
}
|
||||
@@ -388,6 +391,10 @@ public static class MarketOutlook
|
||||
return new MarketEvent(best, shock, days / w.Calendar.DaysPerMonth);
|
||||
}
|
||||
|
||||
/// <summary>Eventi del mondo in corso che cambiano la domanda di un bene (boom o crollo in una zona).</summary>
|
||||
public static List<ActiveWorldEvent> GoodEvents(World w) =>
|
||||
w.WorldEvents.Active.Where(e => e.Good >= 0 && e.Has(Data.EventEffectKind.GoodDemand)).ToList();
|
||||
|
||||
/// <summary>Avanzamento della compagnia verso il primo livello di tiers.json che sblocca il commercio.</summary>
|
||||
public static TradingProgress Trading(World w, CompanyId company)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo in corso (corpo del salvataggio dalla versione 5, ADR 0017): tipo e bene per id
|
||||
/// testuale, bersaglio, giorni d'inizio e fine, intensità. Le versioni precedenti si caricano senza
|
||||
/// eventi attivi. Entra nell'hash giornaliero con lo stato dinamico.
|
||||
/// </summary>
|
||||
public static class EventSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
s.Write(state.NextId);
|
||||
s.Write(state.Active.Count);
|
||||
foreach (var e in state.Active)
|
||||
{
|
||||
s.Write(e.Id);
|
||||
s.Write(e.Def.Id);
|
||||
s.Write((byte)e.TargetKind);
|
||||
s.Write(e.Target);
|
||||
s.Write(e.Good >= 0 ? w.Data.Goods[e.Good].Id : "");
|
||||
s.Write(e.StartDay);
|
||||
s.Write(e.EndDay);
|
||||
s.Write(e.Intensity);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
state.Clear();
|
||||
state.NextId = r.ReadInt32();
|
||||
int n = r.ReadInt32();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int id = r.ReadInt32();
|
||||
string type = r.ReadRequiredString();
|
||||
var kind = (EntityKind)r.ReadByte();
|
||||
int target = r.ReadInt32();
|
||||
string goodId = r.ReadRequiredString();
|
||||
long start = r.ReadInt64();
|
||||
long end = r.ReadInt64();
|
||||
double intensity = r.ReadDouble();
|
||||
// un tipo o un bene tolti dai dati fanno finire l'evento al caricamento
|
||||
var def = w.Data.EventType(type);
|
||||
if (def is null) continue;
|
||||
int good = -1;
|
||||
if (goodId.Length > 0 && !w.Data.TryGoodIndex(goodId, out good)) continue;
|
||||
var (center, radius2) = EventSystem.Zone(w, def, kind, target);
|
||||
state.Add(new ActiveWorldEvent
|
||||
{
|
||||
Id = id,
|
||||
Def = def,
|
||||
TargetKind = kind,
|
||||
Target = target,
|
||||
Good = good,
|
||||
StartDay = start,
|
||||
EndDay = end,
|
||||
Intensity = intensity,
|
||||
Center = center,
|
||||
RadiusSquaredM = radius2,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 4;
|
||||
public const int BodyVersion = 5;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
@@ -28,7 +28,7 @@ public static class WorldSerializer
|
||||
if (bodyVersion < 1 || bodyVersion > BodyVersion) throw new ArgumentOutOfRangeException(nameof(bodyVersion));
|
||||
s.Write(bodyVersion);
|
||||
WriteDictionary(w.Data, s);
|
||||
WriteSettings(w.Settings, s);
|
||||
WriteSettings(w.Settings, s, bodyVersion);
|
||||
WriteTerrain(w.Terrain, w.SeaSide, s);
|
||||
WriteDynamic(w, s, bodyVersion);
|
||||
s.Write(w.LastStateHash);
|
||||
@@ -246,6 +246,7 @@ public static class WorldSerializer
|
||||
if (version >= 2) MaintenanceSerializer.Write(w, s);
|
||||
if (version >= 3) CorporateSerializer.Write(w, s);
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
if (version >= 5) EventSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -265,7 +266,7 @@ public static class WorldSerializer
|
||||
foreach (var g in data.Goods) s.Write(g.Id);
|
||||
}
|
||||
|
||||
private static void WriteSettings(WorldSettings st, SaveWriter s)
|
||||
private static void WriteSettings(WorldSettings st, SaveWriter s, int version)
|
||||
{
|
||||
s.Write(st.Seed);
|
||||
s.Write(st.SizeKm);
|
||||
@@ -293,6 +294,8 @@ public static class WorldSerializer
|
||||
s.Write(d.PlayerShareAtStart);
|
||||
s.Write((byte)d.Ironman);
|
||||
s.Write((byte)d.Depletion);
|
||||
// versione 5 (F6): frequenza degli eventi del mondo
|
||||
if (version >= 5) s.Write(d.EventFrequencyMultiplier);
|
||||
}
|
||||
|
||||
private static void WriteTerrain(Terrain t, MapSide seaSide, SaveWriter s)
|
||||
@@ -340,7 +343,7 @@ public static class WorldSerializer
|
||||
goodMap[g] = data.TryGoodIndex(id, out int idx) ? idx : -1;
|
||||
}
|
||||
|
||||
var settings = ReadSettings(r);
|
||||
var settings = ReadSettings(data, r, version);
|
||||
var (terrain, seaSide) = ReadTerrain(r);
|
||||
var w = new World(data, settings, terrain, seaSide);
|
||||
ReadDynamic(w, r, goodMap, version);
|
||||
@@ -350,7 +353,7 @@ public static class WorldSerializer
|
||||
return w;
|
||||
}
|
||||
|
||||
private static WorldSettings ReadSettings(SaveReader r)
|
||||
private static WorldSettings ReadSettings(GameData data, SaveReader r, int version)
|
||||
{
|
||||
ulong seed = r.ReadUInt64();
|
||||
int size = r.ReadInt32();
|
||||
@@ -379,6 +382,15 @@ public static class WorldSerializer
|
||||
PlayerShareAtStart = r.ReadDouble(),
|
||||
Ironman = (IronmanRule)r.ReadByte(),
|
||||
Depletion = (DepletionRate)r.ReadByte(),
|
||||
EventFrequencyMultiplier = 0,
|
||||
};
|
||||
// le versioni 1–4 non hanno la frequenza degli eventi: si prende quella del preset con lo
|
||||
// stesso id nei dati correnti (1 per una difficoltà personalizzata sconosciuta)
|
||||
d = d with
|
||||
{
|
||||
EventFrequencyMultiplier = version >= 5
|
||||
? r.ReadDouble()
|
||||
: data.Difficulty.Presets.FirstOrDefault(p => p.Id == d.Id)?.EventFrequencyMultiplier ?? 1.0,
|
||||
};
|
||||
return new WorldSettings { Seed = seed, SizeKm = size, StartYear = startYear, RegionId = region, Endless = endless, Difficulty = d };
|
||||
}
|
||||
@@ -693,6 +705,8 @@ public static class WorldSerializer
|
||||
// versione 4 (F6): magazzini della compagnia e merce propria in viaggio
|
||||
if (version >= 4) TradingSerializer.Read(w, r);
|
||||
else TradingSerializer.Migrate(w);
|
||||
// versione 5 (F6): eventi del mondo in corso; prima nessun evento attivo
|
||||
if (version >= 5) EventSerializer.Read(w, r);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -18,6 +18,8 @@ public enum EventKind : byte
|
||||
Maintenance = 7,
|
||||
Employment = 8,
|
||||
Company = 9,
|
||||
/// <summary>Evento del mondo (events.json, ADR 0017): inizio e fine.</summary>
|
||||
World = 10,
|
||||
}
|
||||
|
||||
/// <summary>Riferimento facoltativo all'entità coinvolta.</summary>
|
||||
|
||||
@@ -16,6 +16,11 @@ public sealed class ScenarioFile
|
||||
public string Difficulty { get; set; } = "imprenditore";
|
||||
/// <summary>Numero di concorrenti IA (sostituisce quello della difficoltà; null = come la difficoltà).</summary>
|
||||
public int? AiCompetitors { get; set; }
|
||||
/// <summary>
|
||||
/// Frequenza degli eventi del mondo (sostituisce quella della difficoltà; null = come la difficoltà,
|
||||
/// 0 = nessun evento casuale): gli scenari di accettazione la mettono a 0 (ADR 0017).
|
||||
/// </summary>
|
||||
public double? EventFrequencyMultiplier { get; set; }
|
||||
public required ScenarioTerrain Terrain { get; init; }
|
||||
public List<ScenarioTown> Towns { get; set; } = [];
|
||||
public List<ScenarioIndustry> Industries { get; set; } = [];
|
||||
|
||||
@@ -29,6 +29,15 @@ public sealed record LoadedScenario(World World, ScenarioFile File)
|
||||
/// <summary>Costruisce un mondo da uno scenario JSON (terreno a mano + entità in posizioni date).</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
/// <summary>Ritocchi della difficoltà scritti nello scenario (concorrenti IA, frequenza degli eventi).</summary>
|
||||
private static List<(string Key, double Value)> Overrides(ScenarioFile file)
|
||||
{
|
||||
var list = new List<(string Key, double Value)>();
|
||||
if (file.AiCompetitors is { } ai) list.Add(("aiCompetitors", ai));
|
||||
if (file.EventFrequencyMultiplier is { } events) list.Add(("eventFrequencyMultiplier", events));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static LoadedScenario LoadFile(GameData data, string path) => Load(data, File.ReadAllText(path));
|
||||
|
||||
public static LoadedScenario Load(GameData data, string json)
|
||||
@@ -104,8 +113,8 @@ public static class ScenarioLoader
|
||||
StartYear = file.StartYear,
|
||||
DifficultyId = file.Difficulty,
|
||||
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
|
||||
DifficultyOverride = file.AiCompetitors is { } ai
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), [("aiCompetitors", ai)])
|
||||
DifficultyOverride = Overrides(file) is { Count: > 0 } overrides
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), overrides)
|
||||
: null,
|
||||
};
|
||||
var world = WorldFactory.FromMap(data, map, settings);
|
||||
|
||||
@@ -42,6 +42,7 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
|
||||
new FinanceSystem(),
|
||||
new StockMarketSystem(),
|
||||
new AiSystem(),
|
||||
new EventSystem(),
|
||||
new HashSystem(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -158,7 +158,8 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
var owner = w.Companies[e.Owner.Value];
|
||||
double before = e.Condition;
|
||||
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier;
|
||||
// il maltempo sull'area accelera l'usura del traffico (ADR 0017)
|
||||
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier * w.WorldEvents.EdgeWear(e);
|
||||
e.TonnesThisYear += e.WearToday;
|
||||
e.WearToday = 0;
|
||||
// la manutenzione ordinaria pagata annulla la deriva naturale; senza (bancarotta) il binario deperisce
|
||||
|
||||
@@ -43,7 +43,8 @@ public sealed class DemandSystem : ISimSystem
|
||||
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
|
||||
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
|
||||
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
|
||||
// capacità modificata dagli eventi del mondo (incidente, boom: ADR 0017)
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
var inputs = ind.Def.Recipe.Inputs;
|
||||
for (int i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
@@ -54,14 +55,18 @@ public sealed class DemandSystem : ISimSystem
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Domanda giornaliera di una città per un bene, in unità.</summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year)
|
||||
/// <summary>
|
||||
/// Domanda giornaliera di una città per un bene, in unità, con i moltiplicatori degli eventi del
|
||||
/// mondo in corso (fiera, epidemia, domanda del bene nella zona: ADR 0017) se <paramref name="events"/>.
|
||||
/// </summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year, bool events = true)
|
||||
{
|
||||
var def = w.Data.Goods[good];
|
||||
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
|
||||
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
|
||||
var tb = w.Data.Balance.Town;
|
||||
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), tb.DemandPriceFactorMin, tb.DemandPriceFactorMax);
|
||||
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
double d = town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
return events ? d * w.WorldEvents.TownDemand(town, good) : d;
|
||||
}
|
||||
}
|
||||
@@ -446,6 +446,8 @@ public sealed class EmploymentSystem : ISimSystem
|
||||
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
|
||||
if (!c.Walking) c.LowCoverageDays = c.Coverage < eb.DissolveCoverage ? c.LowCoverageDays + 1 : 0;
|
||||
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
||||
// eventi del mondo: epidemia o sciopero in città, sciopero in deposito (ADR 0017)
|
||||
present *= w.WorldEvents.Attendance(c.Town, c.Workplace);
|
||||
var p = Workplace(w, c.Workplace);
|
||||
if (c.Category == PaxClass.Staff) p.StaffPresent += present;
|
||||
else p.WorkersPresent += present;
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo (F6, ADR 0017): ogni giorno chiude quelli scaduti, poi per ogni tipo del
|
||||
/// catalogo (events.json, in ordine) estrae con il flusso dedicato «events» se ne nasce uno, con
|
||||
/// probabilità chancePerYear × difficoltà / giorni dell'anno, e sceglie il bersaglio tra i candidati
|
||||
/// in ordine di id. Nessun doppione dello stesso tipo sullo stesso bersaglio; al massimo maxActive
|
||||
/// eventi insieme. Inizio e fine danno una notizia (<see cref="EventKind.World"/>). Gli effetti sono
|
||||
/// moltiplicatori letti dai sistemi tramite <see cref="WorldEventState"/>.
|
||||
/// Gira dopo le IA e prima dell'hash, quindi dopo i sistemi giornalieri del giorno: un evento estratto
|
||||
/// oggi inizia domani (StartDay) e agisce sui sistemi giornalieri nei giorni [StartDay, EndDay), cioè
|
||||
/// esattamente per la durata estratta; si chiude a fine giornata del suo ultimo giorno (EndDay − 1),
|
||||
/// con la notizia di fine. I treni, che si muovono a ogni tick, lo sentono dal tick successivo.
|
||||
/// </summary>
|
||||
public sealed class EventSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Events";
|
||||
|
||||
private readonly List<(EntityKind Kind, int Target, int Good)> _candidates = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
Expire(w, ctx.Day);
|
||||
|
||||
double frequency = w.Difficulty.EventFrequencyMultiplier;
|
||||
if (frequency <= 0) return;
|
||||
var catalog = w.Data.Events;
|
||||
var rng = w.Stream("events");
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var def in catalog.Events)
|
||||
{
|
||||
if (ctx.Year < def.MinYear) continue;
|
||||
if (!rng.Chance(def.ChancePerYear * frequency / days)) continue;
|
||||
if (w.WorldEvents.Active.Count >= catalog.MaxActive) continue;
|
||||
Candidates(w, def, _candidates);
|
||||
if (_candidates.Count == 0) continue;
|
||||
var (kind, target, good) = _candidates[rng.NextInt(_candidates.Count)];
|
||||
int duration = rng.NextInt(def.DurationDays[0], def.DurationDays[1] + 1);
|
||||
double intensity = rng.NextDouble();
|
||||
Begin(w, def, kind, target, good, ctx.Day + 1, duration, intensity);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiude gli eventi scaduti o il cui bersaglio non esiste più (industria chiusa, deposito demolito).</summary>
|
||||
private static void Expire(World w, long day)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
for (int i = 0; i < state.Active.Count;)
|
||||
{
|
||||
var e = state.Active[i];
|
||||
bool alive = TargetAlive(w, e.TargetKind, e.Target);
|
||||
// domani è fuori dall'intervallo [StartDay, EndDay): oggi era l'ultimo giorno
|
||||
if (day + 1 < e.EndDay && alive)
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
state.RemoveAt(i);
|
||||
if (alive) Announce(w, e, e.Def.NewsEndIt, NewsSeverity.Info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fa iniziare subito un evento sul bersaglio indicato (test, scenari e strumenti; in partita li
|
||||
/// estrae il sistema). Restituisce null se il bersaglio non è ammesso dal tipo, se un evento dello
|
||||
/// stesso tipo è già in corso lì o se la durata non è positiva. Non usa numeri casuali e non
|
||||
/// controlla maxActive né l'anno minimo. Chiamato tra un giorno e l'altro (fuori dalla pipeline),
|
||||
/// l'evento agisce già sul giorno che sta per cominciare; a giornata iniziata, da domani.
|
||||
/// </summary>
|
||||
public static ActiveWorldEvent? Force(World w, string typeId, int target, int good = -1, int? durationDays = null, double intensity = 1.0)
|
||||
{
|
||||
var def = w.Data.EventType(typeId) ?? throw new ArgumentException($"Tipo di evento sconosciuto: {typeId}", nameof(typeId));
|
||||
var list = new List<(EntityKind Kind, int Target, int Good)>();
|
||||
Candidates(w, def, list);
|
||||
var kind = KindOf(def.Target);
|
||||
if (!list.Contains((kind, target, def.Target == EventTarget.TownGood ? good : -1))) return null;
|
||||
int duration = durationDays ?? def.DurationDays[0];
|
||||
if (duration <= 0) return null;
|
||||
long start = w.Clock.Tick % w.Calendar.TicksPerDay == 0 ? w.Clock.Day : w.Clock.Day + 1;
|
||||
return Begin(w, def, kind, target, good, start, duration, Math.Clamp(intensity, 0, 1));
|
||||
}
|
||||
|
||||
private static ActiveWorldEvent Begin(World w, WorldEventDef def, EntityKind kind, int target, int good, long start, int duration, double intensity)
|
||||
{
|
||||
var (center, radius2) = Zone(w, def, kind, target);
|
||||
var e = new ActiveWorldEvent
|
||||
{
|
||||
Id = w.WorldEvents.NextId++,
|
||||
Def = def,
|
||||
TargetKind = kind,
|
||||
Target = target,
|
||||
Good = def.Target == EventTarget.TownGood ? good : -1,
|
||||
StartDay = start,
|
||||
EndDay = start + duration,
|
||||
Intensity = intensity,
|
||||
Center = center,
|
||||
RadiusSquaredM = radius2,
|
||||
};
|
||||
w.WorldEvents.Add(e);
|
||||
Announce(w, e, def.NewsIt, def.Severity);
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Centro e raggio al quadrato della zona di un evento (dal catalogo e dalla città bersaglio).</summary>
|
||||
public static (Vec2 Center, double RadiusSquaredM) Zone(World w, WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
if (kind != EntityKind.Town || def.RadiusKm is not { } km || target < 0 || target >= w.Towns.Count) return (Vec2.Zero, 0);
|
||||
double r = km * 1000;
|
||||
return (w.Towns[target].Position, r * r);
|
||||
}
|
||||
|
||||
public static EntityKind KindOf(EventTarget target) => target switch
|
||||
{
|
||||
EventTarget.Industry => EntityKind.Industry,
|
||||
EventTarget.Depot => EntityKind.Depot,
|
||||
_ => EntityKind.Town,
|
||||
};
|
||||
|
||||
private static bool TargetAlive(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry => target < w.Industries.Count && !w.Industries[target].Closed && w.Industries[target].Level > 0,
|
||||
EntityKind.Depot => target < w.Network.Depots.Count && w.Network.IsAlive(w.Network.Depots[target]),
|
||||
EntityKind.Town => target < w.Towns.Count,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Bersagli ammessi in ordine deterministico (id dell'entità, poi indice del bene).</summary>
|
||||
private static void Candidates(World w, WorldEventDef def, List<(EntityKind, int, int)> into)
|
||||
{
|
||||
into.Clear();
|
||||
var state = w.WorldEvents;
|
||||
switch (def.Target)
|
||||
{
|
||||
case EventTarget.Industry:
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
if (def.IndustryKinds is { } kinds && !kinds.Contains(ind.Def.Kind)) continue;
|
||||
if (state.IsActive(def, EntityKind.Industry, ind.Id.Value)) continue;
|
||||
into.Add((EntityKind.Industry, ind.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Depot:
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!w.Network.IsAlive(d) || state.IsActive(def, EntityKind.Depot, d.Id.Value)) continue;
|
||||
into.Add((EntityKind.Depot, d.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Town:
|
||||
case EventTarget.Area:
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.TownGood:
|
||||
int year = w.Clock.Year;
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
foreach (int g in def.GoodIndices)
|
||||
{
|
||||
// solo i beni che la città consuma quest'anno (era e fine del consumo)
|
||||
if (DemandSystem.TownDemand(w, t, g, year, events: false) <= 0) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, g));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Announce(World w, ActiveWorldEvent e, string template, NewsSeverity severity)
|
||||
{
|
||||
string text = Format(w, e, template);
|
||||
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.World, (EventSeverity)(byte)severity, text, e.TargetKind, e.Target));
|
||||
}
|
||||
|
||||
/// <summary>Testo della notizia con i segnaposti {target}, {good}, {pct}, {days}, {until}.</summary>
|
||||
public static string Format(World w, ActiveWorldEvent e, string template) => template
|
||||
.Replace("{target}", TargetName(w, e.TargetKind, e.Target), StringComparison.Ordinal)
|
||||
.Replace("{good}", e.Good >= 0 ? w.Data.Goods[e.Good].NameIt.ToLowerInvariant() : "", StringComparison.Ordinal)
|
||||
.Replace("{pct}", $"{Math.Round(e.Primary * 100):0}%", StringComparison.Ordinal)
|
||||
.Replace("{days}", e.DurationDays.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal)
|
||||
.Replace("{until}", w.Calendar.DateOfDay(e.EndDay).ToString(), StringComparison.Ordinal);
|
||||
|
||||
public static string TargetName(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry when target < w.Industries.Count => w.Industries[target].Name,
|
||||
EntityKind.Depot when target < w.Network.Depots.Count => w.Network.Depots[target].Name,
|
||||
EntityKind.Town when target < w.Towns.Count => w.Towns[target].Name,
|
||||
_ => "?",
|
||||
};
|
||||
}
|
||||
@@ -60,9 +60,11 @@ public sealed class IndustrySystem : ISimSystem
|
||||
if (frac < ib.DepletionStartFraction) depletion = frac / ib.DepletionStartFraction;
|
||||
}
|
||||
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
|
||||
// eventi del mondo: incidente (capacità ridotta o nulla) e boom di produzione (ADR 0017)
|
||||
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion * capacity;
|
||||
for (int o = 0; o < recipe.Outputs.Count && !stopped; o++)
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * capacity * recipe.Outputs[o].PerCycle;
|
||||
|
||||
// copertura degli input di oggi: limita la produzione alle scorte disponibili
|
||||
double covInToday = 1.0;
|
||||
@@ -109,7 +111,7 @@ public sealed class IndustrySystem : ISimSystem
|
||||
double extracted = whole * recipe.Outputs[0].PerCycle * data.Difficulty.DepletionMultipliers.For(w.Difficulty.Depletion);
|
||||
site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted);
|
||||
}
|
||||
ind.Efficiency = eLabor * covInToday * depletion;
|
||||
ind.Efficiency = eLabor * covInToday * depletion * capacity;
|
||||
|
||||
// salari giornalieri ai presenti
|
||||
double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm;
|
||||
|
||||
@@ -243,7 +243,8 @@ public sealed class TrainSystem : ISimSystem
|
||||
// 2. velocità obiettivo: limiti presenti e futuri, fine dell'autorizzazione, fermata
|
||||
var step = t.Route[t.RouteIndex];
|
||||
var edge = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge);
|
||||
// condizione del binario e maltempo sull'area (ADR 0017)
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge) * w.WorldEvents.EdgeSpeed(edge);
|
||||
double limit = Math.Min(t.TopSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
|
||||
double target = Math.Min(limit, Math.Sqrt(2 * _brake * Math.Max(0, ma - 1)));
|
||||
target = Math.Min(target, LookaheadCap(w, t, needed + 500));
|
||||
@@ -657,7 +658,7 @@ public sealed class TrainSystem : ISimSystem
|
||||
{
|
||||
var step = t.Route[s];
|
||||
var e = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e);
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e) * w.WorldEvents.EdgeSpeed(e);
|
||||
double start = s == t.RouteIndex ? t.StepPos : 0;
|
||||
int n = e.S.Length;
|
||||
if (step.Forward)
|
||||
|
||||
@@ -95,6 +95,9 @@ public sealed class World
|
||||
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; } = new();
|
||||
|
||||
/// <summary>Avvisi di manutenzione del giorno (non salvati): il server li inoltra come MaintenanceAlert.</summary>
|
||||
public List<FleetAlert> Alerts { get; } = [];
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Evento del mondo in corso (ADR 0017): tipo del catalogo, bersaglio, bene (per la domanda di un
|
||||
/// bene), giorno d'inizio e di fine e intensità in [0, 1] da cui si ricavano i moltiplicatori.
|
||||
/// </summary>
|
||||
public sealed class ActiveWorldEvent
|
||||
{
|
||||
public required int Id { get; init; }
|
||||
public required WorldEventDef Def { get; init; }
|
||||
/// <summary>Entità bersaglio: industria, città (anche centro di zona e area) o deposito.</summary>
|
||||
public required EntityKind TargetKind { get; init; }
|
||||
public required int Target { get; init; }
|
||||
/// <summary>Bene coinvolto (TownGood), altrimenti −1.</summary>
|
||||
public int Good { get; init; } = -1;
|
||||
public required long StartDay { get; init; }
|
||||
/// <summary>Primo giorno senza l'evento: dura EndDay − StartDay giorni.</summary>
|
||||
public required long EndDay { get; init; }
|
||||
public required double Intensity { get; init; }
|
||||
|
||||
/// <summary>Centro della zona in metri (città bersaglio), per area e domanda di un bene.</summary>
|
||||
public Vec2 Center { get; init; }
|
||||
|
||||
/// <summary>Quadrato del raggio della zona in metri (0 senza zona).</summary>
|
||||
public double RadiusSquaredM { get; init; }
|
||||
|
||||
public int DurationDays => (int)(EndDay - StartDay);
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto indicato (1 se il tipo non ce l'ha).</summary>
|
||||
public double Effect(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return e.At(Intensity);
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
public bool Has(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto principale (il primo del catalogo).</summary>
|
||||
public double Primary => Def.Effects[0].At(Intensity);
|
||||
|
||||
public bool InZone(Vec2 p) => RadiusSquaredM > 0 && (p - Center).LengthSquared <= RadiusSquaredM;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo in corso: unica sorgente dei moltiplicatori temporanei letti dai sistemi. Ogni
|
||||
/// interrogazione restituisce il prodotto degli effetti attivi sull'entità (1 senza eventi), così a
|
||||
/// evento scaduto tutto torna come prima. L'elenco è in ordine d'inizio (id crescente).
|
||||
/// </summary>
|
||||
public sealed class WorldEventState
|
||||
{
|
||||
private readonly List<ActiveWorldEvent> _active = [];
|
||||
private int _areaEvents;
|
||||
|
||||
public IReadOnlyList<ActiveWorldEvent> Active => _active;
|
||||
|
||||
/// <summary>Prossimo id libero (mai riutilizzato).</summary>
|
||||
public int NextId { get; set; }
|
||||
|
||||
internal void Add(ActiveWorldEvent e)
|
||||
{
|
||||
_active.Add(e);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void RemoveAt(int index)
|
||||
{
|
||||
_active.RemoveAt(index);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void Clear()
|
||||
{
|
||||
_active.Clear();
|
||||
Recount();
|
||||
}
|
||||
|
||||
private void Recount()
|
||||
{
|
||||
_areaEvents = 0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area) _areaEvents++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Vero se un evento dello stesso tipo è già in corso sullo stesso bersaglio.</summary>
|
||||
public bool IsActive(WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def == def && e.TargetKind == kind && e.Target == target) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Eventi che riguardano un'entità (bersaglio diretto o città centro di una zona).</summary>
|
||||
public IEnumerable<ActiveWorldEvent> For(EntityKind kind, int index)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == kind && e.Target == index) yield return e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Capacità produttiva dell'industria (IndustrySystem, DemandSystem).</summary>
|
||||
public double IndustryCapacity(IndustryId industry)
|
||||
{
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == EntityKind.Industry && e.Target == industry.Value) f *= e.Effect(EventEffectKind.IndustryCapacity);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Domanda della città per un bene: eventi sulla città e sul bene nella zona.</summary>
|
||||
public double TownDemand(Town town, int good)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
switch (e.Def.Target)
|
||||
{
|
||||
case EventTarget.Town when e.Target == town.Id.Value:
|
||||
f *= e.Effect(EventEffectKind.TownDemand);
|
||||
break;
|
||||
case EventTarget.TownGood when e.Good == good && (e.Target == town.Id.Value || e.InZone(town.Position)):
|
||||
f *= e.Effect(EventEffectKind.GoodDemand);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quota dei pendolari che si presenta al lavoro: eventi sulla città di provenienza (epidemia,
|
||||
/// sciopero) e sul deposito di destinazione (sciopero del personale).
|
||||
/// </summary>
|
||||
public double Attendance(TownId town, WorkplaceRef workplace)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
bool hit = e.Def.Target switch
|
||||
{
|
||||
EventTarget.Town => e.Target == town.Value,
|
||||
EventTarget.Depot => workplace.Kind == WorkplaceKind.Depot && e.Target == workplace.Index,
|
||||
_ => false,
|
||||
};
|
||||
if (hit) f *= e.Effect(EventEffectKind.Attendance);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Velocità dei treni sull'arco (TrainSystem): aree di maltempo che contengono il suo punto medio.</summary>
|
||||
public double EdgeSpeed(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrainSpeed);
|
||||
|
||||
/// <summary>Usura del binario dovuta al traffico sull'arco (ConstructionSystem).</summary>
|
||||
public double EdgeWear(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrackWear);
|
||||
|
||||
private double AreaEffect(TrackEdge edge, EventEffectKind kind)
|
||||
{
|
||||
int mid = edge.X.Length / 2;
|
||||
var p = new Vec2(edge.X[mid], edge.Y[mid]);
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area && e.InZone(p)) f *= e.Effect(kind);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,8 @@ public sealed class WarehouseInfo
|
||||
|
||||
/// <summary>
|
||||
/// Quadro del mercato globale per la compagnia della sessione (F6): indice materie prime, beni con
|
||||
/// storico mensile e previsione, hub, evento in corso e avanzamento verso la compravendita in proprio.
|
||||
/// storico mensile e previsione, hub, evento in corso (shock mondiale ed eventi del mondo sulla domanda
|
||||
/// di un bene) e avanzamento verso la compravendita in proprio.
|
||||
/// </summary>
|
||||
public sealed class MarketReport : IMessage
|
||||
{
|
||||
@@ -231,6 +232,8 @@ public sealed class MarketReport : IMessage
|
||||
public bool RatingMet { get; init; }
|
||||
/// <summary>Blocco 1: magazzini della compagnia nelle sue stazioni vive (ADR 0016).</summary>
|
||||
public List<WarehouseInfo> Warehouses { get; init; } = [];
|
||||
/// <summary>Blocco 2 (ADR 0017): eventi del mondo in corso sulla domanda di un bene (boom o crollo in una zona).</summary>
|
||||
public List<WorldEventInfo> GoodEvents { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -242,10 +245,17 @@ public sealed class MarketReport : IMessage
|
||||
w.I32(EventGood); w.F32(EventShock); w.F32(EventMonths);
|
||||
w.Bool(TradingUnlocked); w.U8(TradingTier); w.F32(TradingProgress); w.Money(NetWorth); w.Money(NetWorthRequired);
|
||||
w.I32(TownsConnected); w.I32(TownsRequired); w.I32(TownPopulation); w.String(Rating); w.String(RatingRequired); w.Bool(RatingMet);
|
||||
w.Flags(Warehouses.Count > 0 ? (byte)1 : (byte)0);
|
||||
if (Warehouses.Count == 0) return;
|
||||
w.Count(Warehouses.Count);
|
||||
foreach (var h in Warehouses) h.Write(ref w);
|
||||
w.Flags((byte)((Warehouses.Count > 0 ? 1 : 0) | (GoodEvents.Count > 0 ? 2 : 0)));
|
||||
if (Warehouses.Count > 0)
|
||||
{
|
||||
w.Count(Warehouses.Count);
|
||||
foreach (var h in Warehouses) h.Write(ref w);
|
||||
}
|
||||
if (GoodEvents.Count > 0)
|
||||
{
|
||||
w.Count(GoodEvents.Count);
|
||||
foreach (var e in GoodEvents) e.Write(ref w);
|
||||
}
|
||||
}
|
||||
|
||||
public static MarketReport Read(ref SpanReader r)
|
||||
@@ -268,6 +278,10 @@ public sealed class MarketReport : IMessage
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Warehouses.Add(WarehouseInfo.Read(ref r));
|
||||
}
|
||||
if ((flags & 2) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.GoodEvents.Add(WorldEventInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -542,6 +542,49 @@ public sealed class EventInfo : IWritable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evento del mondo in corso (F6, ADR 0017): tipo del catalogo (id di events.json), bersaglio
|
||||
/// (entità come in <see cref="EventInfo"/>), bene (−1 se nessuno), giorni d'inizio e di fine
|
||||
/// (escluso) e valori dei moltiplicatori nell'ordine degli effetti del catalogo.
|
||||
/// </summary>
|
||||
public sealed class WorldEventInfo : IWritable
|
||||
{
|
||||
public int Id { get; init; }
|
||||
public string Type { get; init; } = "";
|
||||
public byte Entity { get; init; }
|
||||
public int EntityIndex { get; init; } = -1;
|
||||
public int Good { get; init; } = -1;
|
||||
public long StartDay { get; init; }
|
||||
public long EndDay { get; init; }
|
||||
public byte Severity { get; init; }
|
||||
public float[] Effects { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.String(Type); w.U8(Entity); w.I32(EntityIndex); w.I32(Good); w.I64(StartDay); w.I64(EndDay); w.U8(Severity);
|
||||
w.Count(Effects.Length);
|
||||
foreach (float f in Effects) w.F32(f);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorldEventInfo Read(ref SpanReader r)
|
||||
{
|
||||
int id = r.I32();
|
||||
string type = r.String();
|
||||
byte entity = r.U8();
|
||||
int index = r.I32(), good = r.I32();
|
||||
long start = r.I64(), end = r.I64();
|
||||
byte severity = r.U8();
|
||||
var effects = new float[r.Count()];
|
||||
for (int i = 0; i < effects.Length; i++) effects[i] = r.F32();
|
||||
r.Flags();
|
||||
return new WorldEventInfo
|
||||
{
|
||||
Id = id, Type = type, Entity = entity, EntityIndex = index, Good = good, StartDay = start, EndDay = end, Severity = severity, Effects = effects,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tratto di moto di un treno: arco percorso nel verso indicato tra due progressive.</summary>
|
||||
public readonly record struct MotionSegment(int Edge, bool Forward, double FromS, double ToS)
|
||||
{
|
||||
|
||||
@@ -320,6 +320,8 @@ public sealed class DailyDigest : IMessage
|
||||
public bool Slow { get; init; }
|
||||
public byte Speed { get; init; }
|
||||
public float TickMs { get; init; }
|
||||
/// <summary>Blocco 1 (F6, ADR 0017): eventi del mondo in corso su tutta la mappa.</summary>
|
||||
public List<WorldEventInfo> WorldEvents { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -329,7 +331,10 @@ public sealed class DailyDigest : IMessage
|
||||
w.Count(Events.Count);
|
||||
foreach (var e in Events) e.Write(ref w);
|
||||
w.U64(StateHash); w.Bool(Slow); w.U8(Speed); w.F32(TickMs);
|
||||
w.Flags(0);
|
||||
w.Flags(WorldEvents.Count > 0 ? (byte)1 : (byte)0);
|
||||
if (WorldEvents.Count == 0) return;
|
||||
w.Count(WorldEvents.Count);
|
||||
foreach (var e in WorldEvents) e.Write(ref w);
|
||||
}
|
||||
|
||||
public static DailyDigest Read(ref SpanReader r)
|
||||
@@ -348,7 +353,11 @@ public sealed class DailyDigest : IMessage
|
||||
Day = day, Tick = tick, Date = date, Cash = cash, NetWorth = worth, Rating = rating, Prices = prices, Events = events,
|
||||
StateHash = r.U64(), Slow = r.Bool(), Speed = r.U8(), TickMs = r.F32(),
|
||||
};
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.WorldEvents.Add(WorldEventInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,6 +410,7 @@ public static class Projection
|
||||
Slow = slow,
|
||||
Speed = speed,
|
||||
TickMs = tickMs,
|
||||
WorldEvents = w.WorldEvents.Active.Select(WorldEvent).ToList(),
|
||||
};
|
||||
|
||||
/// <summary>Hash di un record serializzato (per i delta per sessione).</summary>
|
||||
@@ -548,9 +549,18 @@ public static class Projection
|
||||
TownsRequired = trading.TownsRequired, TownPopulation = trading.TownPopulation, Rating = trading.Rating.ToString(),
|
||||
RatingRequired = trading.RatingRequired.ToString(), RatingMet = trading.RatingMet,
|
||||
Warehouses = Warehouses(w, company),
|
||||
GoodEvents = report.GoodEvents.Select(WorldEvent).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
Id = e.Id, Type = e.Def.Id, Entity = (byte)e.TargetKind, EntityIndex = e.Target, Good = e.Good,
|
||||
StartDay = e.StartDay, EndDay = e.EndDay, Severity = (byte)e.Def.Severity,
|
||||
Effects = e.Def.Effects.Select(x => (float)x.At(e.Intensity)).ToArray(),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Magazzini della compagnia nelle sue stazioni vive (ADR 0016): giacenze, merce in arrivo e
|
||||
/// quotazioni locali dei beni disponibili che si possono comprare, vendere o che sono in magazzino.
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
using static RailEnterprise.Tests.Rail.RailFixture;
|
||||
|
||||
namespace RailEnterprise.Tests.Simulation;
|
||||
|
||||
/// <summary>Eventi del mondo con effetti temporanei e notizie (F6, issue #33, ADR 0017).</summary>
|
||||
public static class EventTests
|
||||
{
|
||||
private static void AssertInvariants(World w, string when)
|
||||
{
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
|
||||
}
|
||||
|
||||
/// <summary>Copia esatta del mondo (salvataggio e caricamento del corpo): stesso stato e stesso futuro.</summary>
|
||||
private static World Clone(World w)
|
||||
{
|
||||
var s = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, s);
|
||||
return WorldSerializer.Read(TestData.Data, new SaveReader(s.WrittenSpan.ToArray()));
|
||||
}
|
||||
|
||||
/// <summary>Mondo generato di 64 km senza IA, con la frequenza degli eventi indicata.</summary>
|
||||
private static World Generated(ulong seed, double frequency, int ai = 0) =>
|
||||
TestWorlds.Small(seed, "imprenditore", ("eventFrequencyMultiplier", frequency), ("aiCompetitors", ai));
|
||||
|
||||
private static Town TownNamed(World w, string name) => w.Towns.Single(t => t.Name == name);
|
||||
|
||||
private static Industry IndustryOfType(World w, string type) => w.Industries.First(i => i.Def.Id == type);
|
||||
|
||||
private static List<GameEvent> WorldNews(World w) => w.Events.Recent.Where(e => e.Kind == EventKind.World).ToList();
|
||||
|
||||
// ------------------------------------------------------------------ catalogo
|
||||
|
||||
[Test(Description = "Il catalogo events.json è valido e copre industria, città, bene, maltempo e sciopero con effetti nel verso atteso")]
|
||||
public static void CatalogIsValidAndCoversEveryKind()
|
||||
{
|
||||
var d = TestData.Data;
|
||||
var events = d.Events.Events;
|
||||
Assert.True(d.Events.MaxActive > 0, "maxActive positivo");
|
||||
foreach (EventTarget t in Enum.GetValues<EventTarget>())
|
||||
Assert.True(events.Any(e => e.Target == t), $"manca un evento con bersaglio {t}");
|
||||
foreach (var e in events)
|
||||
{
|
||||
Assert.True(e.DurationDays[0] >= 1 && e.DurationDays[0] <= e.DurationDays[1], $"{e.Id}: durata");
|
||||
Assert.True(e.ChancePerYear > 0, $"{e.Id}: probabilità");
|
||||
Assert.True(e.NewsIt.Contains("{target}", StringComparison.Ordinal), $"{e.Id}: la notizia nomina il bersaglio");
|
||||
Assert.True(e.Effects.All(x => DataValidator.EffectFits(e.Target, x.Kind)), $"{e.Id}: effetti compatibili");
|
||||
Assert.Equal(e, d.EventType(e.Id));
|
||||
}
|
||||
double Primary(string id, bool max) => max ? d.EventType(id)!.Effects[0].Max : d.EventType(id)!.Effects[0].Min;
|
||||
Assert.True(Primary("industry_accident", true) < 1 && Primary("industry_accident", false) >= 0, "incidente: capacità ridotta o nulla");
|
||||
Assert.True(Primary("industry_boom", false) > 1, "boom: capacità aumentata");
|
||||
Assert.True(Primary("town_fair", false) > 1, "fiera: consumi aumentati");
|
||||
Assert.True(Primary("epidemic", true) < 1 && d.EventType("epidemic")!.Effects.Any(x => x.Kind == EventEffectKind.Attendance && x.Max < 1), "epidemia: consumi e presenze ridotti");
|
||||
Assert.True(Primary("good_demand_boom", false) > 1 && Primary("good_demand_slump", true) < 1, "boom e crollo della domanda di un bene");
|
||||
var storm = d.EventType("storm")!;
|
||||
Assert.True(storm.Effects.Single(x => x.Kind == EventEffectKind.TrainSpeed).Max < 1 && storm.Effects.Single(x => x.Kind == EventEffectKind.TrackWear).Min > 1, "maltempo: treni lenti e usura");
|
||||
Assert.True(Primary("strike_town", true) < 1 && Primary("strike_depot", true) < 1, "scioperi: presenze ridotte");
|
||||
Assert.True(d.EventType("good_demand_boom")!.GoodIndices.Length > 0, "beni ammessi risolti");
|
||||
Assert.True(d.Difficulty.Presets.All(p => p.EventFrequencyMultiplier > 0), "eventi attivi in ogni preset");
|
||||
}
|
||||
|
||||
[Test(Description = "Il validatore rifiuta un effetto incompatibile con il bersaglio, un bene sconosciuto, min > max, il raggio mancante e un bersaglio fuori elenco")]
|
||||
public static void CatalogValidationRejectsInconsistentEvents()
|
||||
{
|
||||
static IReadOnlyList<string> Errors(Action<JsonNode> mutate)
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var root = JsonNode.Parse(files["events.json"])!;
|
||||
mutate(root);
|
||||
files["events.json"] = root.ToJsonString();
|
||||
try
|
||||
{
|
||||
GameData.Load(new MemoryDataSource(files));
|
||||
}
|
||||
catch (DataValidationException ex)
|
||||
{
|
||||
return ex.Errors;
|
||||
}
|
||||
Assert.Fail("il catalogo alterato doveva essere rifiutato");
|
||||
return [];
|
||||
}
|
||||
var semantic = Errors(root =>
|
||||
{
|
||||
var list = root["events"]!.AsArray();
|
||||
list[0]!["effects"]![0]!["kind"] = "trainSpeed";
|
||||
list[1]!["effects"]![0]!["min"] = 2.0;
|
||||
list[1]!["effects"]![0]!["max"] = 1.5;
|
||||
list[4]!["goods"] = new JsonArray("unobtainium");
|
||||
list[6]!.AsObject().Remove("radiusKm");
|
||||
});
|
||||
Assert.True(semantic.Any(e => e.Contains("non si applica al bersaglio", StringComparison.Ordinal)), "effetto incompatibile");
|
||||
Assert.True(semantic.Any(e => e.Contains("min > max", StringComparison.Ordinal)), "min > max");
|
||||
Assert.True(semantic.Any(e => e.Contains("unobtainium", StringComparison.Ordinal)), "bene sconosciuto");
|
||||
Assert.True(semantic.Any(e => e.Contains("richiede radiusKm", StringComparison.Ordinal)), "raggio mancante");
|
||||
var schema = Errors(root => root["events"]![0]!["target"] = "planet");
|
||||
Assert.True(schema.Any(e => e.Contains("events.json", StringComparison.Ordinal)), "bersaglio fuori elenco");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ effetti
|
||||
|
||||
[Test(Description = "Incidente e boom: la capacità dell'industria segue il moltiplicatore e a evento scaduto torna 1")]
|
||||
public static void IndustryEventsScaleCapacityAndThenStop()
|
||||
{
|
||||
foreach (var (type, intensity, expected) in new[] { ("industry_accident", 0.5, 0.25), ("industry_boom", 1.0, 1.5) })
|
||||
{
|
||||
var f = Valdoria();
|
||||
f.W.RunDays(2);
|
||||
var a = f.W;
|
||||
var b = Clone(a);
|
||||
var mine = IndustryOfType(a, "iron_mine");
|
||||
var ev = EventSystem.Force(a, type, mine.Id.Value, durationDays: 5, intensity: intensity);
|
||||
Assert.NotNull(ev, $"{type} sulla miniera");
|
||||
Assert.Approx(expected, a.WorldEvents.IndustryCapacity(mine.Id), 1e-12, $"{type}: moltiplicatore");
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
var mineB = b.Industries[mine.Id.Value];
|
||||
Assert.True(mineB.Efficiency > 0, "la miniera lavora");
|
||||
Assert.Approx(expected * mineB.Efficiency, mine.Efficiency, 1e-12, $"{type}: efficienza scalata dalla capacità");
|
||||
Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(a.Industries.First(i => i.Def.Id == "coal_mine").Id), 0, "le altre industrie non cambiano");
|
||||
a.RunDays(5);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count, $"{type}: scaduto");
|
||||
Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(mine.Id), 0, $"{type}: capacità tornata normale");
|
||||
Assert.Equal(2, WorldNews(a).Count(e => e.EntityIndex == mine.Id.Value && e.Entity == EntityKind.Industry), $"{type}: notizia d'inizio e di fine");
|
||||
AssertInvariants(a, type);
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Fiera ed epidemia: la domanda della città segue il moltiplicatore, l'epidemia riduce anche le presenze dei suoi lavoratori")]
|
||||
public static void TownEventsScaleDemandAndAttendance()
|
||||
{
|
||||
foreach (var (type, intensity) in new[] { ("town_fair", 1.0), ("epidemic", 0.0) })
|
||||
{
|
||||
var f = Valdoria();
|
||||
f.W.RunDays(3);
|
||||
var a = f.W;
|
||||
var b = Clone(a);
|
||||
var town = TownNamed(a, "Valdoria");
|
||||
var ev = EventSystem.Force(a, type, town.Id.Value, durationDays: 4, intensity: intensity)!;
|
||||
double demand = ev.Effect(EventEffectKind.TownDemand);
|
||||
double attendance = ev.Effect(EventEffectKind.Attendance);
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
int goods = 0;
|
||||
for (int g = 0; g < a.Data.GoodCount; g++)
|
||||
{
|
||||
double db = b.Towns[town.Id.Value].DemandToday[g];
|
||||
if (db <= 0) continue;
|
||||
goods++;
|
||||
Assert.Approx(db * demand, town.DemandToday[g], 1e-9 * db, $"{type}: domanda di {a.Data.Goods[g].Id}");
|
||||
}
|
||||
Assert.True(goods > 0, "la città consuma");
|
||||
var other = TownNamed(a, "Borgo Ceresio");
|
||||
Assert.SequenceEqual(b.Towns[other.Id.Value].DemandToday, other.DemandToday, "le altre città non cambiano");
|
||||
|
||||
// presenze: i lavoratori di Valdoria nei posti vicini (a piedi) si presentano in quota
|
||||
CheckAttendance(a, b, town, attendance, type);
|
||||
a.RunDays(4);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count);
|
||||
Assert.Approx(1.0, a.WorldEvents.TownDemand(town, 0), 0, "domanda tornata normale");
|
||||
AssertInvariants(a, type);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Presenze dei posti di lavoro con pendolari della città: ricalcolate con il moltiplicatore e confrontate con il gemello senza evento.</summary>
|
||||
private static void CheckAttendance(World a, World b, Town town, double attendance, string what)
|
||||
{
|
||||
var ib = a.Data.Balance.Industry;
|
||||
int checkedPlaces = 0;
|
||||
foreach (var ind in a.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
var contracts = a.Commutes.Where(c => c.Workplace == ind.Ref && c.Category == PaxClass.Worker).ToList();
|
||||
if (!contracts.Any(c => c.Town == town.Id)) continue;
|
||||
double expected = EmploymentSystem.OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare);
|
||||
foreach (var c in contracts)
|
||||
{
|
||||
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
||||
expected += present * (c.Town == town.Id ? attendance : 1.0);
|
||||
}
|
||||
expected = Math.Min(expected, ind.JobsWorkers);
|
||||
Assert.Approx(expected, ind.WorkersPresent, 1e-9, $"{what}: presenze a {ind.Name}");
|
||||
if (attendance < 1) Assert.True(ind.WorkersPresent < b.Industries[ind.Id.Value].WorkersPresent, $"{what}: meno presenti a {ind.Name}");
|
||||
checkedPlaces++;
|
||||
}
|
||||
Assert.True(checkedPlaces > 0, $"{what}: un posto di lavoro con pendolari della città");
|
||||
}
|
||||
|
||||
[Test(Description = "Sciopero dei lavoratori di una città: presenze ridotte solo per chi viene da quella città, poi tutto come prima")]
|
||||
public static void TownStrikeCutsAttendanceOfItsWorkers()
|
||||
{
|
||||
var f = Valdoria();
|
||||
f.W.RunDays(3);
|
||||
var a = f.W;
|
||||
var b = Clone(a);
|
||||
var town = TownNamed(a, "Valdoria");
|
||||
var ev = EventSystem.Force(a, "strike_town", town.Id.Value, durationDays: 3, intensity: 0)!;
|
||||
Assert.Approx(0.2, ev.Primary, 1e-12);
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
CheckAttendance(a, b, town, 0.2, "sciopero");
|
||||
var sb = b.Towns[town.Id.Value];
|
||||
Assert.SequenceEqual(sb.DemandToday, town.DemandToday, "lo sciopero non cambia i consumi");
|
||||
a.RunDays(3);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count);
|
||||
Assert.Approx(1.0, a.WorldEvents.Attendance(town.Id, new WorkplaceRef(WorkplaceKind.Industry, 0)), 0);
|
||||
}
|
||||
|
||||
[Test(Description = "Boom e crollo della domanda di un bene: moltiplicano il consumo di quel bene solo nelle città della zona")]
|
||||
public static void GoodDemandEventsActOnTheZoneOnly()
|
||||
{
|
||||
foreach (var (type, intensity, expected) in new[] { ("good_demand_boom", 1.0, 2.0), ("good_demand_slump", 0.0, 0.3) })
|
||||
{
|
||||
var a = Generated(31, 0);
|
||||
a.RunDays(1);
|
||||
var b = Clone(a);
|
||||
var def = a.Data.EventType(type)!;
|
||||
var center = a.Towns.OrderByDescending(t => t.Population).First();
|
||||
int good = def.GoodIndices.First(g => DemandSystem.TownDemand(a, center, g, a.Clock.Year) > 0);
|
||||
var ev = EventSystem.Force(a, type, center.Id.Value, good, durationDays: 2, intensity: intensity)!;
|
||||
Assert.Approx(expected, ev.Primary, 1e-12);
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
double r2 = def.RadiusKm!.Value * 1000 * def.RadiusKm.Value * 1000;
|
||||
int inside = 0, outside = 0;
|
||||
foreach (var t in a.Towns)
|
||||
{
|
||||
var tb = b.Towns[t.Id.Value];
|
||||
bool zone = (t.Position - center.Position).LengthSquared <= r2;
|
||||
for (int g = 0; g < a.Data.GoodCount; g++)
|
||||
{
|
||||
double f = zone && g == good ? expected : 1.0;
|
||||
Assert.Approx(tb.DemandToday[g] * f, t.DemandToday[g], 1e-9 * Math.Max(1, tb.DemandToday[g]), $"{type}: {t.Name}, {a.Data.Goods[g].Id}");
|
||||
}
|
||||
if (zone) inside++;
|
||||
else outside++;
|
||||
}
|
||||
Assert.True(inside >= 1 && outside >= 1, $"città dentro ({inside}) e fuori ({outside}) dalla zona");
|
||||
a.RunDays(2);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count);
|
||||
Assert.Approx(1.0, a.WorldEvents.TownDemand(center, good), 0);
|
||||
AssertInvariants(a, type);
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Maltempo: gli archi dell'area hanno velocità ridotta e il traffico li consuma di più; fuori dall'area e dopo l'evento nessun effetto")]
|
||||
public static void StormSlowsAndWearsTheTrackInItsArea()
|
||||
{
|
||||
var f = Valdoria();
|
||||
f.BuildFreightNetwork();
|
||||
var a = f.W;
|
||||
var b = Clone(a);
|
||||
var town = TownNamed(a, "Valdoria");
|
||||
var ev = EventSystem.Force(a, "storm", town.Id.Value, durationDays: 3, intensity: 1.0)!;
|
||||
double speed = ev.Effect(EventEffectKind.TrainSpeed), wear = ev.Effect(EventEffectKind.TrackWear);
|
||||
Assert.Approx(0.8, speed, 1e-12);
|
||||
Assert.Approx(4.0, wear, 1e-12);
|
||||
Assert.False(ev.InZone(new Vec2(1e7, 1e7)), "lontano dall'area");
|
||||
|
||||
// stessa usura del traffico nei due mondi: con il maltempo l'arco perde «wear» volte di più
|
||||
var edges = a.Network.Edges.Where(e => e.State == EdgeState.Active).ToList();
|
||||
foreach (var e in edges)
|
||||
{
|
||||
e.WearToday = 2000;
|
||||
b.Network.Edges[e.Id.Value].WearToday = 2000;
|
||||
}
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
int affected = 0;
|
||||
foreach (var e in edges)
|
||||
{
|
||||
double factor = a.WorldEvents.EdgeWear(e);
|
||||
Assert.True(factor == 1.0 || Math.Abs(factor - wear) < 1e-12, "fattore dell'arco");
|
||||
Assert.Approx(factor == 1.0 ? 1.0 : speed, a.WorldEvents.EdgeSpeed(e), 1e-12, "velocità dell'arco");
|
||||
double dropA = 100 - e.Condition, dropB = 100 - b.Network.Edges[e.Id.Value].Condition;
|
||||
Assert.True(dropB > 0, "il traffico consuma il binario");
|
||||
Assert.Approx(dropB * factor, dropA, 1e-9, $"usura dell'arco {e.Id.Value}");
|
||||
if (factor > 1) affected++;
|
||||
}
|
||||
Assert.True(affected > 0, "archi nell'area");
|
||||
a.RunDays(3);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count);
|
||||
Assert.True(edges.All(e => a.WorldEvents.EdgeSpeed(e) == 1.0 && a.WorldEvents.EdgeWear(e) == 1.0), "nessun effetto dopo l'evento");
|
||||
}
|
||||
|
||||
[Test(Description = "Maltempo: un treno nell'area non supera il limite ridotto ed è più lento del gemello senza evento")]
|
||||
public static void StormSlowsTheTrains()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 4, "Merci 1");
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
f.W.RunDays(2);
|
||||
var a = f.W;
|
||||
var b = Clone(a);
|
||||
// intensità 0: velocità al 50 %, su tutta la rete (centro nel mezzo del tracciato)
|
||||
var center = a.Towns.OrderBy(t => (t.Position - a.Network.Stations[mine].Position).LengthSquared).First();
|
||||
var ev = EventSystem.Force(a, "storm", center.Id.Value, durationDays: 20, intensity: 0)!;
|
||||
double factor = ev.Effect(EventEffectKind.TrainSpeed);
|
||||
Assert.Approx(0.5, factor, 1e-12);
|
||||
double maxA = 0, maxB = 0, maxLimitA = 0;
|
||||
int ticks = 6 * a.Calendar.TicksPerDay;
|
||||
for (int k = 0; k < ticks; k++)
|
||||
{
|
||||
a.RunTicks(1);
|
||||
b.RunTicks(1);
|
||||
if (k < a.Calendar.TicksPerDay) continue; // un giorno per frenare al nuovo limite
|
||||
var ta = a.Trains[train];
|
||||
var tb = b.Trains[train];
|
||||
if (ta.Route.Count > 0 && ta.RouteIndex < ta.Route.Count)
|
||||
{
|
||||
var e = a.Network.Edges[ta.Route[ta.RouteIndex].Edge.Value];
|
||||
if (a.WorldEvents.EdgeSpeed(e) < 1)
|
||||
{
|
||||
maxA = Math.Max(maxA, ta.Speed * 3.6);
|
||||
maxLimitA = Math.Max(maxLimitA, e.SpeedLimitKmh.Max() * factor);
|
||||
}
|
||||
}
|
||||
maxB = Math.Max(maxB, tb.Speed * 3.6);
|
||||
}
|
||||
Assert.True(maxA > 0, "il treno si muove nell'area");
|
||||
Assert.True(maxA <= maxLimitA + 0.5, $"velocità {maxA:F1} km/h oltre il limite ridotto {maxLimitA:F1}");
|
||||
Assert.True(maxB > maxA + 1, $"senza maltempo il treno va più forte ({maxB:F1} contro {maxA:F1} km/h)");
|
||||
AssertInvariants(a, "maltempo");
|
||||
}
|
||||
|
||||
[Test(Description = "Sciopero in deposito: il personale non si presenta, l'officina resta senza tecnici fino alla fine")]
|
||||
public static void DepotStrikeEmptiesTheWorkshop()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
||||
var a = f.W;
|
||||
var depot = a.Network.Depots[net.Officina];
|
||||
Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 120), "personale in officina");
|
||||
var b = Clone(a);
|
||||
var ev = EventSystem.Force(a, "strike_depot", depot.Id.Value, durationDays: 5, intensity: 0)!;
|
||||
Assert.Approx(0.0, ev.Primary, 0);
|
||||
a.RunDays(1);
|
||||
b.RunDays(1);
|
||||
Assert.Equal(0.0, depot.StaffPresent, "nessun tecnico presente durante lo sciopero");
|
||||
Assert.True(b.Network.Depots[net.Officina].StaffPresent > 0, "senza sciopero il personale c'è");
|
||||
Assert.True(WorldNews(a).Any(e => e.Entity == EntityKind.Depot && e.EntityIndex == depot.Id.Value), "notizia sul deposito");
|
||||
a.RunDays(5);
|
||||
Assert.Equal(0, a.WorldEvents.Active.Count);
|
||||
Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 30), "il personale torna dopo lo sciopero");
|
||||
AssertInvariants(a, "sciopero in deposito");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ regole
|
||||
|
||||
[Test(Description = "La durata è rispettata al giorno: l'evento agisce per i giorni estratti, poi la notizia di fine")]
|
||||
public static void DurationIsRespected()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var w = f.W;
|
||||
w.RunDays(1);
|
||||
var mine = IndustryOfType(w, "iron_mine");
|
||||
long start = w.Clock.Day;
|
||||
var ev = EventSystem.Force(w, "industry_accident", mine.Id.Value, durationDays: 10, intensity: 0)!;
|
||||
Assert.Equal(start, ev.StartDay);
|
||||
Assert.Equal(start + 10, ev.EndDay);
|
||||
var news = WorldNews(w).Single();
|
||||
Assert.Equal(EventSeverity.Warning, news.Severity);
|
||||
Assert.Equal(EntityKind.Industry, news.Entity);
|
||||
Assert.True(news.Text.Contains(mine.Name, StringComparison.Ordinal) && news.Text.Contains("10 giorni", StringComparison.Ordinal) && news.Text.Contains("0%", StringComparison.Ordinal), news.Text);
|
||||
int stoppedDays = 0;
|
||||
for (int d = 0; d < 12; d++)
|
||||
{
|
||||
w.RunDays(1);
|
||||
if (mine.Efficiency == 0) stoppedDays++;
|
||||
Assert.Equal(d < 9, w.WorldEvents.Active.Contains(ev), $"giorno {d}: evento in corso");
|
||||
}
|
||||
Assert.Equal(10, stoppedDays, "dieci giorni di produzione nulla");
|
||||
var end = WorldNews(w).Last();
|
||||
Assert.Equal(start + 9, end.Day, "la notizia di fine arriva la sera dell'ultimo giorno");
|
||||
Assert.True(end.Text.Contains("riprende", StringComparison.Ordinal), end.Text);
|
||||
Assert.Equal(2, WorldNews(w).Count);
|
||||
}
|
||||
|
||||
[Test(Description = "Niente due eventi dello stesso tipo sullo stesso bersaglio; un bersaglio non ammesso si rifiuta")]
|
||||
public static void NoDuplicateOnTheSameTarget()
|
||||
{
|
||||
var w = Valdoria().W;
|
||||
var mine = IndustryOfType(w, "iron_mine");
|
||||
Assert.NotNull(EventSystem.Force(w, "industry_accident", mine.Id.Value));
|
||||
Assert.True(EventSystem.Force(w, "industry_accident", mine.Id.Value) is null, "doppione rifiutato");
|
||||
Assert.NotNull(EventSystem.Force(w, "industry_boom", mine.Id.Value), "un altro tipo sullo stesso bersaglio è ammesso");
|
||||
Assert.NotNull(EventSystem.Force(w, "industry_accident", IndustryOfType(w, "coal_mine").Id.Value), "lo stesso tipo su un altro bersaglio è ammesso");
|
||||
Assert.True(EventSystem.Force(w, "town_fair", 99) is null, "città inesistente");
|
||||
Assert.True(EventSystem.Force(w, "town_fair", TownNamed(w, "Valdoria").Id.Value, durationDays: 0) is null, "durata nulla");
|
||||
Assert.True(EventSystem.Force(w, "good_demand_boom", TownNamed(w, "Valdoria").Id.Value, w.Data.GoodIndex("iron_ore")) is null, "bene non di consumo");
|
||||
Assert.Throws<ArgumentException>(() => EventSystem.Force(w, "meteor", 0));
|
||||
Assert.Equal(3, w.WorldEvents.Active.Count);
|
||||
Assert.Approx(0.5 * 1.5, w.WorldEvents.IndustryCapacity(mine.Id), 1e-12, "incidente e boom insieme: la capacità è il prodotto dei due");
|
||||
}
|
||||
|
||||
[Test(Description = "Con la frequenza a zero (scenari di accettazione) non nasce nessun evento; la difficoltà scala la frequenza")]
|
||||
public static void FrequencyZeroMeansNoEvents()
|
||||
{
|
||||
var w = Generated(5, 0);
|
||||
w.RunDays(360);
|
||||
Assert.Equal(0, w.WorldEvents.NextId, "nessun evento in un anno");
|
||||
Assert.Equal(0.0, Valdoria().W.Difficulty.EventFrequencyMultiplier, "valdoria.json disattiva gli eventi");
|
||||
var d = TestData.Data;
|
||||
Assert.True(d.DifficultyPreset("apprendista").EventFrequencyMultiplier < d.DifficultyPreset("ferro_e_sangue").EventFrequencyMultiplier, "più eventi alle difficoltà alte");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ determinismo e salvataggi
|
||||
|
||||
private static (World World, List<string> News) FrequentYear(ulong seed, int days, Func<World, World>? midway = null)
|
||||
{
|
||||
var w = Generated(seed, 10);
|
||||
w.RunDays(days / 2);
|
||||
if (midway is not null) w = midway(w);
|
||||
w.RunDays(days - days / 2);
|
||||
return (w, w.Events.Recent.Where(e => e.Kind == EventKind.World).Select(e => $"{e.Day} {e.Text}").ToList());
|
||||
}
|
||||
|
||||
[Test(Description = "Determinismo: stesso seme, stessi eventi e stesso hash; un altro seme dà altri eventi")]
|
||||
public static void SameSeedSameEvents()
|
||||
{
|
||||
var (a, newsA) = FrequentYear(11, 180);
|
||||
var (b, newsB) = FrequentYear(11, 180);
|
||||
var (_, newsC) = FrequentYear(12, 180);
|
||||
Assert.True(newsA.Count >= 10, $"eventi frequenti: {newsA.Count} notizie");
|
||||
Assert.SequenceEqual(newsA, newsB, "stesse notizie");
|
||||
Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso hash");
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
|
||||
Assert.False(newsA.SequenceEqual(newsC), "un altro seme cambia gli eventi");
|
||||
}
|
||||
|
||||
[Test(Description = "Salvataggio e caricamento con eventi in corso: stessi eventi, stesso hash e stesso futuro")]
|
||||
public static void SaveAndLoadWithActiveEvents()
|
||||
{
|
||||
int activeAtSave = 0;
|
||||
World ThroughSave(World w)
|
||||
{
|
||||
if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30);
|
||||
activeAtSave = w.WorldEvents.Active.Count;
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico");
|
||||
Assert.SequenceEqual(w.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)),
|
||||
loaded.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)), "eventi ricaricati");
|
||||
Assert.Equal(w.WorldEvents.NextId, loaded.WorldEvents.NextId);
|
||||
Assert.Equal(w.Difficulty.EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza salvata");
|
||||
foreach (var e in loaded.WorldEvents.Active.Where(e => e.Def.Target is EventTarget.Area or EventTarget.TownGood))
|
||||
Assert.True(e.RadiusSquaredM > 0, "zona ricostruita");
|
||||
return loaded;
|
||||
}
|
||||
var (direct, newsDirect) = FrequentYear(17, 120, w =>
|
||||
{
|
||||
if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30);
|
||||
return w;
|
||||
});
|
||||
var (saved, newsSaved) = FrequentYear(17, 120, ThroughSave);
|
||||
Assert.True(activeAtSave > 0, "eventi in corso al salvataggio");
|
||||
Assert.Equal(direct.LastStateHash, saved.LastStateHash, "salvare e ricaricare non cambia il futuro");
|
||||
Assert.SequenceEqual(newsDirect, newsSaved, "stesse notizie");
|
||||
}
|
||||
|
||||
[Test(Description = "Un salvataggio della versione 4 si carica senza eventi attivi e con la frequenza del preset; la partita prosegue con gli invarianti")]
|
||||
public static void VersionFourSavesLoadWithoutEvents()
|
||||
{
|
||||
var w = Generated(23, 1);
|
||||
w.RunDays(3);
|
||||
if (w.WorldEvents.NextId == 0)
|
||||
{
|
||||
var body = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, body, 4);
|
||||
var same = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray()));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(same), "senza eventi lo stato è identico");
|
||||
}
|
||||
EventSystem.Force(w, "town_fair", w.Towns[0].Id.Value, durationDays: 20);
|
||||
var v4 = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, v4, 4);
|
||||
var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(v4.WrittenSpan.ToArray()));
|
||||
Assert.Equal(0, loaded.WorldEvents.Active.Count, "nessun evento attivo dopo la migrazione");
|
||||
Assert.Equal(0, loaded.WorldEvents.NextId);
|
||||
Assert.Equal(TestData.Data.DifficultyPreset("imprenditore").EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza dal preset");
|
||||
Assert.Approx(1.0, loaded.WorldEvents.TownDemand(loaded.Towns[0], 0), 0);
|
||||
loaded.RunDays(60);
|
||||
AssertInvariants(loaded, "dopo la migrazione");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Un anno con eventi frequenti (e IA): invarianti di denaro e merci, mai doppioni né oltre maxActive, quasi tutti i tipi")]
|
||||
public static void InvariantsHoldThroughAYearOfFrequentEvents()
|
||||
{
|
||||
var w = Generated(3, 10, ai: 2);
|
||||
var types = new HashSet<string>(StringComparer.Ordinal);
|
||||
int max = 0;
|
||||
for (int d = 0; d < w.Calendar.DaysPerYear; d++)
|
||||
{
|
||||
w.RunDays(1);
|
||||
var active = w.WorldEvents.Active;
|
||||
max = Math.Max(max, active.Count);
|
||||
Assert.True(active.Count <= w.Data.Events.MaxActive, $"giorno {d}: {active.Count} eventi");
|
||||
var keys = active.Select(e => (e.Def.Id, e.TargetKind, e.Target)).ToList();
|
||||
Assert.Equal(keys.Count, keys.Distinct().Count(), $"giorno {d}: doppioni");
|
||||
foreach (var e in active)
|
||||
{
|
||||
types.Add(e.Def.Id);
|
||||
Assert.True(e.DurationDays >= e.Def.DurationDays[0] && e.DurationDays <= e.Def.DurationDays[1], $"{e.Def.Id}: durata");
|
||||
Assert.True(e.StartDay <= w.Clock.Day && w.Clock.Day < e.EndDay, $"{e.Def.Id}: in corso oggi");
|
||||
Assert.InRange(e.Intensity, 0, 1, "intensità");
|
||||
}
|
||||
if (d % 30 == 29) AssertInvariants(w, $"giorno {d}");
|
||||
}
|
||||
Console.WriteLine($" {w.WorldEvents.NextId} eventi in un anno, al massimo {max} insieme, tipi: {string.Join(", ", types.Order(StringComparer.Ordinal))}");
|
||||
Assert.True(types.Count >= 7, $"tipi visti: {string.Join(", ", types)}");
|
||||
Assert.Equal(max, w.Data.Events.MaxActive, "con la frequenza alta si arriva al tetto");
|
||||
Assert.True(w.Events.Recent.Count(e => e.Kind == EventKind.World) >= Math.Min(w.WorldEvents.NextId, 250), "notizie degli eventi");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ protocollo e mercato
|
||||
|
||||
[Test(Description = "Protocollo: gli eventi in corso arrivano nel resoconto giornaliero e quelli sul bene nel quadro del mercato, con round-trip")]
|
||||
public static void EventsReachTheClient()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var w = f.W;
|
||||
var town = TownNamed(w, "Valdoria");
|
||||
var def = w.Data.EventType("good_demand_boom")!;
|
||||
int good = def.GoodIndices.First(g => DemandSystem.TownDemand(w, town, g, w.Clock.Year) > 0);
|
||||
var boom = EventSystem.Force(w, "good_demand_boom", town.Id.Value, good, durationDays: 90, intensity: 0.5)!;
|
||||
var storm = EventSystem.Force(w, "storm", town.Id.Value, durationDays: 5, intensity: 0.25)!;
|
||||
|
||||
var digest = RailEnterprise.Server.Projection.Digest(w, w.Player, [], false, 1, 0);
|
||||
Assert.Equal(2, digest.WorldEvents.Count);
|
||||
var decoded = (DailyDigest)Frame.Decode(Frame.Encode(digest));
|
||||
Assert.Equal(2, decoded.WorldEvents.Count);
|
||||
var s = decoded.WorldEvents.Single(e => e.Type == "storm");
|
||||
Assert.Equal(storm.Id, s.Id);
|
||||
Assert.Equal((byte)EntityKind.Town, s.Entity);
|
||||
Assert.Equal(town.Id.Value, s.EntityIndex);
|
||||
Assert.Equal(-1, s.Good);
|
||||
Assert.Equal(storm.StartDay, s.StartDay);
|
||||
Assert.Equal(storm.EndDay, s.EndDay);
|
||||
Assert.Equal((byte)NewsSeverity.Warning, s.Severity);
|
||||
Assert.Equal(2, s.Effects.Length);
|
||||
Assert.Approx(storm.Effect(EventEffectKind.TrainSpeed), s.Effects[0], 1e-6);
|
||||
Assert.Approx(storm.Effect(EventEffectKind.TrackWear), s.Effects[1], 1e-6);
|
||||
var g = decoded.WorldEvents.Single(e => e.Type == "good_demand_boom");
|
||||
Assert.Equal(good, g.Good);
|
||||
Assert.Approx(1.7, g.Effects[0], 1e-6);
|
||||
|
||||
// il quadro del mercato mostra l'evento sul bene come «evento in corso»
|
||||
var outlook = MarketOutlook.Build(w, f.Me);
|
||||
Assert.Equal(boom, outlook.GoodEvents.Single());
|
||||
var report = RailEnterprise.Server.Projection.Market(w, f.Me);
|
||||
var back = (MarketReport)Frame.Decode(Frame.Encode(report));
|
||||
Assert.Equal(boom.Id, back.GoodEvents.Single().Id);
|
||||
Assert.Equal(good, back.GoodEvents.Single().Good);
|
||||
Assert.Equal(report.Warehouses.Count, back.Warehouses.Count);
|
||||
|
||||
// senza eventi i blocchi non viaggiano e il resoconto resta compatibile
|
||||
var empty = RailEnterprise.Server.Projection.Digest(Valdoria().W, w.Player, [], false, 1, 0);
|
||||
Assert.Equal(0, ((DailyDigest)Frame.Decode(Frame.Encode(empty))).WorldEvents.Count);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
"startYear": 1850,
|
||||
"difficulty": "imprenditore",
|
||||
"aiCompetitors": 0,
|
||||
"eventFrequencyMultiplier": 0,
|
||||
"terrain": {
|
||||
"widthCells": 160,
|
||||
"heightCells": 120,
|
||||
|
||||
Reference in new issue
Block a user