F6: mercato globale, storico prezzi a 24 mesi e previsione

Prima parte della F6: il pannello «Mercato globale» dell'immagine di
riferimento 06, con i dati calcolati dal server.

- Lo storico dei prezzi globali passa da 360 a 720 giorni. I salvataggi
  con lo storico di un anno si migrano al caricamento allungando la
  finestra (RollingWindow.Extended), senza cambiare formato.
- MarketOutlook (Core) è un'analisi in sola lettura del mondo: storico
  mensile, variazione a 30 giorni, offerta e domanda con la quota
  mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi
  dalla componente mondiale con banda, destinazioni di vendita ordinate
  per prezzo con la linea che le collega, hub, evento in corso e
  avanzamento verso la compravendita in proprio. Parametri nuovi in
  balance.json (market.outlook); interpretazioni nell'ADR 0015.
- Protocollo: DetailKind.Market (7) e MarketReport (129); il server
  risponde su richiesta, il client lo mostra in un pannello a tutto
  schermo e il pilota automatico ne fa la schermata 16_mercato.
- Test: finestra allungata e migrazione, storico mensile, previsione
  deterministica ed entro i limiti, evento, analisi su Valdoria,
  round-trip del messaggio e quadro via WebSocket.

La simulazione non cambia: l'analisi non scrive nel mondo e
l'accettazione F4 dà gli stessi numeri di prima.

Closes #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 14:25:38 +01:00
1 parent bfbdb6297e
commit 2992e7cc36
29 files changed
+1877 -50

No files matched your search

@@ -173,7 +173,27 @@ public sealed class MarketBalance
public required double RatioMin { get; init; }
public required double RatioMax { get; init; }
public required WorldMarketParams World { get; init; }
/// <summary>Giorni di prezzi globali conservati per bene (storico del pannello Mercato globale).</summary>
public required int HistoryDays { get; init; }
/// <summary>Analisi del mercato per il pannello «Mercato globale» (ADR 0015).</summary>
public required MarketOutlookBalance Outlook { get; init; }
}
/// <summary>Parametri dell'analisi del mercato (MarketOutlook, ADR 0015).</summary>
public sealed class MarketOutlookBalance
{
/// <summary>Mesi di storico mensile (un campione per mese di calendario).</summary>
public required int HistoryMonths { get; init; }
/// <summary>Giorni della variazione del prezzo e dell'indice («30 giorni»).</summary>
public required int ChangeDays { get; init; }
/// <summary>Mesi di previsione dalla componente mondiale.</summary>
public required int ForecastMonths { get; init; }
/// <summary>Semiampiezza della banda di previsione per mese di distanza (frazione del prezzo).</summary>
public required double ForecastBandPerMonth { get; init; }
/// <summary>Destinazioni elencate in «Dove conviene vendere».</summary>
public required int SellPlaces { get; init; }
/// <summary>Shock mondiale minimo (frazione del prezzo base) perché sia un «evento in corso».</summary>
public required double EventThreshold { get; init; }
}
public sealed class WorldMarketParams
@@ -145,6 +145,9 @@ public static class DataValidator
var b = d.Balance;
if (!b.Time.Speeds.Contains(0) || !b.Time.Speeds.Contains(1)) Err("balance.json", "time.speeds deve contenere 0 e 1");
if (b.Market.MinPriceFactor >= 1 || b.Market.MaxPriceFactor <= 1) Err("balance.json", "market: i fattori di prezzo devono racchiudere 1");
if (b.Market.Outlook.HistoryMonths * b.Time.DaysPerMonth > b.Market.HistoryDays)
Err("balance.json", "market.outlook.historyMonths: lo storico mensile richiede più giorni di market.historyDays");
if (b.Market.Outlook.ChangeDays >= b.Market.HistoryDays) Err("balance.json", "market.outlook.changeDays deve essere minore di market.historyDays");
foreach (int size in b.Map.SizesKm)
{
string key = size.ToString(System.Globalization.CultureInfo.InvariantCulture);
+1 -1
View File
@@ -49,7 +49,7 @@ public sealed class Market
public RollingWindow[] Demand { get; private set; }
public RollingWindow[] Supply { get; private set; }
/// <summary>Storico dei prezzi globali (un anno).</summary>
/// <summary>Storico dei prezzi globali giornalieri (market.historyDays: 24 mesi dalla F6).</summary>
public RollingWindow[] PriceHistory { get; private set; }
/// <summary>Giorni consecutivi con domanda insoddisfatta, per bene (nascita di nuove industrie).</summary>
@@ -0,0 +1,421 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Economy;
/// <summary>Prezzo globale di un giorno (centesimi per unità).</summary>
public readonly record struct PricePoint(long Day, double Price);
/// <summary>Prezzo previsto a una distanza in mesi, con la banda bassa e alta.</summary>
public readonly record struct ForecastPoint(int Months, double Price, double Low, double High);
public enum SellPlaceKind : byte { Industry = 0, Hub = 1 }
/// <summary>
/// Destinazione dove vendere un bene: industria che lo consuma (prezzo locale) o hub
/// (prezzo d'esportazione), con la linea della compagnia che la serve (None se non collegata).
/// </summary>
public readonly record struct SellPlace(SellPlaceKind Kind, int Target, double Price, LineId Line);
/// <summary>Quadro di un bene per il pannello «Mercato globale».</summary>
public sealed class GoodOutlook
{
public required int Good { get; init; }
/// <summary>Bene già disponibile nell'era corrente.</summary>
public required bool Available { get; init; }
public required double Price { get; init; }
/// <summary>Variazione del prezzo su market.outlook.changeDays giorni (frazione).</summary>
public required double Change { get; init; }
/// <summary>Offerta e domanda della mappa in un mese (finestre di 30 giorni riportate al mese).</summary>
public required double SupplyMonth { get; init; }
public required double DemandMonth { get; init; }
/// <summary>Quota del mercato mondiale scambiata dagli hub in un mese (componente W di MarketSystem).</summary>
public required double WorldSupplyMonth { get; init; }
public required double WorldDemandMonth { get; init; }
/// <summary>Giacenze nei magazzini delle industrie aperte e nelle stazioni.</summary>
public required double StockUnits { get; init; }
/// <summary>Giacenze diviso domanda mensile della mappa (−1 se la domanda è nulla).</summary>
public required double StockMonths { get; init; }
/// <summary>Un campione per mese di calendario, dal più vecchio; l'ultimo è il giorno corrente.</summary>
public required List<PricePoint> History { get; init; }
public required List<ForecastPoint> Forecast { get; init; }
public required List<SellPlace> SellPlaces { get; init; }
}
/// <summary>Hub verso il mercato mondiale visto dalla compagnia.</summary>
public readonly record struct HubOutlook(HubId Hub, HubKind Kind, int MonthlyCapacity, double Duty, int UsedThisMonth, LineId Line);
/// <summary>Shock mondiale in corso più forte (Good −1 se nessuno supera la soglia).</summary>
public readonly record struct MarketEvent(int Good, double Shock, double Months)
{
public static readonly MarketEvent None = new(-1, 0, 0);
}
/// <summary>Avanzamento verso il primo livello che sblocca la compravendita in proprio.</summary>
public sealed class TradingProgress
{
public required bool Unlocked { get; init; }
/// <summary>Livello che sblocca il commercio (0 se nessuno).</summary>
public required int Level { get; init; }
/// <summary>Minimo tra le frazioni dei requisiti numerici (patrimonio, città collegate), in [0, 1].</summary>
public required double Fraction { get; init; }
public required Money NetWorth { get; init; }
public required Money NetWorthRequired { get; init; }
public required int TownsConnected { get; init; }
public required int TownsRequired { get; init; }
public required int TownPopulation { get; init; }
public required CreditRating Rating { get; init; }
public required CreditRating RatingRequired { get; init; }
public required bool RatingMet { get; init; }
}
public sealed class MarketOutlookReport
{
public required long Day { get; init; }
/// <summary>Indice materie prime: media di Pg/Pb × 100 sui beni disponibili.</summary>
public required double Index { get; init; }
public required double IndexChange { get; init; }
public required List<GoodOutlook> Goods { get; init; }
public required List<HubOutlook> Hubs { get; init; }
public required MarketEvent Event { get; init; }
public required TradingProgress Trading { get; init; }
}
/// <summary>
/// Analisi del mercato per il pannello «Mercato globale» (ADR 0015): pura funzione del mondo,
/// nessuno stato nuovo e nessun numero casuale. Storico mensile dalla finestra dei prezzi,
/// variazioni, offerta e domanda, scorte, indice materie prime, previsione dalla componente
/// mondiale, destinazioni di vendita, hub, evento in corso e avanzamento verso il commercio.
/// </summary>
public static class MarketOutlook
{
public static MarketOutlookReport Build(World w, CompanyId company)
{
var data = w.Data;
var stationLines = StationLines(w, company);
var goods = new List<GoodOutlook>(data.GoodCount);
for (int g = 0; g < data.GoodCount; g++) goods.Add(Good(w, g, company, stationLines));
var (index, indexChange) = CommodityIndex(w);
return new MarketOutlookReport
{
Day = w.Clock.Day,
Index = index,
IndexChange = indexChange,
Goods = goods,
Hubs = Hubs(w, company, stationLines),
Event = StrongestEvent(w),
Trading = Trading(w, company),
};
}
/// <summary>Bene disponibile nell'anno corrente (era).</summary>
public static bool IsAvailable(World w, int good) => w.Data.Goods[good].Era <= w.Clock.Year;
public static GoodOutlook Good(World w, int g, CompanyId company, LineId[] stationLines)
{
var market = w.Market;
bool available = IsAvailable(w, g);
var (supply, demand, worldSupply, worldDemand) = MonthlyFlows(w, g);
double stock = StockUnits(w, g);
return new GoodOutlook
{
Good = g,
Available = available,
Price = market.GlobalPrice[g],
Change = Change(w, g, w.Data.Balance.Market.Outlook.ChangeDays),
SupplyMonth = supply,
DemandMonth = demand,
WorldSupplyMonth = worldSupply,
WorldDemandMonth = worldDemand,
StockUnits = stock,
StockMonths = demand > 0 ? stock / demand : -1,
History = MonthlyHistory(w, g, w.Data.Balance.Market.Outlook.HistoryMonths),
Forecast = Forecast(w, g),
SellPlaces = available ? SellPlaces(w, g, company, stationLines) : [],
};
}
/// <summary>Ultimo giorno registrato nello storico: il sistema del mercato gira al primo tick del giorno.</summary>
public static long LastRecordedDay(World w) => w.Clock.TickOfDay == 0 ? w.Clock.Day - 1 : w.Clock.Day;
/// <summary>
/// Storico mensile: il prezzo dell'ultimo giorno di ciascuno degli ultimi mesi di calendario
/// conclusi più quello del giorno corrente, fino a <paramref name="months"/> campioni, dal più vecchio.
/// </summary>
public static List<PricePoint> MonthlyHistory(World w, int good, int months)
{
var history = w.Market.PriceHistory[good];
int dpm = w.Calendar.DaysPerMonth;
long last = LastRecordedDay(w);
var points = new List<PricePoint>(months);
for (int j = 0; j < months; j++)
{
long day = j == 0 ? last : last - last % dpm - 1 - (long)(j - 1) * dpm;
long k = last - day;
if (day < 0 || k >= history.Count) break;
points.Add(new PricePoint(day, history.Ago((int)k)));
}
points.Reverse();
return points;
}
/// <summary>Giorni effettivi della variazione: quelli chiesti o quelli presenti nello storico.</summary>
private static int ChangeSpan(RollingWindow history, int days) => Math.Min(days, history.Count - 1);
/// <summary>Variazione del prezzo globale negli ultimi <paramref name="days"/> giorni (frazione).</summary>
public static double Change(World w, int good, int days)
{
var history = w.Market.PriceHistory[good];
int k = ChangeSpan(history, days);
if (k <= 0) return 0;
double before = history.Ago(k);
return before > 0 ? history.Ago(0) / before - 1 : 0;
}
/// <summary>
/// Offerta e domanda della mappa in un mese (finestre di 30 giorni riportate ai giorni del mese)
/// e quota mondiale come in MarketSystem: V = max(baseline·giorni, quota·(D + S)/2) scambiato al
/// prezzo mondiale Pw, domanda V·(Pw/Pg)^ε e offerta V·(Pg/Pw)^ε.
/// </summary>
public static (double Supply, double Demand, double WorldSupply, double WorldDemand) MonthlyFlows(World w, int g)
{
var market = w.Market;
var m = w.Data.Balance.Market;
int count = market.Demand[g].Count;
if (count == 0) return (0, 0, 0, 0);
double perMonth = (double)w.Calendar.DaysPerMonth / count;
double d = market.Demand[g].Sum, s = market.Supply[g].Sum;
if (!IsAvailable(w, g)) return (s * perMonth, d * perMonth, 0, 0);
double pb = w.Data.Goods[g].BasePrice;
double pg = Math.Max(1e-9, market.GlobalPrice[g]);
double pw = pb * Math.Max(m.World.PriceFloor,
1 + Market.WorldFactor(m, w.Difficulty.MarketVolatilityMultiplier, w.Clock.YearsElapsed, market.Shock[g]));
double v = Math.Max(m.World.BaselinePerDay * count, m.World.VolumeShare * (d + s) / 2);
double worldDemand = v * DMath.Pow(pw / pg, m.World.Elasticity);
double worldSupply = v * DMath.Pow(pg / pw, m.World.Elasticity);
return (s * perMonth, d * perMonth, worldSupply * perMonth, worldDemand * perMonth);
}
/// <summary>Giacenze di un bene nei magazzini (input e output) delle industrie aperte e nelle stazioni.</summary>
public static double StockUnits(World w, int good)
{
long sum = 0;
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
int i = ind.InputIndexOf(good);
if (i >= 0) sum += ind.InputStock[i];
int o = ind.OutputIndexOf(good);
if (o >= 0) sum += ind.OutputStock[o];
}
foreach (var s in w.Network.Stations)
{
if (!w.Network.IsAlive(s)) continue;
foreach (var p in s.Waiting)
{
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
}
}
return sum;
}
/// <summary>Indice materie prime (media di Pg/Pb × 100 sui beni disponibili) e sua variazione.</summary>
public static (double Index, double Change) CommodityIndex(World w)
{
var data = w.Data;
int days = data.Balance.Market.Outlook.ChangeDays;
double now = 0, before = 0;
int n = 0;
for (int g = 0; g < data.GoodCount; g++)
{
if (!IsAvailable(w, g)) continue;
double pb = data.Goods[g].BasePrice;
var history = w.Market.PriceHistory[g];
int k = ChangeSpan(history, days);
now += w.Market.GlobalPrice[g] / pb;
before += (k > 0 ? history.Ago(k) : w.Market.GlobalPrice[g]) / pb;
n++;
}
if (n == 0) return (100, 0);
double index = now / n * 100, previous = before / n * 100;
return (index, previous > 0 ? index / previous - 1 : 0);
}
/// <summary>
/// Previsione a market.outlook.forecastMonths mesi dalla sola componente mondiale (ciclo e shock
/// che decade come in MarketSystem): Pf = Pg·(1 + W(t + Δ))/(1 + W(t)), entro i limiti del prezzo,
/// con una banda che si allarga di forecastBandPerMonth per mese.
/// </summary>
public static List<ForecastPoint> Forecast(World w, int g)
{
var m = w.Data.Balance.Market;
var o = m.Outlook;
var points = new List<ForecastPoint>(o.ForecastMonths);
double pb = w.Data.Goods[g].BasePrice;
double pg = w.Market.GlobalPrice[g];
double min = m.MinPriceFactor * pb, max = m.MaxPriceFactor * pb;
bool available = IsAvailable(w, g);
double volatility = w.Difficulty.MarketVolatilityMultiplier;
double years = w.Clock.YearsElapsed;
double shock = w.Market.Shock[g];
double w0 = Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years, shock));
for (int i = 1; i <= o.ForecastMonths; i++)
{
double days = (double)i * w.Calendar.DaysPerMonth;
double price = pg;
if (available)
{
double s = shock * DMath.Exp(-days / m.World.ShockDecayDays);
double wi = Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years + days / w.Calendar.DaysPerYear, s));
price = DMath.Clamp(pg * wi / w0, min, max);
}
double band = o.ForecastBandPerMonth * i;
points.Add(new ForecastPoint(i, price, DMath.Clamp(price * (1 - band), min, max), DMath.Clamp(price * (1 + band), min, max)));
}
return points;
}
/// <summary>
/// Per ogni stazione: la linea della compagnia (id più basso) con almeno un treno che vi fa
/// fermata, None altrimenti (stesso criterio di Tiers.ServedStations).
/// </summary>
public static LineId[] StationLines(World w, CompanyId company)
{
var result = new LineId[w.Network.Stations.Count];
Array.Fill(result, LineId.None);
if (!company.IsValid) return result;
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (t.Owner == company && t.Line.IsValid && !t.Removed) lineHasTrain[t.Line.Value] = true;
}
foreach (var l in w.Lines)
{
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
foreach (var stop in l.Stops)
{
int s = stop.Station.Value;
if (s >= 0 && s < result.Length && !result[s].IsValid) result[s] = l.Id;
}
}
return result;
}
/// <summary>Linea che collega un'industria o un hub: una stazione servita della compagnia con il bersaglio nel bacino.</summary>
private static LineId LineFor(World w, CompanyId company, LineId[] stationLines, Func<Station, bool> inCatchment)
{
var best = LineId.None;
foreach (var s in w.Network.Stations)
{
if (s.Owner != company || !w.Network.IsAlive(s)) continue;
var line = stationLines[s.Id.Value];
if (!line.IsValid || !inCatchment(s)) continue;
if (!best.IsValid || line.Value < best.Value) best = line;
}
return best;
}
public static LineId IndustryLine(World w, CompanyId company, LineId[] stationLines, IndustryId industry) =>
LineFor(w, company, stationLines, s => s.Industries.Contains(industry));
public static LineId HubLine(World w, CompanyId company, LineId[] stationLines, HubId hub) =>
LineFor(w, company, stationLines, s => s.Hubs.Contains(hub));
/// <summary>
/// Dove conviene vendere: industrie aperte (livello > 0) che consumano il bene, al prezzo locale
/// dell'ADR 0004 (Dl = consumo giornaliero a piena capacità × giorni di magazzino, Sl = giacenza
/// dell'input), e hub al prezzo d'esportazione; i primi market.outlook.sellPlaces per prezzo.
/// </summary>
public static List<SellPlace> SellPlaces(World w, int g, CompanyId company, LineId[] stationLines)
{
var lp = w.Data.Balance.LocalPrice;
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[g];
var candidates = new List<(SellPlaceKind Kind, int Target, double Price)>();
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0) continue;
int i = ind.InputIndexOf(g);
if (i < 0) continue;
double desired = IndustryMath.InputCapacity(ind, i, dpm);
candidates.Add((SellPlaceKind.Industry, ind.Id.Value, Market.LocalPrice(pg, desired, ind.InputStock[i], lp)));
}
foreach (var h in w.Hubs) candidates.Add((SellPlaceKind.Hub, h.Id.Value, h.BuyPrice(pg)));
// ordine stabile: prezzo decrescente, poi industrie prima degli hub, poi id
var top = candidates.OrderByDescending(c => c.Price).ThenBy(c => c.Kind).ThenBy(c => c.Target)
.Take(w.Data.Balance.Market.Outlook.SellPlaces).ToList();
var result = new List<SellPlace>(top.Count);
foreach (var c in top)
{
var line = c.Kind == SellPlaceKind.Industry
? IndustryLine(w, company, stationLines, new IndustryId(c.Target))
: HubLine(w, company, stationLines, new HubId(c.Target));
result.Add(new SellPlace(c.Kind, c.Target, c.Price, line));
}
return result;
}
public static List<HubOutlook> Hubs(World w, CompanyId company, LineId[] stationLines) =>
w.Hubs.Select(h => new HubOutlook(h.Id, h.Kind, h.MonthlyCapacity, h.Duty, h.UsedThisMonth, HubLine(w, company, stationLines, h.Id))).ToList();
/// <summary>
/// Evento di mercato in corso: lo shock mondiale più forte in valore assoluto tra i beni
/// disponibili, se supera market.outlook.eventThreshold, con i mesi stimati prima che il decadimento
/// esponenziale (shockDecayDays) lo porti sotto la soglia.
/// </summary>
public static MarketEvent StrongestEvent(World w)
{
var m = w.Data.Balance.Market;
int best = -1;
for (int g = 0; g < w.Data.GoodCount; g++)
{
if (!IsAvailable(w, g)) continue;
if (best < 0 || Math.Abs(w.Market.Shock[g]) > Math.Abs(w.Market.Shock[best])) best = g;
}
if (best < 0) return MarketEvent.None;
double shock = w.Market.Shock[best];
double threshold = m.Outlook.EventThreshold;
if (Math.Abs(shock) <= threshold) return MarketEvent.None;
double days = threshold > 0 ? m.World.ShockDecayDays * DMath.Log(Math.Abs(shock) / threshold) : 0;
return new MarketEvent(best, shock, days / w.Calendar.DaysPerMonth);
}
/// <summary>Avanzamento della compagnia verso il primo livello di tiers.json che sblocca il commercio.</summary>
public static TradingProgress Trading(World w, CompanyId company)
{
var tiers = w.Data.Tiers.Tiers;
var target = tiers.FirstOrDefault(t => t.Unlocks.Trading);
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
if (target is null || c is null)
{
return new TradingProgress
{
Unlocked = false, Level = target?.Level ?? 0, Fraction = 0, NetWorth = c?.NetWorth ?? Money.Zero, NetWorthRequired = Money.Zero,
TownsConnected = 0, TownsRequired = 0, TownPopulation = 0, Rating = c?.Rating ?? CreditRating.D,
RatingRequired = CreditRating.D, RatingMet = false,
};
}
var req = target.Requirements;
int towns = Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
bool unlocked = Tiers.Unlocks(w, c).Trading;
return new TradingProgress
{
Unlocked = unlocked,
Level = target.Level,
Fraction = unlocked ? 1 : Math.Min(worth, townsFraction),
NetWorth = c.NetWorth,
NetWorthRequired = new Money(req.NetWorth),
TownsConnected = towns,
TownsRequired = req.ConnectedTownsOver.Count,
TownPopulation = req.ConnectedTownsOver.Population,
Rating = c.Rating,
RatingRequired = req.CreditRating,
RatingMet = c.Rating <= req.CreditRating,
};
}
}
@@ -48,6 +48,29 @@ public sealed class RollingWindow
return _values[i];
}
/// <summary>Media degli ultimi n valori (o di quelli presenti, se sono meno).</summary>
public double AverageOfLast(int n)
{
int k = Math.Min(n, _count);
if (k <= 0) return 0;
double s = 0;
for (int i = 0; i < k; i++) s += Ago(i);
return s / k;
}
/// <summary>
/// Copia della finestra con una lunghezza maggiore: gli stessi valori, nello stesso ordine
/// (dal più vecchio), aggiunti uno per uno alla finestra nuova. Serve a migrare i salvataggi
/// quando i dati allungano la finestra (per esempio lo storico dei prezzi da 12 a 24 mesi).
/// </summary>
public RollingWindow Extended(int length)
{
if (length < _values.Length) throw new ArgumentOutOfRangeException(nameof(length), "la finestra non si accorcia");
var window = new RollingWindow(length);
for (int k = _count - 1; k >= 0; k--) window.Add(Ago(k));
return window;
}
internal void Save(Persistence.SaveWriter w)
{
w.Write(_values.Length);
@@ -571,6 +571,9 @@ public static class WorldSerializer
var sw = RollingWindow.Load(r);
var hw = RollingWindow.Load(r);
if (g < 0) continue;
// salvataggi con uno storico più corto dei dati (360 giorni fino alla F5): si allunga
// conservando i prezzi, senza cambiare il formato (ADR 0015)
if (hw.Length < m.PriceHistory[g].Length) hw = hw.Extended(m.PriceHistory[g].Length);
m.GlobalPrice[g] = price;
m.Shock[g] = shock;
m.DemandToday[g] = dt;
@@ -47,6 +47,9 @@ public sealed class ClientWorld(GameData data)
public Dictionary<int, IndustryCard> IndustryCards { get; } = [];
public Chronicle? Chronicle { get; private set; }
/// <summary>Quadro del mercato globale (F6), su richiesta.</summary>
public MarketReport? Market { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
@@ -127,6 +130,10 @@ public sealed class ClientWorld(GameData data)
Chronicle = m;
DetailVersion++;
return true;
case MarketReport m:
Market = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -146,6 +153,7 @@ public sealed class ClientWorld(GameData data)
CompanyCards.Clear();
IndustryCards.Clear();
Chronicle = null;
Market = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
+2
View File
@@ -37,6 +37,8 @@ public enum MessageId : ushort
IndustryCard = 127,
/// <summary>Cronaca finale della partita del giocatore (F5).</summary>
Chronicle = 128,
/// <summary>Quadro del mercato globale: beni, storico a 24 mesi, previsione, hub (F6).</summary>
MarketReport = 129,
CommandResult = 130,
Notification = 131,
Newspaper = 132,
@@ -237,6 +237,8 @@ public enum DetailKind : byte
Industry = 5,
/// <summary>Cronaca finale (risposta Chronicle, F5; Id ignorato).</summary>
Chronicle = 6,
/// <summary>Quadro del mercato globale (risposta MarketReport, F6; Id ignorato).</summary>
Market = 7,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,210 @@
using RailEnterprise.Core.Common;
namespace RailEnterprise.Protocol.Messages;
// Messaggi della fase F6: pannello «Mercato globale» (immagine di riferimento 06). Il quadro del
// mercato arriva su richiesta (RequestDetail con DetailKind.Market) ed è calcolato dal server con
// MarketOutlook (ADR 0015): il client lo mostra com'è, senza logica di gioco.
/// <summary>Prezzo globale di un giorno (centesimi per unità).</summary>
public sealed class PricePointInfo
{
public long Day { get; init; }
public double Price { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.F64(Price);
w.Flags(0);
}
public static PricePointInfo Read(ref SpanReader r)
{
var m = new PricePointInfo { Day = r.I64(), Price = r.F64() };
r.Flags();
return m;
}
}
/// <summary>Prezzo previsto a una distanza in mesi, con la banda bassa e alta (centesimi).</summary>
public sealed class ForecastInfo
{
public byte Months { get; init; }
public double Price { get; init; }
public double Low { get; init; }
public double High { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Months); w.F64(Price); w.F64(Low); w.F64(High);
w.Flags(0);
}
public static ForecastInfo Read(ref SpanReader r)
{
var m = new ForecastInfo { Months = r.U8(), Price = r.F64(), Low = r.F64(), High = r.F64() };
r.Flags();
return m;
}
}
/// <summary>Destinazione di vendita: Kind 0 industria, 1 hub; Line −1 se la compagnia non la collega.</summary>
public sealed class SellPlaceInfo
{
public const byte Industry = 0;
public const byte Hub = 1;
public byte Kind { get; init; }
public int Target { get; init; }
public double Price { get; init; }
public int Line { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.I32(Target); w.F64(Price); w.I32(Line);
w.Flags(0);
}
public static SellPlaceInfo Read(ref SpanReader r)
{
var m = new SellPlaceInfo { Kind = r.U8(), Target = r.I32(), Price = r.F64(), Line = r.I32() };
r.Flags();
return m;
}
}
/// <summary>Quadro di un bene: prezzo, variazione, offerta e domanda, scorte, storico, previsione, vendite.</summary>
public sealed class GoodMarketInfo
{
public int Good { get; init; }
public bool Available { get; init; }
public double Price { get; init; }
/// <summary>Variazione a 30 giorni (frazione).</summary>
public float Change { get; init; }
/// <summary>Offerta e domanda della mappa in un mese (unità).</summary>
public double SupplyMonth { get; init; }
public double DemandMonth { get; init; }
/// <summary>Quota mondiale scambiata dagli hub in un mese (unità).</summary>
public double WorldSupplyMonth { get; init; }
public double WorldDemandMonth { get; init; }
public double StockUnits { get; init; }
/// <summary>Scorte in mesi di domanda della mappa (−1 senza domanda).</summary>
public float StockMonths { get; init; } = -1;
public List<PricePointInfo> History { get; init; } = [];
public List<ForecastInfo> Forecast { get; init; } = [];
public List<SellPlaceInfo> SellPlaces { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Good); w.Bool(Available); w.F64(Price); w.F32(Change);
w.F64(SupplyMonth); w.F64(DemandMonth); w.F64(WorldSupplyMonth); w.F64(WorldDemandMonth); w.F64(StockUnits); w.F32(StockMonths);
w.Count(History.Count);
foreach (var p in History) p.Write(ref w);
w.Count(Forecast.Count);
foreach (var f in Forecast) f.Write(ref w);
w.Count(SellPlaces.Count);
foreach (var s in SellPlaces) s.Write(ref w);
w.Flags(0);
}
public static GoodMarketInfo Read(ref SpanReader r)
{
var m = new GoodMarketInfo
{
Good = r.I32(), Available = r.Bool(), Price = r.F64(), Change = r.F32(),
SupplyMonth = r.F64(), DemandMonth = r.F64(), WorldSupplyMonth = r.F64(), WorldDemandMonth = r.F64(), StockUnits = r.F64(), StockMonths = r.F32(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.History.Add(PricePointInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Forecast.Add(ForecastInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.SellPlaces.Add(SellPlaceInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Hub verso il mercato mondiale: Kind 0 porto, 1 valico; Line −1 se la compagnia non lo collega.</summary>
public sealed class HubMarketInfo
{
public int Hub { get; init; }
public byte Kind { get; init; }
public int MonthlyCapacity { get; init; }
public float Duty { get; init; }
public int UsedThisMonth { get; init; }
public int Line { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Hub); w.U8(Kind); w.I32(MonthlyCapacity); w.F32(Duty); w.I32(UsedThisMonth); w.I32(Line);
w.Flags(0);
}
public static HubMarketInfo Read(ref SpanReader r)
{
var m = new HubMarketInfo { Hub = r.I32(), Kind = r.U8(), MonthlyCapacity = r.I32(), Duty = r.F32(), UsedThisMonth = r.I32(), Line = r.I32() };
r.Flags();
return m;
}
}
/// <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.
/// </summary>
public sealed class MarketReport : IMessage
{
public MessageId Id => MessageId.MarketReport;
public long Day { get; init; }
/// <summary>Indice materie prime (100 = prezzi base) e variazione a 30 giorni (frazione).</summary>
public float Index { get; init; }
public float IndexChange { get; init; }
public List<GoodMarketInfo> Goods { get; init; } = [];
public List<HubMarketInfo> Hubs { get; init; } = [];
/// <summary>Evento in corso: bene (−1 nessuno), shock mondiale con segno (frazione del prezzo base), mesi stimati.</summary>
public int EventGood { get; init; } = -1;
public float EventShock { get; init; }
public float EventMonths { get; init; }
/// <summary>Compravendita in proprio: sbloccata, livello che la sblocca, avanzamento 0–1 e requisiti.</summary>
public bool TradingUnlocked { get; init; }
public byte TradingTier { get; init; }
public float TradingProgress { get; init; }
public Money NetWorth { get; init; }
public Money NetWorthRequired { get; init; }
public int TownsConnected { get; init; }
public int TownsRequired { get; init; }
public int TownPopulation { get; init; }
public string Rating { get; init; } = "";
public string RatingRequired { get; init; } = "";
public bool RatingMet { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.F32(Index); w.F32(IndexChange);
w.Count(Goods.Count);
foreach (var g in Goods) g.Write(ref w);
w.Count(Hubs.Count);
foreach (var h in Hubs) h.Write(ref w);
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(0);
}
public static MarketReport Read(ref SpanReader r)
{
long day = r.I64();
float index = r.F32(), change = r.F32();
var goods = new List<GoodMarketInfo>();
for (int n = r.Count(), i = 0; i < n; i++) goods.Add(GoodMarketInfo.Read(ref r));
var hubs = new List<HubMarketInfo>();
for (int n = r.Count(), i = 0; i < n; i++) hubs.Add(HubMarketInfo.Read(ref r));
var m = new MarketReport
{
Day = day, Index = index, IndexChange = change, Goods = goods, Hubs = hubs,
EventGood = r.I32(), EventShock = r.F32(), EventMonths = r.F32(),
TradingUnlocked = r.Bool(), TradingTier = r.U8(), TradingProgress = r.F32(), NetWorth = r.Money(), NetWorthRequired = r.Money(),
TownsConnected = r.I32(), TownsRequired = r.I32(), TownPopulation = r.I32(), Rating = r.String(), RatingRequired = r.String(), RatingMet = r.Bool(),
};
r.Flags();
return m;
}
}
@@ -31,6 +31,7 @@ public static class MessageCodec
MessageId.CompanyCard => CompanyCard.Read(ref r),
MessageId.IndustryCard => IndustryCard.Read(ref r),
MessageId.Chronicle => Chronicle.Read(ref r),
MessageId.MarketReport => MarketReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
+3
View File
@@ -658,6 +658,9 @@ public sealed class GameHost : IDisposable
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
break;
case DetailKind.Market:
s.Send(Projection.Market(w, s.Company));
break;
}
}
+31
View File
@@ -518,4 +518,35 @@ public static class Projection
Highlights = report.Highlights,
};
}
/// <summary>Quadro del mercato globale per la compagnia della sessione (MarketOutlook, ADR 0015).</summary>
public static MarketReport Market(World w, CompanyId company)
{
var report = MarketOutlook.Build(w, company);
var trading = report.Trading;
return new MarketReport
{
Day = report.Day,
Index = (float)report.Index,
IndexChange = (float)report.IndexChange,
Goods = report.Goods.Select(g => new GoodMarketInfo
{
Good = g.Good, Available = g.Available, Price = g.Price, Change = (float)g.Change,
SupplyMonth = g.SupplyMonth, DemandMonth = g.DemandMonth, WorldSupplyMonth = g.WorldSupplyMonth, WorldDemandMonth = g.WorldDemandMonth,
StockUnits = g.StockUnits, StockMonths = (float)g.StockMonths,
History = g.History.Select(p => new PricePointInfo { Day = p.Day, Price = p.Price }).ToList(),
Forecast = g.Forecast.Select(f => new ForecastInfo { Months = (byte)f.Months, Price = f.Price, Low = f.Low, High = f.High }).ToList(),
SellPlaces = g.SellPlaces.Select(p => new SellPlaceInfo { Kind = (byte)p.Kind, Target = p.Target, Price = p.Price, Line = p.Line.Value }).ToList(),
}).ToList(),
Hubs = report.Hubs.Select(h => new HubMarketInfo
{
Hub = h.Hub.Value, Kind = (byte)h.Kind, MonthlyCapacity = h.MonthlyCapacity, Duty = (float)h.Duty, UsedThisMonth = h.UsedThisMonth, Line = h.Line.Value,
}).ToList(),
EventGood = report.Event.Good, EventShock = (float)report.Event.Shock, EventMonths = (float)report.Event.Months,
TradingUnlocked = trading.Unlocked, TradingTier = (byte)trading.Level, TradingProgress = (float)trading.Fraction,
NetWorth = trading.NetWorth, NetWorthRequired = trading.NetWorthRequired, TownsConnected = trading.TownsConnected,
TownsRequired = trading.TownsRequired, TownPopulation = trading.TownPopulation, Rating = trading.Rating.ToString(),
RatingRequired = trading.RatingRequired.ToString(), RatingMet = trading.RatingMet,
};
}
}
@@ -83,7 +83,7 @@ public sealed class SimulateCommand : IToolCommand
for (int g = 0; g < data.GoodCount; g++)
{
var def = data.Goods[g];
double price = w.Market.PriceHistory[g].Average / 100.0;
double price = w.Market.PriceHistory[g].AverageOfLast(w.Calendar.DaysPerYear) / 100.0;
long produced = w.Goods.Produced[g] - lastProduced[g];
long consumed = w.Goods.Consumed[g] - lastConsumed[g];
string note = def.Era > year ? "non ancora disponibile" : "";