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

@@ -442,3 +442,78 @@ ultimi,,last
vincitore,,winner
"volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.",,"times annual profit, divided by the shares and multiplied by market sentiment."
⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto.,,⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
30 giorni,,30 days
Avanzamento verso,,Progress towards
Capacità,,Capacity
Capacità usata questo mese,,Capacity used this month
Città collegate oltre,,Connected towns over
Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello,,Buy goods at the source and resell them where the price is highest. Unlocked at level
Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello,,Buy goods at the source and resell them where the price is highest. Unlocks at level
Compravendita in proprio,,Own-account trading
Consumi della mappa,,Map consumption
Dazio,,Duty
Disponibile dal,,Available from
Domanda globale,,Global demand
Dove conviene vendere,,Where to sell
Evento in corso,,Current event
Hub verso il mercato mondiale via mare,,Hub to the world market by sea
Hub verso il mercato mondiale via terra,,Hub to the world market by land
"I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse.",,"World prices follow their multi-year cycle, with no shocks."
Il prezzo mondiale di,,The world price of
In attesa dei prezzi dal server…,,Waiting for prices from the server…
Indice materie prime,,Commodity index
Lo storico si forma giorno dopo giorno,,The history builds up day by day
"Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.",,"Average of the global prices of the available goods relative to their base price (100 = base prices), with the change over the last 30 days."
Mercato globale,,Global market
Merce,,Goods
Nessun evento in corso,,No current event
Nessuna industria consuma questa merce e nessun hub la compra.,,No industry consumes these goods and no hub buys them.
Non ancora disponibili,,Not yet available
Offerta,,Supply
Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub.,,Supply and demand add the map's production and consumption to the share of the world market traded through the hubs.
Offerta globale,,Global supply
Offerta · domanda,,Supply · demand
Pianifica la linea,,Plan the line
Porta i binari fino al confine per comprare e vendere via terra.,,Lay track to the border to buy and sell by land.
Porta i binari fino al porto per comprare e vendere via mare.,,Lay track to the port to buy and sell by sea.
"Prezzi alla destinazione: le industrie pagano il prezzo locale (più alto se il magazzino è vuoto), gli hub il prezzo mondiale meno il dazio. Il trasporto è a parte.",,"Prices at the destination: industries pay the local price (higher when their storage is empty), hubs the world price minus duty. Transport is extra."
Prezzi mondiali al,,World prices as of
Prezzo,,Price
"Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.",,"Global price at the end of each month; the dashed line is the forecast from the world component (cycle and fading shocks), the blue band its uncertainty."
Produzione della mappa,,Map production
Scegli una merce a sinistra,,Pick goods on the left
Servito da,,Served by
Torna alla mappa,,Back to the map
aggiornati ogni giorno di gioco,,updated every game day
ago,,Aug
apr,,Apr
collegato,,connected
dic,,Dec
domanda,,demand
esportazione,,export
feb,,Feb
gen,,Jan
giu,,Jun
in 30 giorni,,in 30 days
lug,,Jul
mag,,May
mar,,Mar
mese,,month
mesi e previsione a,,months and forecast for
"nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa",,"in industry storage and at stations, divided by the map's monthly demand"
nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino,,none of your stations served by a line with trains has this destination in its catchment
non collegato,,not connected
nov,,Nov
oggi,,today
ott,,Oct
prev.,,fcst.
prezzo mondiale in calo,,world price falling
prezzo mondiale in rialzo,,world price rising
quota mondiale dagli hub,,world share through the hubs
rispetto al ciclo per circa,,compared with the cycle for about
serve,,needs
servita dalla tua linea,,served by your line
set,,Sep
unità/mese,,units/month
è più alto del,,is higher by
è più basso del,,is lower by
1 keys it en
442 vincitore winner
443 volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato. times annual profit, divided by the shares and multiplied by market sentiment.
444 ⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto. ⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
445 30 giorni 30 days
446 Avanzamento verso Progress towards
447 Capacità Capacity
448 Capacità usata questo mese Capacity used this month
449 Città collegate oltre Connected towns over
450 Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello Buy goods at the source and resell them where the price is highest. Unlocked at level
451 Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello Buy goods at the source and resell them where the price is highest. Unlocks at level
452 Compravendita in proprio Own-account trading
453 Consumi della mappa Map consumption
454 Dazio Duty
455 Disponibile dal Available from
456 Domanda globale Global demand
457 Dove conviene vendere Where to sell
458 Evento in corso Current event
459 Hub verso il mercato mondiale via mare Hub to the world market by sea
460 Hub verso il mercato mondiale via terra Hub to the world market by land
461 I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse. World prices follow their multi-year cycle, with no shocks.
462 Il prezzo mondiale di The world price of
463 In attesa dei prezzi dal server… Waiting for prices from the server…
464 Indice materie prime Commodity index
465 Lo storico si forma giorno dopo giorno The history builds up day by day
466 Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni. Average of the global prices of the available goods relative to their base price (100 = base prices), with the change over the last 30 days.
467 Mercato globale Global market
468 Merce Goods
469 Nessun evento in corso No current event
470 Nessuna industria consuma questa merce e nessun hub la compra. No industry consumes these goods and no hub buys them.
471 Non ancora disponibili Not yet available
472 Offerta Supply
473 Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub. Supply and demand add the map's production and consumption to the share of the world market traded through the hubs.
474 Offerta globale Global supply
475 Offerta · domanda Supply · demand
476 Pianifica la linea Plan the line
477 Porta i binari fino al confine per comprare e vendere via terra. Lay track to the border to buy and sell by land.
478 Porta i binari fino al porto per comprare e vendere via mare. Lay track to the port to buy and sell by sea.
479 Prezzi alla destinazione: le industrie pagano il prezzo locale (più alto se il magazzino è vuoto), gli hub il prezzo mondiale meno il dazio. Il trasporto è a parte. Prices at the destination: industries pay the local price (higher when their storage is empty), hubs the world price minus duty. Transport is extra.
480 Prezzi mondiali al World prices as of
481 Prezzo Price
482 Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza. Global price at the end of each month; the dashed line is the forecast from the world component (cycle and fading shocks), the blue band its uncertainty.
483 Produzione della mappa Map production
484 Scegli una merce a sinistra Pick goods on the left
485 Servito da Served by
486 Torna alla mappa Back to the map
487 aggiornati ogni giorno di gioco updated every game day
488 ago Aug
489 apr Apr
490 collegato connected
491 dic Dec
492 domanda demand
493 esportazione export
494 feb Feb
495 gen Jan
496 giu Jun
497 in 30 giorni in 30 days
498 lug Jul
499 mag May
500 mar Mar
501 mese month
502 mesi e previsione a months and forecast for
503 nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa in industry storage and at stations, divided by the map's monthly demand
504 nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino none of your stations served by a line with trains has this destination in its catchment
505 non collegato not connected
506 nov Nov
507 oggi today
508 ott Oct
509 prev. fcst.
510 prezzo mondiale in calo world price falling
511 prezzo mondiale in rialzo world price rising
512 quota mondiale dagli hub world share through the hubs
513 rispetto al ciclo per circa compared with the cycle for about
514 serve needs
515 servita dalla tua linea served by your line
516 set Sep
517 unità/mese units/month
518 è più alto del is higher by
519 è più basso del is lower by
@@ -235,6 +235,11 @@ public partial class AutoPilot : Node
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
await Shot("14_compagnia_giocatore", 40);
// Mercato globale (immagine 06): storico, previsione, hub ed evento in corso
_game.OpenMarket();
await Until(() => World.Market is not null, "quadro del mercato", 30);
await Shot("16_mercato", 40);
// Cronaca provvisoria
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
@@ -0,0 +1,542 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// «Mercato globale» a tutto schermo (immagine di riferimento 06): a sinistra i beni con prezzo,
/// variazione a 30 giorni e barre di offerta e domanda; al centro il bene scelto con lo storico a
/// 24 mesi, la previsione, offerta, domanda, scorte e «Dove conviene vendere»; a destra gli hub,
/// l'evento di mercato in corso e l'avanzamento verso la compravendita in proprio. Tutti i numeri
/// arrivano dal server (MarketReport, ADR 0015): il pannello li chiede all'apertura e a ogni nuovo
/// giorno e li mostra com'è.
/// </summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _index = UiTheme.Text("", 22, bold: true);
private readonly Label _indexChange = UiTheme.Text("", 16, bold: true);
private readonly VBoxContainer _rows = PanelKit.Column(2);
private readonly Label _later = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _goodTitle = UiTheme.TitleLabel("", 40);
private readonly Label _goodCaption = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _goodPrice = UiTheme.Text("", 26, bold: true);
private readonly Label _goodChange = UiTheme.Text("", 14, bold: true);
private readonly SeriesChart _chart = new(250);
private readonly HBoxContainer _stats = PanelKit.Row(10);
private readonly VBoxContainer _sell = PanelKit.Column(4);
private readonly VBoxContainer _right = PanelKit.Column(14);
private readonly Dictionary<int, GoodRow> _rowByGood = [];
private MarketReport? _shown;
private string _rowsKey = "";
private int _selected = -1;
private long _requestedDay = long.MinValue;
private double _sinceRequest = double.MaxValue;
public event Action? CloseRequested;
/// <summary>Chiesto di pianificare una linea verso un hub (strumento binari centrato sull'hub).</summary>
public event Action<int>? PlanLineRequested;
public MarketPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
var header = PanelKit.Row(16);
var titles = PanelKit.Column(0);
titles.AddChild(UiTheme.TitleLabel(T("Mercato globale"), 40));
titles.AddChild(_subtitle);
header.AddChild(titles);
var index = PanelKit.Column(0);
index.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
index.SizeFlagsVertical = SizeFlags.ShrinkCenter;
var indexCaption = UiTheme.Text(T("Indice materie prime"), 13, Palette.TextSecondary);
indexCaption.HorizontalAlignment = HorizontalAlignment.Right;
index.AddChild(indexCaption);
var indexRow = new HBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
indexRow.AddThemeConstantOverride("separation", 8);
indexRow.AddChild(_index);
indexRow.AddChild(_indexChange);
index.AddChild(indexRow);
index.TooltipText = T("Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.");
index.MouseFilter = MouseFilterEnum.Pass;
header.AddChild(index);
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(150, 44) };
close.Pressed += () => CloseRequested?.Invoke();
header.AddChild(close);
AddChild(header);
var body = PanelKit.Row(16);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
AddChild(body);
var left = Column(body, 1.05f);
left.AddChild(TableHeader());
left.AddChild(PanelKit.Separator());
left.AddChild(_rows);
_later.AutowrapMode = TextServer.AutowrapMode.WordSmart;
left.AddChild(_later);
left.AddChild(Wrapped(T("Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub."), 12, Palette.TextSecondary));
var center = Column(body, 1.35f);
var top = PanelKit.Row(12);
var names = PanelKit.Column(0);
names.SizeFlagsHorizontal = SizeFlags.ExpandFill;
names.AddChild(_goodTitle);
names.AddChild(_goodCaption);
top.AddChild(names);
var price = PanelKit.Column(0);
price.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
_goodPrice.HorizontalAlignment = HorizontalAlignment.Right;
_goodChange.HorizontalAlignment = HorizontalAlignment.Right;
price.AddChild(_goodPrice);
price.AddChild(_goodChange);
top.AddChild(price);
center.AddChild(top);
center.AddChild(_chart);
center.AddChild(_stats);
center.AddChild(UiTheme.Text(T("Dove conviene vendere"), 16, bold: true));
center.AddChild(_sell);
var right = Column(body, 0.8f);
right.AddChild(_right);
_subtitle.Text = T("In attesa dei prezzi dal server…");
}
/// <summary>Bene mostrato al centro (−1 se nessuno).</summary>
public int Selected => _selected;
public void Select(int good)
{
_selected = good;
foreach (var (id, row) in _rowByGood) row.SetSelected(id == good);
if (_session.World.Market is { } report) ShowGood(_session.World, report);
}
private static VBoxContainer Column(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 18));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
scroll.AddChild(margin);
var col = PanelKit.Column(12);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
public override void _Process(double delta)
{
var w = _session.World;
_sinceRequest += delta;
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
long today = Fmt.Today(w);
if (today != _requestedDay || (w.Market is null && _sinceRequest > 5))
{
_requestedDay = today;
_sinceRequest = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Market, Target = 0 });
}
if (w.Market is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
}
private void Refresh(ClientWorld w, MarketReport report)
{
_shown = report;
_subtitle.Text = $"{T("Prezzi mondiali al")} {Fmt.Date(w, report.Day)}, {T("aggiornati ogni giorno di gioco")}";
_index.Text = Fmt.Number(report.Index, 1);
SetChange(_indexChange, report.IndexChange, "");
RefreshRows(w, report);
if (_selected < 0 || report.Goods.All(g => g.Good != _selected))
_selected = report.Goods.Where(g => g.Available).Select(g => g.Good).DefaultIfEmpty(0).First();
foreach (var (id, row) in _rowByGood) row.SetSelected(id == _selected);
ShowGood(w, report);
RefreshRight(w, report);
}
// ------------------------------------------------------------------ dati di comodo (solo lettura)
private static string GoodName(ClientWorld w, int good)
{
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
private static string Unit(ClientWorld w, int good) => w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)].Unit;
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
private static string PerUnit(ClientWorld w, int good, double cents) => $"{Price(cents)} / {Unit(w, good)}";
/// <summary>Quantità intera con il punto delle migliaia («41.200»).</summary>
private static string Quantity(double units) => Fmt.Number(Math.Round(units), 0);
private static string LineName(ClientWorld w, int line) =>
w.Lines.TryGetValue(line, out var l) ? l.Name : $"{T("Linea")} {line + 1}";
/// <summary>Variazione con la freccia: ambra in salita, azzurro in discesa (immagine 06).</summary>
private static void SetChange(Label label, double change, string suffix)
{
bool up = change > 0.0005, down = change < -0.0005;
string arrow = up ? "▲ " : down ? "▼ " : "= ";
label.Text = arrow + Fmt.Pct(Math.Abs(change)) + suffix;
label.AddThemeColorOverride("font_color", up ? Palette.AmberLight : down ? Palette.Staff : Palette.TextSecondary);
}
// ------------------------------------------------------------------ elenco dei beni
private const float WPrice = 96, WChange = 86, WBars = 110;
private static Control TableHeader()
{
var row = PanelKit.Row(8);
var name = UiTheme.Text(T("Merce"), 13, Palette.TextSecondary);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
row.AddChild(name);
foreach (var (text, width) in new[] { (T("Prezzo"), WPrice), (T("30 giorni"), WChange), (T("Offerta · domanda"), WBars) })
{
var l = UiTheme.Text(text, 13, Palette.TextSecondary);
l.CustomMinimumSize = new Vector2(width, 0);
row.AddChild(l);
}
return row;
}
private void RefreshRows(ClientWorld w, MarketReport report)
{
var available = report.Goods.Where(g => g.Available).ToList();
string key = string.Join(",", available.Select(g => g.Good));
if (key != _rowsKey)
{
_rowsKey = key;
foreach (var c in _rows.GetChildren()) c.QueueFree();
_rowByGood.Clear();
foreach (var g in available)
{
int id = g.Good;
var row = new GoodRow();
row.Pressed += () => Select(id);
_rowByGood[id] = row;
_rows.AddChild(row);
}
}
foreach (var g in available)
{
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
_rowByGood[g.Good].Update(GoodName(w, g.Good), PerUnit(w, g.Good, g.Price), g.Change, supply, demand,
$"{GoodName(w, g.Good)}\n{T("Offerta")} {Quantity(supply)} {Unit(w, g.Good)}/{T("mese")} · {T("domanda")} {Quantity(demand)} {Unit(w, g.Good)}/{T("mese")}");
}
var later = report.Goods.Where(g => !g.Available).Select(g => $"{GoodName(w, g.Good)} ({w.Data.Goods[g.Good].Era})").ToList();
_later.Text = later.Count > 0 ? $"{T("Non ancora disponibili")}: {string.Join(", ", later)}" : "";
_later.Visible = later.Count > 0;
}
/// <summary>Riga di un bene: pulsante piatto con nome, prezzo, variazione e barre di offerta e domanda.</summary>
private sealed partial class GoodRow : Button
{
private readonly Label _name = UiTheme.Text("", 16, bold: true);
private readonly Label _price = UiTheme.Text("", 15);
private readonly Label _change = UiTheme.Text("", 14, bold: true);
private readonly SupplyDemandBars _bars = new();
public GoodRow()
{
CustomMinimumSize = new Vector2(0, 58);
FocusMode = FocusModeEnum.None;
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
SetSelected(false);
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
row.AddThemeConstantOverride("separation", 8);
row.SetAnchorsPreset(LayoutPreset.FullRect);
row.OffsetLeft = 12;
row.OffsetRight = -8;
AddChild(row);
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_name.ClipText = true;
_name.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
_name.CustomMinimumSize = new Vector2(24, 0);
foreach (var (l, width) in new[] { (_name, 0f), (_price, WPrice), (_change, WChange) })
{
if (width > 0) l.CustomMinimumSize = new Vector2(width, 0);
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
l.MouseFilter = MouseFilterEnum.Ignore;
row.AddChild(l);
}
_bars.CustomMinimumSize = new Vector2(WBars, 22);
_bars.SizeFlagsVertical = SizeFlags.ShrinkCenter;
row.AddChild(_bars);
}
public void SetSelected(bool on) =>
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
public void Update(string name, string price, double change, double supply, double demand, string tooltip)
{
_name.Text = name;
_price.Text = price;
SetChange(_change, change, "");
_bars.Set(supply, demand);
TooltipText = tooltip;
}
}
/// <summary>Due barre sovrapposte: offerta in azzurro, domanda in ambra, riferite alla maggiore delle due.</summary>
private sealed partial class SupplyDemandBars : Control
{
private double _supply, _demand;
public SupplyDemandBars() => MouseFilter = MouseFilterEnum.Ignore;
public void Set(double supply, double demand)
{
_supply = supply;
_demand = demand;
QueueRedraw();
}
public override void _Draw()
{
double top = Math.Max(1e-9, Math.Max(_supply, _demand) * 1.2);
float h = 6, gap = 5;
float y0 = (Size.Y - 2 * h - gap) / 2;
for (int i = 0; i < 2; i++)
{
var y = y0 + i * (h + gap);
double v = i == 0 ? _supply : _demand;
DrawRect(new Rect2(0, y, Size.X, h), Palette.Inner);
DrawRect(new Rect2(0, y, (float)(Size.X * Math.Clamp(v / top, 0, 1)), h), i == 0 ? Palette.Staff : Palette.Amber);
}
}
}
// ------------------------------------------------------------------ bene scelto
private void ShowGood(ClientWorld w, MarketReport report)
{
var g = report.Goods.FirstOrDefault(x => x.Good == _selected);
foreach (var c in _stats.GetChildren()) c.QueueFree();
foreach (var c in _sell.GetChildren()) c.QueueFree();
if (g is null)
{
_goodTitle.Text = "";
_goodCaption.Text = "";
_goodPrice.Text = "";
_goodChange.Text = "";
_chart.Show([], [], Price, SeriesChart.Style.Line, Palette.Amber, T("Scegli una merce a sinistra"));
return;
}
_goodTitle.Text = GoodName(w, g.Good);
int months = g.History.Count;
_goodCaption.Text = g.Forecast.Count > 0
? $"{T("Storico")} {months} {T("mesi e previsione a")} {g.Forecast.Count} {T("mesi")}"
: $"{T("Storico")} {months} {T("mesi")}";
_goodPrice.Text = PerUnit(w, g.Good, g.Price);
SetChange(_goodChange, g.Change, " " + T("in 30 giorni"));
var labels = g.History.Select((p, i) => i == g.History.Count - 1 ? "" : MonthLabel(w, p.Day)).ToList();
_chart.ShowWithForecast(g.History.Select(p => p.Price).ToList(), labels,
g.Forecast.Select(f => f.Price).ToList(), g.Forecast.Select(f => f.Low).ToList(), g.Forecast.Select(f => f.High).ToList(),
Price, Palette.Amber, T("Lo storico si forma giorno dopo giorno"), T("oggi"), g.Forecast.Count > 0 ? T("prev.") : "");
_chart.TooltipText = T("Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.");
_chart.MouseFilter = MouseFilterEnum.Pass;
string unit = Unit(w, g.Good);
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
AddStat(T("Offerta globale"), $"{Quantity(supply)} {unit}/{T("mese")}",
$"{T("Produzione della mappa")} {Quantity(g.SupplyMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldSupplyMonth)} {unit}");
AddStat(T("Domanda globale"), $"{Quantity(demand)} {unit}/{T("mese")}",
$"{T("Consumi della mappa")} {Quantity(g.DemandMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldDemandMonth)} {unit}");
AddStat(T("Scorte"), g.StockMonths < 0 ? "—" : $"{Fmt.Number(g.StockMonths, 1)} {T("mesi")}",
$"{Quantity(g.StockUnits)} {unit} {T("nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa")}");
if (!g.Available)
{
_sell.AddChild(Wrapped($"{T("Disponibile dal")} {w.Data.Goods[g.Good].Era}.", 13, Palette.TextSecondary));
return;
}
if (g.SellPlaces.Count == 0)
{
_sell.AddChild(Wrapped(T("Nessuna industria consuma questa merce e nessun hub la compra."), 13, Palette.TextSecondary));
return;
}
for (int i = 0; i < g.SellPlaces.Count; i++) _sell.AddChild(SellRow(w, g, g.SellPlaces[i], i == 0));
_sell.AddChild(Wrapped(T("Prezzi alla destinazione: le industrie pagano il prezzo locale (più alto se il magazzino è vuoto), gli hub il prezzo mondiale meno il dazio. Il trasporto è a parte."), 12, Palette.TextSecondary));
}
private static string MonthLabel(ClientWorld w, long day)
{
if (w.Calendar is not { } c) return "";
var date = c.DateOfDay(Math.Max(0, day));
string[] months = [T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
return $"{months[Math.Clamp(date.Month, 1, 12) - 1]} {date.Year}";
}
private void AddStat(string caption, string value, string tooltip)
{
var stat = PanelKit.Stat(caption, PanelKit.Value(value));
stat.TooltipText = tooltip;
stat.MouseFilter = MouseFilterEnum.Pass;
_stats.AddChild(stat);
}
private static Control SellRow(ClientWorld w, GoodMarketInfo g, SellPlaceInfo p, bool best)
{
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", best ? UiTheme.Box(Palette.Inner, Palette.Inner, 6, 12) : UiTheme.Box(Palette.Panel, Palette.Panel, 6, 12));
var row = PanelKit.Row(10);
box.AddChild(row);
string name = p.Kind == SellPlaceInfo.Hub
? $"{(w.Hubs.TryGetValue(p.Target, out var hub) ? hub.Name : "#" + p.Target)}, {T("esportazione")}"
: w.Industries.TryGetValue(p.Target, out var ind) ? ind.Name : "#" + p.Target;
var label = UiTheme.Text(name, 14);
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
label.ClipText = true;
label.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
label.CustomMinimumSize = new Vector2(24, 0);
row.AddChild(label);
var price = UiTheme.Text(PerUnit(w, g.Good, p.Price), 14, bold: true);
price.CustomMinimumSize = new Vector2(110, 0);
row.AddChild(price);
var line = UiTheme.Text(p.Line >= 0 ? LineName(w, p.Line) : T("non collegato"), 14, p.Line >= 0 ? Palette.TextSecondary : Palette.Amber);
line.CustomMinimumSize = new Vector2(130, 0);
line.ClipText = true;
line.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
row.AddChild(line);
box.TooltipText = p.Line >= 0
? $"{name}: {T("servita dalla tua linea")} {LineName(w, p.Line)}"
: $"{name}: {T("nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino")}";
return box;
}
// ------------------------------------------------------------------ colonna destra
private void RefreshRight(ClientWorld w, MarketReport report)
{
foreach (var c in _right.GetChildren()) c.QueueFree();
foreach (var h in report.Hubs) _right.AddChild(HubCard(w, h));
_right.AddChild(EventCard(w, report));
_right.AddChild(TradingCard(w, report));
}
private Control HubCard(ClientWorld w, HubMarketInfo h)
{
var card = Card(Palette.Inner, Palette.Border);
var col = (VBoxContainer)card.GetChild(0);
var title = PanelKit.Row(8);
var name = UiTheme.Text(w.Hubs.TryGetValue(h.Hub, out var info) ? info.Name : $"Hub {h.Hub}", 17, bold: true);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
name.AutowrapMode = TextServer.AutowrapMode.WordSmart;
title.AddChild(name);
bool connected = h.Line >= 0;
title.AddChild(UiTheme.Text(connected ? T("collegato") : T("non collegato"), 13, connected ? Palette.Ok : Palette.Amber));
col.AddChild(title);
bool port = h.Kind == 0;
col.AddChild(Wrapped(port ? T("Hub verso il mercato mondiale via mare") : T("Hub verso il mercato mondiale via terra"), 13, Palette.TextSecondary));
col.AddChild(PanelKit.Pair(T("Capacità"), PanelKit.Value($"{Fmt.Number(h.MonthlyCapacity, 0)} {T("unità/mese")}")));
col.AddChild(PanelKit.Pair(T("Dazio"), PanelKit.Value(Fmt.Pct(h.Duty, 0))));
double used = h.MonthlyCapacity > 0 ? Math.Clamp((double)h.UsedThisMonth / h.MonthlyCapacity, 0, 1) : 0;
col.AddChild(Bar(used, Palette.Workers));
col.AddChild(UiTheme.Text($"{T("Capacità usata questo mese")}: {Fmt.Pct(used, 0)}", 12, Palette.TextSecondary));
if (connected)
{
col.AddChild(UiTheme.Text($"{T("Servito da")} {LineName(w, h.Line)}", 12, Palette.TextSecondary));
}
else
{
col.AddChild(Wrapped(port ? T("Porta i binari fino al porto per comprare e vendere via mare.") : T("Porta i binari fino al confine per comprare e vendere via terra."), 13, Palette.TextSecondary));
var plan = new Button { Text = T("Pianifica la linea"), CustomMinimumSize = new Vector2(0, 40) };
int hub = h.Hub;
plan.Pressed += () => PlanLineRequested?.Invoke(hub);
col.AddChild(plan);
}
return card;
}
private static Control EventCard(ClientWorld w, MarketReport report)
{
var card = Card(Palette.Inner, Palette.Inner);
var col = (VBoxContainer)card.GetChild(0);
if (report.EventGood < 0)
{
col.AddChild(UiTheme.Text(T("Nessun evento in corso"), 13, Palette.TextSecondary, bold: true));
col.AddChild(Wrapped(T("I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse."), 13, Palette.TextSecondary));
return card;
}
bool up = report.EventShock > 0;
string good = GoodName(w, report.EventGood);
col.AddChild(UiTheme.Text(T("Evento in corso"), 13, Palette.AmberLight, bold: true));
col.AddChild(Wrapped(up ? $"{good}: {T("prezzo mondiale in rialzo")}" : $"{good}: {T("prezzo mondiale in calo")}", 17, Palette.Text, bold: true));
int months = Math.Max(1, (int)Math.Ceiling(report.EventMonths));
col.AddChild(Wrapped($"{T("Il prezzo mondiale di")} {good.ToLowerInvariant()} {(up ? T("è più alto del") : T("è più basso del"))} {Fmt.Pct(Math.Abs(report.EventShock), 0)} " +
$"{T("rispetto al ciclo per circa")} {months} {(months == 1 ? T("mese") : T("mesi"))}.", 13, Palette.Text));
return card;
}
private static Control TradingCard(ClientWorld w, MarketReport report)
{
var card = Card(Palette.Panel, Palette.Border);
var col = (VBoxContainer)card.GetChild(0);
col.AddChild(UiTheme.Text(T("Compravendita in proprio"), 17, bold: true));
string tier = report.TradingTier > 0 ? Fmt.Tier(w, report.TradingTier) : "—";
if (report.TradingUnlocked)
{
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello")} {tier}.", 13, Palette.Text));
col.AddChild(Bar(1, Palette.Amber));
return card;
}
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
col.AddChild(Bar(report.TradingProgress, Palette.Amber));
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Pct(report.TradingProgress, 0)}", 12, Palette.TextSecondary));
col.AddChild(Requirement($"{T("Patrimonio netto")} {report.NetWorth.ToString("short")} / {report.NetWorthRequired.ToString("short")}",
report.NetWorth.Cents >= report.NetWorthRequired.Cents));
col.AddChild(Requirement($"{T("Città collegate oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}: {report.TownsConnected} / {report.TownsRequired}",
report.TownsConnected >= report.TownsRequired));
col.AddChild(Requirement($"{T("Rating")} {report.Rating} ({T("serve")} {report.RatingRequired})", report.RatingMet));
return card;
}
// ------------------------------------------------------------------ mattoni
private static PanelContainer Card(Color background, Color border)
{
var card = new PanelContainer();
card.AddThemeStyleboxOverride("panel", UiTheme.Box(background, border, 10, 18));
card.AddChild(PanelKit.Column(8));
return card;
}
private static ProgressBar Bar(double fraction, Color color)
{
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 4, 0));
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
return bar;
}
private static Label Requirement(string text, bool met)
{
var l = UiTheme.Text((met ? "✓ " : "· ") + text, 12, met ? Palette.Ok : Palette.TextSecondary);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
{
var l = UiTheme.Text(text, size, color, bold);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -5,8 +5,9 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni e
/// delle merci (con la previsione tratteggiata e la sua banda, immagine 06), barre per il
/// patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// </summary>
public partial class SeriesChart : Control
{
@@ -18,6 +19,8 @@ public partial class SeriesChart : Control
private Style _style;
private Color _color = Palette.Amber;
private string _empty = "";
private IReadOnlyList<double> _forecast = [], _low = [], _high = [];
private string _todayLabel = "", _forecastLabel = "";
public SeriesChart(float height = 150)
{
@@ -34,9 +37,27 @@ public partial class SeriesChart : Control
_style = style;
_color = color;
_empty = empty;
_forecast = _low = _high = [];
QueueRedraw();
}
/// <summary>
/// Serie a linea seguita dalla previsione (prezzi, banda bassa e alta), un punto per passo
/// dopo l'ultimo valore; una riga verticale segna «oggi».
/// </summary>
public void ShowWithForecast(IReadOnlyList<double> values, IReadOnlyList<string> labels, IReadOnlyList<double> forecast,
IReadOnlyList<double> low, IReadOnlyList<double> high, Func<double, string> format, Color color, string empty,
string todayLabel, string forecastLabel)
{
Show(values, labels, format, Style.Line, color, empty);
bool consistent = forecast.Count == low.Count && forecast.Count == high.Count;
_forecast = consistent ? forecast : [];
_low = consistent ? low : [];
_high = consistent ? high : [];
_todayLabel = todayLabel;
_forecastLabel = forecastLabel;
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
@@ -50,6 +71,11 @@ public partial class SeriesChart : Control
return;
}
double min = _values.Min(), max = _values.Max();
if (_style == Style.Line && _forecast.Count > 0)
{
min = Math.Min(min, _low.Min());
max = Math.Max(max, _high.Max());
}
if (_style == Style.Bars) min = Math.Min(0, min);
if (max - min < 1e-9)
{
@@ -84,12 +110,14 @@ public partial class SeriesChart : Control
return;
}
float step = area.Size.X / (n - 1);
int f = _forecast.Count;
float step = area.Size.X / (n - 1 + f);
var points = new Vector2[n];
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
var fill = new List<Vector2>(points) { new(points[^1].X, area.End.Y), new(area.Position.X, area.End.Y) };
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
DrawPolyline(points, _color, 2.5f, true);
if (f > 0) DrawForecast(area, points[^1], step, Y, font, fontSize);
DrawCircle(points[^1], 4, Palette.AmberLight);
string last = _format(_values[^1]);
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
@@ -99,6 +127,35 @@ public partial class SeriesChart : Control
DrawLabels(area, n, step, font, fontSize, centered: false);
}
/// <summary>Previsione: banda chiara, linea tratteggiata e riga verticale di «oggi».</summary>
private void DrawForecast(Rect2 area, Vector2 today, float step, Func<double, float> y, Font font, int fontSize)
{
int f = _forecast.Count;
var band = new List<Vector2> { today };
for (int i = 0; i < f; i++) band.Add(new Vector2(today.X + step * (i + 1), y(_high[i])));
for (int i = f - 1; i >= 0; i--) band.Add(new Vector2(today.X + step * (i + 1), y(_low[i])));
DrawColoredPolygon(band.ToArray(), Palette.WithAlpha(Palette.Workers, 0.22f));
var previous = today;
for (int i = 0; i < f; i++)
{
var next = new Vector2(today.X + step * (i + 1), y(_forecast[i]));
DrawDashedLine(previous, next, Palette.Staff, 2f, 6f);
previous = next;
}
DrawDashedLine(new Vector2(today.X, area.Position.Y), new Vector2(today.X, area.End.Y), Palette.TextSecondary, 1f, 4f);
if (_todayLabel.Length > 0)
{
var dims = font.GetStringSize(_todayLabel, HorizontalAlignment.Left, -1, fontSize);
DrawString(font, new Vector2(today.X - dims.X / 2, area.End.Y + 16), _todayLabel, HorizontalAlignment.Left, -1, fontSize, Palette.Text);
}
if (_forecastLabel.Length > 0)
{
var dims = font.GetStringSize(_forecastLabel, HorizontalAlignment.Left, -1, fontSize);
DrawString(font, new Vector2(Math.Min(area.End.X - dims.X / 2, Size.X - dims.X - 4), area.End.Y + 16), _forecastLabel,
HorizontalAlignment.Left, -1, fontSize, Palette.Staff);
}
}
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
{
@@ -78,39 +78,6 @@ public partial class HelpPanel : VBoxContainer
}
}
/// <summary>Prezzi globali del giorno (resoconto giornaliero).</summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _rows = PanelKit.Column(4);
private long _day = -1;
public MarketPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Mercato"), 34));
AddChild(UiTheme.Text(T("Prezzi globali di oggi (la borsa arriva in seguito)."), 13, Palette.TextSecondary));
AddChild(_rows);
}
public override void _Process(double delta)
{
var digest = _session.World.LastDigest;
if (digest is null || digest.Day == _day) return;
_day = digest.Day;
foreach (var c in _rows.GetChildren()) c.QueueFree();
var goods = _session.World.Data.Goods;
for (int g = 0; g < Math.Min(goods.Count, digest.Prices.Count); g++)
{
var ratio = digest.Prices[g].Cents / (double)Math.Max(1, goods[g].BasePrice);
var value = PanelKit.Value($"{digest.Prices[g]} / {goods[g].Unit}");
value.AddThemeColorOverride("font_color", ratio > 1.15 ? Palette.AmberLight : ratio < 0.85 ? Palette.Staff : Palette.Text);
_rows.AddChild(PanelKit.Pair(goods[g].NameIt, value));
}
}
}
/// <summary>Conti della compagnia e prestiti.</summary>
public partial class FinancePanel : VBoxContainer
{
@@ -41,7 +41,8 @@ public partial class GameScreen : Node
private MaintenancePanel? _maintenance;
private IndustryPanel? _industryPanel;
private CompaniesPanel? _companies;
// pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta
private MarketPanel? _market;
// pannelli a tutto schermo (Compagnie e borsa, Mercato globale): coprono mappa e pannello destro, la barra resta
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
private Control? _mapArea;
private Control? _side;
@@ -108,6 +109,24 @@ public partial class GameScreen : Node
_companies?.Select(company);
}
/// <summary>Apre il «Mercato globale» a tutto schermo, facoltativamente su un bene.</summary>
public void OpenMarket(int good = -1)
{
if (_tool != Tool.Market) _toolbar.Select(Tool.Market);
if (good >= 0) _market?.Select(good);
}
/// <summary>Dal Mercato globale: strumento binari con la mappa centrata sull'hub da collegare.</summary>
private void PlanLineToHub(int hub)
{
_toolbar.Select(Tool.Track);
if (_session.World.Hubs.TryGetValue(hub, out var h))
{
_map.CenterOn(MapScale.V(h.Position));
_map.SetZoom(0.3f);
}
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
@@ -365,8 +384,9 @@ public partial class GameScreen : Node
_maintenance = null;
_industryPanel = null;
_companies = null;
_market = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool == Tool.Companies;
bool full = tool is Tool.Companies or Tool.Market;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
@@ -430,7 +450,11 @@ public partial class GameScreen : Node
panel = NewInfoPanel();
break;
case Tool.Market:
panel = new MarketPanel(_session);
_market = new MarketPanel(_session);
_market.CloseRequested += () => _toolbar.Select(Tool.None);
_market.PlanLineRequested += PlanLineToHub;
_full.AddChild(_market);
panel = NewInfoPanel();
break;
case Tool.Finance:
panel = new FinancePanel(_session);
+2 -1
View File
@@ -49,7 +49,8 @@
"ratioMax": 5.0,
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0,
"shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150, "priceFloor": 0.05 },
"historyDays": 360
"historyDays": 720,
"outlook": { "historyMonths": 24, "changeDays": 30, "forecastMonths": 4, "forecastBandPerMonth": 0.03, "sellPlaces": 3, "eventThreshold": 0.05 }
},
"localPrice": { "lambda": 0.35, "maxDeviation": 0.40, "epsilon": 1.0 },
"industry": {
+44 -1
View File
@@ -256,6 +256,48 @@
"historyDays": {
"type": "integer",
"minimum": 1
},
"outlook": {
"type": "object",
"properties": {
"historyMonths": {
"type": "integer",
"minimum": 1
},
"changeDays": {
"type": "integer",
"minimum": 1
},
"forecastMonths": {
"type": "integer",
"minimum": 0,
"maximum": 24
},
"forecastBandPerMonth": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"sellPlaces": {
"type": "integer",
"minimum": 1,
"maximum": 20
},
"eventThreshold": {
"type": "number",
"minimum": 0,
"maximum": 1
}
},
"required": [
"historyMonths",
"changeDays",
"forecastMonths",
"forecastBandPerMonth",
"sellPlaces",
"eventThreshold"
],
"additionalProperties": false
}
},
"required": [
@@ -267,7 +309,8 @@
"ratioMin",
"ratioMax",
"world",
"historyDays"
"historyDays",
"outlook"
],
"additionalProperties": false
},
+1 -1
View File
@@ -90,7 +90,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
## 6. Economia e contabilità
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`.
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio.
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
- Interpretazioni delle formule della guida: ADR 0004.
+7 -2
View File
@@ -77,7 +77,7 @@ costMultiplier: f64 }`
| 7 | Save | `name: string` |
| 8 | Load | `saveId: string` |
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3 e 6). Aggiunto in F4 |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6 e 7). Aggiunto in F4 |
### Comandi (`Command.type`, payload in ordine)
@@ -152,6 +152,7 @@ comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emitt
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool` (su richiesta, F6; ADR 0015) |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
| 131 | Notification | `EventInfo` |
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
@@ -190,6 +191,8 @@ Record (ognuno chiude con `flags`):
- `HoldingInfo { holder: i32 (−1 fondatore, −2 mercato, altrimenti compagnia), shares: i64 }`, `CompanyYearInfo { year, netWorth, cash, revenue, profit: Money, tier: u8, trains, trackKm: f32, sharePrice: Money }`
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
- `GoodMarketInfo { good, available, price: f64 (centesimi), change: f32 (30 giorni), supplyMonth, demandMonth, worldSupplyMonth, worldDemandMonth, stockUnits: f64, stockMonths: f32 (−1 senza domanda), history: [PricePointInfo { day: i64, price: f64 }] (un campione per mese, l'ultimo è oggi), forecast: [ForecastInfo { months: u8, price, low, high: f64 }], sellPlaces: [SellPlaceInfo { kind: u8 (0 industria, 1 hub), target, price: f64, line: i32 (−1 non collegato) }] }`
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
## 6. Flusso e interest management
@@ -208,7 +211,9 @@ Record (ognuno chiude con `flags`):
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. Dalla F5 anche
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce.
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce. Dalla F6
`MarketReport` (quadro del mercato globale per la compagnia della sessione), che il pannello chiede
all'apertura e a ogni nuovo giorno; il server non lo manda da solo.
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
sessione si chiude (il client può riprenderla).
- Obiettivo di banda in regime: < 100 KB/s per client.
+11 -3
View File
@@ -94,18 +94,26 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
## In corso
- Nessun lavoro a metà: F5 chiusa.
### F6 — Economia completa, eventi, rifinitura
- **Mercato globale (issue #29, ADR 0015)**:
- storico dei prezzi a 24 mesi (`market.historyDays` 720); i salvataggi con lo storico di 360 giorni si migrano al caricamento con `RollingWindow.Extended`, senza cambiare formato;
- `MarketOutlook` (Core, sola lettura): storico mensile (un campione per mese di calendario), variazione a 30 giorni, offerta e domanda mensili con la quota mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi dalla componente mondiale con banda, «Dove conviene vendere» (industrie al prezzo locale dell'ADR 0004 e hub) con la linea che collega, hub, evento in corso, avanzamento verso la compravendita in proprio; parametri in `balance.json` (`market.outlook`);
- protocollo: `DetailKind.Market` (7) e `MarketReport` (129); server: quadro su richiesta;
- client: pannello «Mercato globale» a tutto schermo come l'immagine 06 (beni, storico e previsione nel grafico, offerta, domanda, scorte, vendite, hub con «Pianifica la linea», evento, compravendita in proprio); schermata `16_mercato` nel pilota automatico;
- test: finestra allungata, migrazione di un salvataggio a 360 giorni, storico mensile, previsione deterministica ed entro i limiti, evento, analisi su Valdoria (linea che collega, ordine delle vendite, indice, commercio, nessun effetto sull'hash), round-trip di `MarketReport`, quadro via WebSocket. 126 test (120 senza i lenti).
- Restano della F6: commercio (`BuyGoods`/`SellGoods`), eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
## Prossimo passo
- F6: hub e commercio (`BuyGoods`/`SellGoods`), eventi, storico dei prezzi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 06–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`, esportazione Windows con il server.
- F6: hub e commercio (`BuyGoods`/`SellGoods`, con i prezzi e le destinazioni di `MarketOutlook`), eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
## Limiti noti
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): i pannelli Mercato, Industria e Scalata e la schermata di connessione vanno allineati in F6.
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
+77
View File
@@ -0,0 +1,77 @@
# ADR 0015 — Mercato globale: storico a 24 mesi, analisi e previsione (F6)
Stato: accettato (F6, issue #29).
## Contesto
La F6 chiede lo storico dei prezzi e il pannello «Mercato globale» dell'immagine di riferimento 06:
elenco dei beni con prezzo, variazione a 30 giorni e barre di offerta e domanda; storico a 24 mesi con
la previsione a qualche mese; offerta, domanda e scorte; «Dove conviene vendere»; hub con capacità e
dazio; evento di mercato in corso; avanzamento verso la compravendita in proprio. La guida (6.3) fissa
le formule del prezzo globale e locale ma non dice come leggere storico, scorte, previsione ed eventi,
né come migrare i salvataggi con lo storico di un anno.
## Decisione
1. **Storico a 24 mesi.** `market.historyDays` passa da 360 a 720: `Market.PriceHistory` resta una
finestra mobile giornaliera per bene, salvata con la sua lunghezza. Al caricamento, se la finestra
salvata è più corta di quella dei dati, `RollingWindow.Extended` ne crea una più lunga riaggiungendo
i valori dal più vecchio: stessi prezzi, stesso ordine, nessun cambio di formato del salvataggio.
Una finestra salvata più lunga dei dati resta com'è. Il KPI annuale di `simulate` usa la media degli
ultimi 360 giorni (`AverageOfLast`), non dell'intera finestra.
2. **Analisi come pura funzione del mondo.** `MarketOutlook` (Core, `Economy/MarketOutlook.cs`) legge
il mondo e non scrive nulla: nessuno stato nuovo, nessun numero casuale, nessuna iterazione di
dizionari; matematica da `DMath`. Il server la proietta in `MarketReport` (129) su richiesta
(`RequestDetail` con `DetailKind.Market` = 7); il client la mostra com'è. I parametri stanno in
`balance.json`, `market.outlook` (validati: lo storico mensile deve stare nella finestra).
3. **Storico mensile.** Un campione per mese di calendario: il prezzo dell'ultimo giorno di ogni mese
concluso più quello del giorno corrente, fino a `historyMonths` (24) campioni. Il «giorno corrente» è
l'ultimo registrato dal sistema del mercato, che gira al primo tick del giorno: al tick 0 è ancora
ieri.
4. **Variazione a 30 giorni** = Pg(oggi)/Pg(oggi − 30) − 1; con meno storico si usa il più vecchio
disponibile (0 senza storico).
5. **Offerta e domanda mensili.** Le finestre `Supply` e `Demand` (30 giorni) riportate ai giorni del
mese. Accanto si dà la quota mondiale con la stessa formula di `MarketSystem` (ADR 0004 §1):
V = max(baseline·giorni, quota·(D + S)/2) al prezzo mondiale Pw, domanda V·(Pw/Pg)^ε e offerta
V·(Pg/Pw)^ε. Il pannello mostra «offerta globale» e «domanda globale» come somma delle due, che è
proprio il rapporto che muove il prezzo; il suggerimento separa mappa e mondo.
6. **Scorte in mesi** = giacenze del bene (input e output nei magazzini delle industrie aperte più le
merci in attesa nelle stazioni vive; esclusi i carichi in viaggio) divise per la domanda mensile
della mappa; −1 se la domanda è nulla.
7. **Indice materie prime** = media di Pg/Pb × 100 sui beni disponibili nell'anno corrente (era), con
la variazione a 30 giorni calcolata sugli stessi beni. Tutti i beni disponibili, non solo le materie
grezze: è l'indice del mercato che il giocatore vede nell'elenco.
8. **Previsione** a `forecastMonths` (4) mesi dalla sola componente mondiale, che è l'unica parte del
prezzo con una dinamica nota in anticipo: Pf(Δ) = Pg·(1 + W(t + Δ))/(1 + W(t)), con il ciclo
A·sin(2πt/T) e lo shock che decade come in `MarketSystem` (shock·exp(−Δ/shockDecayDays)), (1 + W)
non sotto `priceFloor`, Pf entro 0,3·Pb e 3·Pb. La banda è ±`forecastBandPerMonth` (3 %) per mese di
distanza, anch'essa entro i limiti. Domanda e offerta della mappa non si prevedono: dipendono dalle
scelte dei giocatori. Un bene non ancora disponibile ha previsione piatta.
9. **Dove conviene vendere.** Candidati: le industrie aperte di livello > 0 che consumano il bene, al
prezzo locale dell'ADR 0004 §3 con Dl = consumo giornaliero a piena capacità × giorni di magazzino
(`IndustryMath.InputCapacity`, cioè `storageDays` come scorta desiderata) e Sl = giacenza dell'input;
e gli hub, al prezzo d'esportazione Pg·(1 − dazio). Ordine per prezzo decrescente (a parità prima le
industrie, poi l'id), i primi `sellPlaces` (3). Il prezzo è quello alla destinazione: il trasporto
dipende dall'origine e si stima a parte.
10. **Collegato o no.** Una destinazione è collegata se una stazione viva della compagnia la ha nel
bacino ed è fermata di una linea della compagnia con almeno un treno (lo stesso criterio di
`Tiers.ServedStations`); si indica la linea con l'id più basso, altrimenti −1 («non collegato»).
Vale anche per gli hub, con la capacità usata nel mese corrente.
11. **Evento in corso.** Lo shock mondiale più forte in valore assoluto tra i beni disponibili, se supera
`eventThreshold` (5 % del prezzo base), con il segno e i mesi stimati prima che il decadimento lo
porti sotto la soglia: shockDecayDays·ln(|shock|/soglia)/giorni del mese. È lo stesso shock che
`MarketSystem` annuncia con una notizia quando nasce.
12. **Compravendita in proprio.** Il primo livello di `tiers.json` con `trading` sblocca il commercio
(oggi il 2, «Compagnia regionale»). Se la compagnia ce l'ha è «sbloccata»; altrimenti l'avanzamento
è il minimo tra le frazioni dei requisiti numerici (patrimonio netto / richiesto, città collegate /
richieste, entrambe limitate a 1); il rating è soddisfatto o no e si mostra a parte, perché non ha
una frazione sensata.
## Conseguenze
- Il quadro del mercato costa poco (16 beni, 24 campioni, una scansione di industrie e stazioni) e si
calcola solo su richiesta: il pannello lo chiede all'apertura e a ogni nuovo giorno.
- Lo storico doppio raddoppia la sezione dei prezzi nel salvataggio e nell'hash giornaliero
(16 × 720 numeri).
- I comandi `BuyGoods` e `SellGoods` restano da fare (seconda parte della F6): l'analisi dà già i prezzi
e le destinazioni che useranno, e lo sblocco del livello che li abilita.
@@ -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" : "";
@@ -0,0 +1,236 @@
using System.Text.Json.Nodes;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Rail;
namespace RailEnterprise.Tests.Economy;
/// <summary>Mercato globale (F6, ADR 0015): storico a 24 mesi, migrazione della finestra, previsione, analisi.</summary>
public static class MarketOutlookTests
{
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
[Test(Description = "Una finestra allungata conserva i valori nello stesso ordine e continua a scorrere")]
public static void ExtendedWindowKeepsValuesInOrder()
{
var window = new RollingWindow(5);
for (int v = 1; v <= 8; v++) window.Add(v);
var longer = window.Extended(10);
Assert.Equal(10, longer.Length);
Assert.Equal(5, longer.Count);
for (int k = 0; k < 5; k++) Assert.Equal(8.0 - k, longer.Ago(k));
Assert.Equal(30.0, longer.Sum);
longer.Add(9);
Assert.Equal(6, longer.Count);
Assert.Equal(9.0, longer.Ago(0));
Assert.Equal(4.0, longer.Ago(5));
Assert.Equal(39.0, longer.Sum);
Assert.Throws<ArgumentOutOfRangeException>(() => window.Extended(4));
Assert.Approx(8.5, longer.AverageOfLast(2), 1e-12);
}
[Test(Description = "Un salvataggio con lo storico dei prezzi di 360 giorni si carica con la finestra di 720 e gli stessi prezzi")]
public static void OldSavesWithAShortPriceHistoryAreExtended()
{
var files = MemoryDataSource.Snapshot(TestData.Source);
var balance = JsonNode.Parse(files["balance.json"])!;
balance["market"]!["historyDays"] = 360;
balance["market"]!["outlook"]!["historyMonths"] = 12;
files["balance.json"] = balance.ToJsonString();
var oldData = GameData.Load(new MemoryDataSource(files));
Assert.Equal(360, oldData.Balance.Market.HistoryDays);
var settings = new NewGameSettings { Seed = 1501, SizeKm = 64, DifficultyId = "imprenditore" };
var old = WorldFactory.Create(oldData, settings);
old.RunDays(400);
byte[] save = SaveFile.Save(old, "test");
var loaded = SaveFile.Load(TestData.Data, save);
int expected = TestData.Data.Balance.Market.HistoryDays;
Assert.Equal(720, expected);
for (int g = 0; g < TestData.Data.GoodCount; g++)
{
var before = old.Market.PriceHistory[g];
var after = loaded.Market.PriceHistory[g];
Assert.Equal(expected, after.Length);
Assert.Equal(before.Count, after.Count);
for (int k = 0; k < before.Count; k++) Assert.Equal(before.Ago(k), after.Ago(k), $"bene {g}, {k} giorni fa");
}
// la partita continua e lo storico cresce oltre i 360 giorni
loaded.RunDays(30);
Assert.Equal(390, loaded.Market.PriceHistory[0].Count);
Assert.True(MarketOutlook.MonthlyHistory(loaded, 0, 24).Count >= 13, "storico mensile oltre l'anno");
}
[Test(Description = "Storico mensile: un campione per mese di calendario (l'ultimo giorno) più il giorno corrente, 24 mesi")]
public static void MonthlyHistoryTakesOneSamplePerMonth()
{
var w = TestWorlds.NoAi(1502);
w.RunDays(800);
w.RunTicks(5); // a metà giornata: il giorno corrente è già nello storico
int dpm = w.Calendar.DaysPerMonth;
int coal = GoodIndex(w, "coal");
var history = MarketOutlook.MonthlyHistory(w, coal, 24);
Assert.Equal(24, history.Count);
long last = MarketOutlook.LastRecordedDay(w);
Assert.Equal(w.Clock.Day, last);
Assert.Equal(last, history[^1].Day);
Assert.Equal(w.Market.GlobalPrice[coal], history[^1].Price);
for (int i = 0; i < history.Count - 1; i++)
{
Assert.Equal((long)dpm - 1, history[i].Day % dpm, $"campione {i} all'ultimo giorno del mese");
if (i > 0) Assert.Equal((long)dpm, history[i].Day - history[i - 1].Day);
Assert.Equal(w.Market.PriceHistory[coal].Ago((int)(last - history[i].Day)), history[i].Price);
}
Assert.True(history[^2].Day < last && last - history[^2].Day <= dpm, "penultimo campione nel mese precedente");
// all'inizio di un giorno (prima del sistema del mercato) l'ultimo campione è quello di ieri
var fresh = TestWorlds.NoAi(1503);
fresh.RunDays(45);
Assert.Equal(fresh.Clock.Day - 1, MarketOutlook.LastRecordedDay(fresh));
var short_ = MarketOutlook.MonthlyHistory(fresh, coal, 24);
Assert.Equal(2, short_.Count);
Assert.Equal(29L, short_[0].Day);
Assert.Equal(44L, short_[1].Day);
}
[Test(Description = "La previsione segue la componente mondiale, è deterministica, resta entro i limiti e la banda si allarga")]
public static void ForecastIsDeterministicAndWithinLimits()
{
var a = TestWorlds.NoAi(1504);
var b = TestWorlds.NoAi(1504);
a.RunDays(200);
b.RunDays(200);
var m = a.Data.Balance.Market;
for (int g = 0; g < a.Data.GoodCount; g++)
{
var fa = MarketOutlook.Forecast(a, g);
var fb = MarketOutlook.Forecast(b, g);
Assert.SequenceEqual(fa, fb, $"previsione del bene {g}");
Assert.Equal(m.Outlook.ForecastMonths, fa.Count);
double pb = a.Data.Goods[g].BasePrice;
for (int i = 0; i < fa.Count; i++)
{
var p = fa[i];
Assert.Equal(i + 1, p.Months);
Assert.InRange(p.Price, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
Assert.True(p.Low <= p.Price && p.Price <= p.High, $"banda del bene {g} al mese {p.Months}");
Assert.InRange(p.Low, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
Assert.InRange(p.High, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
}
}
// uno shock positivo forte decade: il prezzo previsto scende mese dopo mese e la banda si allarga
int coal = GoodIndex(a, "coal");
a.Market.GlobalPrice[coal] = a.Data.Goods[coal].BasePrice;
for (int g = 0; g < a.Data.GoodCount; g++) a.Market.Shock[g] = 0;
a.Market.Shock[coal] = 0.25;
var forecast = MarketOutlook.Forecast(a, coal);
Assert.True(forecast[^1].Price < a.Market.GlobalPrice[coal], $"previsione {forecast[^1].Price:0} sotto il prezzo attuale");
for (int i = 1; i < forecast.Count; i++)
{
Assert.True(forecast[i].Price < forecast[i - 1].Price, $"mese {i + 1} sotto il mese {i}");
Assert.True(forecast[i].High / forecast[i].Price > forecast[i - 1].High / forecast[i - 1].Price, "la banda si allarga");
}
// lo stesso shock è l'evento in corso, con i mesi prima che scenda sotto la soglia
var e = MarketOutlook.StrongestEvent(a);
Assert.Equal(coal, e.Good);
Assert.Equal(0.25, e.Shock);
double months = m.World.ShockDecayDays * Math.Log(0.25 / m.Outlook.EventThreshold) / a.Calendar.DaysPerMonth;
Assert.Approx(months, e.Months, 1e-6);
a.Market.Shock[coal] = -m.Outlook.EventThreshold / 2;
Assert.Equal(-1, MarketOutlook.StrongestEvent(a).Good);
}
[Test(Description = "Analisi del mercato su Valdoria: beni, vendite ordinate con la linea che collega, hub, indice, commercio; nessun effetto sul mondo")]
public static void OutlookOnValdoria()
{
var f = RailFixture.Valdoria();
var w = f.W;
var (mine, mill, depot) = f.BuildFreightNetwork();
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
// la linea senza treni non collega
Assert.False(MarketOutlook.IndustryLine(w, f.Me, MarketOutlook.StationLines(w, f.Me), steel.Id).IsValid, "linea senza treni");
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
w.RunDays(40);
var lines = MarketOutlook.StationLines(w, f.Me);
Assert.Equal(line, MarketOutlook.IndustryLine(w, f.Me, lines, steel.Id).Value);
Assert.False(MarketOutlook.IndustryLine(w, CompanyId.None, MarketOutlook.StationLines(w, CompanyId.None), steel.Id).IsValid);
ulong hash = StateHasher.Compute(w);
var report = MarketOutlook.Build(w, f.Me);
Assert.Equal(hash, StateHasher.Compute(w), "l'analisi non cambia il mondo");
Assert.Equal(w.Data.GoodCount, report.Goods.Count);
Assert.Equal(w.Hubs.Count, report.Hubs.Count);
int ore = GoodIndex(w, "iron_ore");
var good = report.Goods[ore];
Assert.True(good.Available);
Assert.Equal(w.Market.GlobalPrice[ore], good.Price);
Assert.True(good.History.Count >= 2, "storico di almeno due mesi");
Assert.True(good.SellPlaces.Count is > 0 and <= 3, $"destinazioni: {good.SellPlaces.Count}");
for (int i = 1; i < good.SellPlaces.Count; i++) Assert.True(good.SellPlaces[i - 1].Price >= good.SellPlaces[i].Price, "ordinate per prezzo");
// ogni destinazione industriale consuma il bene, con il prezzo locale dell'ADR 0004
var lp = w.Data.Balance.LocalPrice;
foreach (var p in good.SellPlaces)
{
if (p.Kind == SellPlaceKind.Hub)
{
Assert.Equal(w.Hubs[p.Target].BuyPrice(good.Price), p.Price);
continue;
}
var ind = w.Industries[p.Target];
int input = ind.InputIndexOf(ore);
Assert.True(input >= 0 && !ind.Closed && ind.Level > 0, $"{ind.Name} consuma minerale");
Assert.InRange(p.Price, good.Price * (1 - lp.MaxDeviation) - 1e-9, good.Price * (1 + lp.MaxDeviation) + 1e-9);
Assert.Equal(MarketOutlook.IndustryLine(w, f.Me, lines, ind.Id), p.Line);
}
// tutte le industrie che consumano minerale e gli hub sono candidati: il migliore è davvero il primo
double best = w.Hubs.Select(h => h.BuyPrice(good.Price)).Concat(w.Industries
.Where(i => !i.Closed && i.Level > 0 && i.InputIndexOf(ore) >= 0)
.Select(i => Market.LocalPrice(good.Price, Core.Simulation.Systems.IndustryMath.InputCapacity(i, i.InputIndexOf(ore), w.Calendar.DaysPerMonth), i.InputStock[i.InputIndexOf(ore)], lp)))
.Max();
Assert.Equal(best, good.SellPlaces[0].Price);
// scorte e domanda
Assert.Equal(MarketOutlook.StockUnits(w, ore), good.StockUnits);
if (good.DemandMonth > 0) Assert.Approx(good.StockUnits / good.DemandMonth, good.StockMonths, 1e-9);
Assert.True(good.WorldDemandMonth > 0 && good.WorldSupplyMonth > 0, "quota mondiale");
// indice materie prime: media di Pg/Pb × 100 sui beni disponibili
var available = Enumerable.Range(0, w.Data.GoodCount).Where(g => w.Data.Goods[g].Era <= w.Clock.Year).ToList();
Assert.Approx(available.Average(g => w.Market.GlobalPrice[g] / w.Data.Goods[g].BasePrice) * 100, report.Index, 1e-9);
foreach (var g in report.Goods.Where(g => !g.Available)) Assert.Equal(0, g.SellPlaces.Count);
// hub: nessuna stazione della compagnia al porto
Assert.True(report.Hubs.All(h => !h.Line.IsValid), "hub non collegati");
Assert.Equal(w.Hubs[0].MonthlyCapacity, report.Hubs[0].MonthlyCapacity);
// compravendita in proprio: dal livello 2 di tiers.json
var trading = report.Trading;
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading);
Assert.Equal(tier.Level, trading.Level);
Assert.False(trading.Unlocked);
Assert.Equal(tier.Requirements.CreditRating, trading.RatingRequired);
Assert.InRange(trading.Fraction, 0, 1);
double worth = Math.Clamp((double)w.Player.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1);
double towns = Math.Clamp((double)trading.TownsConnected / tier.Requirements.ConnectedTownsOver.Count, 0, 1);
Assert.Approx(Math.Min(worth, towns), trading.Fraction, 1e-12);
w.Player.Tier = tier.Level;
Assert.True(MarketOutlook.Trading(w, f.Me).Unlocked);
Assert.Equal(1.0, MarketOutlook.Trading(w, f.Me).Fraction);
}
}
@@ -125,6 +125,30 @@ public static class ProtocolTests
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
};
yield return new MarketReport
{
Day = 720, Index = 104.2f, IndexChange = 0.021f,
Goods =
[
new GoodMarketInfo
{
Good = 8, Available = true, Price = 15200.5, Change = 0.124f, SupplyMonth = 41200, DemandMonth = 52800.25, WorldSupplyMonth = 900,
WorldDemandMonth = 1100.5, StockUnits = 74000, StockMonths = 1.4f,
History = [new PricePointInfo { Day = 689, Price = 14800 }, new PricePointInfo { Day = 720, Price = 15200.5 }],
Forecast = [new ForecastInfo { Months = 1, Price = 15400, Low = 14900, High = 15900 }],
SellPlaces =
[
new SellPlaceInfo { Kind = SellPlaceInfo.Hub, Target = 0, Price = 16100, Line = 6 },
new SellPlaceInfo { Kind = SellPlaceInfo.Industry, Target = 12, Price = 15800, Line = -1 },
],
},
new GoodMarketInfo { Good = 14, Available = false, Price = 9000, StockMonths = -1 },
],
Hubs = [new HubMarketInfo { Hub = 0, Kind = 0, MonthlyCapacity = 1200, Duty = 0.04f, UsedThisMonth = 864, Line = 6 }],
EventGood = 8, EventShock = -0.18f, EventMonths = 5.9f,
TradingUnlocked = false, TradingTier = 2, TradingProgress = 0.58f, NetWorth = new Money(23_200_000), NetWorthRequired = new Money(40_000_000),
TownsConnected = 1, TownsRequired = 2, TownPopulation = 800, Rating = "BBB", RatingRequired = "BB", RatingMet = true,
};
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() };
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
@@ -260,6 +260,42 @@ public static class ServerTests
await client.WaitFor(() => client.Received.OfType<Pong>().FirstOrDefault(p => p.Nonce == 5), "il server risponde ancora");
}
[Test(Description = "F6 in rete: il quadro del mercato globale arriva su richiesta con beni, storico, previsione, hub e commercio")]
public static void MarketReportOnRequest() => RunMarket().GetAwaiter().GetResult();
private static async Task RunMarket()
{
var scenario = ScenarioHelper.Load("valdoria");
int hubs = scenario.World.Hubs.Count;
await using var server = ServerFixture.Start(scenario.World);
await using var client = await TestClient.ConnectAsync(server);
var w = client.World;
var data = TestData.Data;
await client.WaitUntil(() => w.LastDigest is { Day: >= 3 }, "tre giorni di prezzi");
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
var stale = w.Market;
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Market, Target = 0 });
var report = await client.WaitFor(() => ReferenceEquals(w.Market, stale) ? null : w.Market, "quadro del mercato");
Assert.True(report.Day >= 3, $"giorno {report.Day}");
Assert.Equal(data.GoodCount, report.Goods.Count);
Assert.Equal(hubs, report.Hubs.Count);
Assert.True(report.Index > 0, $"indice {report.Index}");
var coal = report.Goods[data.Goods.First(g => g.Id == "coal").Index];
Assert.True(coal.Available && coal.Price > 0, "carbone disponibile");
Assert.True(coal.History.Count >= 1 && coal.History[^1].Price > 0, "storico del carbone");
Assert.Equal(data.Balance.Market.Outlook.ForecastMonths, coal.Forecast.Count);
Assert.True(coal.SellPlaces.Count is > 0 and <= 3, $"destinazioni {coal.SellPlaces.Count}");
Assert.True(coal.SellPlaces.All(p => p.Line == -1), "nessuna linea: nessuna destinazione collegata");
Assert.True(report.Hubs.All(h => h.Line == -1 && h.MonthlyCapacity > 0), "hub non collegati");
var tier = data.Tiers.Tiers.First(t => t.Unlocks.Trading);
Assert.False(report.TradingUnlocked);
Assert.Equal((byte)tier.Level, report.TradingTier);
Assert.Equal(tier.Requirements.CreditRating.ToString(), report.RatingRequired);
Assert.Equal(new Money(tier.Requirements.NetWorth), report.NetWorthRequired);
Assert.True(report.TradingProgress is >= 0 and < 1, $"avanzamento {report.TradingProgress}");
}
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();