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:
Alby96andClaude Opus 5.5 committed 2026-11-07 16:59:48 +01:00
1 parent b258e0858a
commit 1f8da87e51
41 files changed
+1892 -41

No files matched your search

@@ -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)