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

@@ -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 &gt; 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);
}
+14
View File
@@ -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;
}
}
+10
View File
@@ -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.