Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Panels/MarketPanel.cs
T
Alby96andClaude Opus 5.5 e157dd77bc F6: compravendita in proprio e spedizione della merce tra stazioni
Dal livello che sblocca il commercio la compagnia può comprare e vendere
merci in proprio. Così può fare arbitraggio tra un produttore con il
magazzino pieno e un consumatore a secco anche dove il vettore non ha
contratti. Le regole sono nell'ADR 0016.

- Ogni stazione della compagnia ha un magazzino: 500 unità e una
  giacenza di 25 centesimi per unità al mese, in balance.json, blocco
  «trading». La merce in magazzino rientra nell'invariante delle merci.
- BuyGoods compra al prezzo locale marginale dell'ADR 0004, unità per
  unità, partendo dal più economico, dai produttori del bacino e dagli
  hub. La merce presa dagli hub conta come importata.
- SellGoods vende ai consumatori del bacino partendo dal prezzo più
  alto, entro lo spazio libero e la cassa di ciascuno. Vende anche agli
  hub, e quella merce conta come esportata.
- Il denaro di entrambi i comandi passa dal registro, sulla voce
  «Commercio».
- ShipGoods (comando 40) spedisce la merce propria come pacchetto senza
  tariffa né consumatore. Il pacchetto entra nel magazzino di
  destinazione, che riserva lo spazio alla partenza. Il percorso dei
  pacchetti già esistenti non cambia: l'accettazione F4 dà ancora
  35/20 guasti senza la linea e 75/2 con la linea.
- Il salvataggio passa al corpo versione 4 (TradingSerializer). I
  salvataggi più vecchi si caricano con i magazzini vuoti, e i magazzini
  entrano nell'hash di stato.
- MarketReport porta i magazzini nel blocco 1. Il Mercato globale ha il
  riquadro «Compravendita in proprio».
- Le IA non commerciano ancora.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:26:20 +01:00

560 lines
27 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 readonly TradeBox _trade;
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;
_trade = new TradeBox(session);
// dopo un comando di compravendita si chiede subito il quadro aggiornato (giacenze e prezzi)
_trade.Traded += () => _requestedDay = long.MinValue;
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…");
}
public override void _Notification(int what)
{
// il riquadro della compravendita fuori dall'albero (commercio non sbloccato) va liberato a mano
if (what == NotificationPredelete && IsInstanceValid(_trade) && _trade.GetParent() is null) _trade.Free();
}
/// <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);
_trade.Update(report, good);
}
}
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("Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. 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)
{
// il riquadro della compravendita resta lo stesso nodo tra un quadro e l'altro
_trade.GetParent()?.RemoveChild(_trade);
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 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(_trade);
_trade.Update(report, _selected);
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;
}
}