F6: tutorial, correzioni della revisione
Unisce origin/main (audio, ere e obsolescenza, scheda dell'industria e schermata di connessione) e corregge i rilievi della revisione del tutorial (ADR 0023 aggiornato). - Chiave dell'avanzamento senza l'impronta del terreno, che il server ricalcola e che cambia giocando (città, industrie): origine della partita, seme, lato, anno d'inizio, regione e compagnia. Un tutorial ripreso dopo un anno di gioco ritrova la sua voce. - «Tutorial» apre una partita locale di prova sempre nuova in user://tutorial-server invece di riprendere l'autosalvataggio del giocatore e rifare il tutorial lì dentro; con salvataggi locali già presenti la casella «Mostra il tutorial» parte spenta. Casella e pulsante passano nella nuova ConnectScreen (MenuScreen non c'è più). - La casella spuntata vale anche su una voce chiusa o completata (stesso seme di una partita vecchia). - Contorno ritagliato dai contenitori a scorrimento, con l'elemento portato in vista; del tutto nascosto si usa il ripiego. - Pulsanti del riquadro senza fuoco: Invio e spazio restano alla partita (Costruisci, pausa) e non saltano il passo. - La base di «increase» è presa al completamento del passo precedente e gli esiti dei comandi si valutano subito: un binario costruito appena dopo conta per il passo nuovo. - Velocità contata solo dalle richieste di questo client. - Copione mancante o non valido segnalato nella partita; validazione dei null ammessi dal JSON. - Test: chiave stabile con impronta diversa, base al completamento, piano con la casella, null nel copione. 228 test (208 senza i lenti). Refs #45. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
64209afd5f
75 files changed
+7612
-571
No files matched your search
@@ -11,21 +11,39 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
|
||||
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
|
||||
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
|
||||
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
|
||||
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
|
||||
/// Scheda dell'industria a tutto schermo (immagine di riferimento 07, sezione 11): in alto nome,
|
||||
/// livello, proprietà, stazione che la serve, valore stimato e l'anello dell'efficienza con il
|
||||
/// fattore che la limita; sotto tre schede (materie prime in ingresso, forza lavoro, produzione), il
|
||||
/// grafo della catena produttiva con fornitori, città dei pendolari e clienti, e la scheda «Impianti
|
||||
/// e crescita» con condizione, punteggio trimestrale e soglie, comandi del proprietario e storico dei
|
||||
/// fermi. Tutti i numeri arrivano dal server nella scheda (IndustryCard, blocco 1: ADR 0021); il
|
||||
/// pannello li chiede una volta al secondo e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
|
||||
private readonly OptionButton _chooser = new() { CustomMinimumSize = new Vector2(320, 44), FitToLongestItem = false };
|
||||
private readonly List<int> _ids = [];
|
||||
private readonly VBoxContainer _header = PanelKit.Column(8);
|
||||
private readonly Label _title = UiTheme.TitleLabel("", 44);
|
||||
private readonly Label _subtitle = UiTheme.Text("", 15, Palette.TextSecondary);
|
||||
private readonly Label _ownerLine = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _valuation = UiTheme.Text("", 26, Palette.AmberLight, bold: true);
|
||||
private readonly EfficiencyRing _ring = new();
|
||||
private readonly Label _limit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly VBoxContainer _notices = PanelKit.Column(6);
|
||||
private readonly ScrollContainer _scroll = new() { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
private readonly VBoxContainer _inputs = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _workforce = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _production = PanelKit.Column(8);
|
||||
private readonly ChainGraph _graph = new();
|
||||
private readonly VBoxContainer _chainFooter = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _plants = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _controls = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _details = PanelKit.Column(6);
|
||||
private readonly VBoxContainer _history = PanelKit.Column(4);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
/// <summary>Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta).</summary>
|
||||
private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private Button? _overhaul, _upgrade;
|
||||
private readonly List<Button> _budgetButtons = [];
|
||||
private SpinBox? _partsOrder;
|
||||
private int _industry = -1;
|
||||
@@ -33,25 +51,108 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private int _entityVersion = -1, _detailVersion = -1;
|
||||
private double _request, _sinceRefresh;
|
||||
|
||||
/// <summary>«Torna alla mappa».</summary>
|
||||
public event Action? CloseRequested;
|
||||
|
||||
/// <summary>«Crea una linea verso questa industria»: strumento binari centrato sull'industria.</summary>
|
||||
public event Action<int>? PlanLineRequested;
|
||||
|
||||
public IndustryPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 10);
|
||||
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
|
||||
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
|
||||
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(help);
|
||||
AddChild(_list);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(_header);
|
||||
AddChild(_controls);
|
||||
AddChild(_details);
|
||||
AddThemeConstantOverride("separation", 14);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
// barra di navigazione: ritorno alla mappa e scelta dell'industria
|
||||
var nav = PanelKit.Row(12);
|
||||
var back = new Button { Text = "‹ " + T("Mappa"), CustomMinimumSize = new Vector2(120, 44) };
|
||||
back.Pressed += () => CloseRequested?.Invoke();
|
||||
nav.AddChild(back);
|
||||
nav.AddChild(_chooser);
|
||||
_chooser.ItemSelected += i => Select(_ids[(int)i]);
|
||||
var hint = UiTheme.Text(T("Scheda dell'industria"), 13, Palette.TextSecondary);
|
||||
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
nav.AddChild(hint);
|
||||
AddChild(nav);
|
||||
|
||||
// intestazione: nome, livello, proprietà, valore ed efficienza
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(2);
|
||||
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_title.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
titles.AddChild(_title);
|
||||
titles.AddChild(_subtitle);
|
||||
_ownerLine.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
titles.AddChild(_ownerLine);
|
||||
header.AddChild(titles);
|
||||
var value = PanelKit.Column(0);
|
||||
value.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var valueCaption = UiTheme.Text(T("Valore stimato"), 13, Palette.TextSecondary);
|
||||
valueCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_valuation.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
value.AddChild(valueCaption);
|
||||
value.AddChild(_valuation);
|
||||
header.AddChild(value);
|
||||
var ring = PanelKit.Column(2);
|
||||
ring.AddChild(_ring);
|
||||
_limit.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
_limit.CustomMinimumSize = new Vector2(150, 0);
|
||||
_limit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
ring.AddChild(_limit);
|
||||
header.AddChild(ring);
|
||||
AddChild(header);
|
||||
AddChild(_notices);
|
||||
|
||||
// corpo scorrevole: tre schede, poi catena produttiva e impianti
|
||||
AddChild(_scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
_scroll.AddChild(margin);
|
||||
var body = PanelKit.Column(18);
|
||||
margin.AddChild(body);
|
||||
|
||||
var cards = PanelKit.Row(18);
|
||||
cards.AddChild(Card(T("Materie prime in ingresso"), _inputs, 1));
|
||||
cards.AddChild(Card(T("Forza lavoro"), _workforce, 1));
|
||||
cards.AddChild(Card(T("Produzione"), _production, 1));
|
||||
body.AddChild(cards);
|
||||
|
||||
var lower = PanelKit.Row(18);
|
||||
var chain = PanelKit.Column(10);
|
||||
var legend = PanelKit.Row(16);
|
||||
foreach (var (text, color) in new[] { (T("merci su linea"), Palette.Amber), (T("lavoratori"), Palette.Workers), (T("personale"), Palette.Staff), (T("non collegato"), Palette.TextSecondary) })
|
||||
legend.AddChild(UiTheme.Text("— " + text, 12, color));
|
||||
chain.AddChild(legend);
|
||||
_graph.IndustryClicked += Select;
|
||||
chain.AddChild(_graph);
|
||||
chain.AddChild(_chainFooter);
|
||||
_buyStatus.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
chain.AddChild(_buyStatus);
|
||||
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
|
||||
var plants = PanelKit.Column(10);
|
||||
plants.AddChild(_plants);
|
||||
plants.AddChild(_controls);
|
||||
plants.AddChild(_history);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
_list.ItemSelected += i => Select(_ids[(int)i]);
|
||||
plants.AddChild(_status);
|
||||
lower.AddChild(Card(T("Impianti e crescita"), plants, 1));
|
||||
body.AddChild(lower);
|
||||
|
||||
RefreshList();
|
||||
}
|
||||
|
||||
/// <summary>Scheda con titolo e contenuto, larga in proporzione al rapporto dato.</summary>
|
||||
private static PanelContainer Card(string title, Control content, float ratio)
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 22));
|
||||
var col = PanelKit.Column(12);
|
||||
col.AddChild(UiTheme.Text(title, 19, bold: true));
|
||||
col.AddChild(content);
|
||||
card.AddChild(col);
|
||||
return card;
|
||||
}
|
||||
|
||||
/// <summary>Industria mostrata (−1 se nessuna).</summary>
|
||||
public int Industry => _industry;
|
||||
|
||||
@@ -60,11 +161,20 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (id == _industry) return;
|
||||
_industry = id;
|
||||
_status.Text = "";
|
||||
_buyStatus.Text = "";
|
||||
_scroll.ScrollVertical = 0;
|
||||
SyncSelection();
|
||||
Request();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Scorre il corpo della scheda (0 in cima, 1 in fondo).</summary>
|
||||
public void ScrollTo(double fraction)
|
||||
{
|
||||
var bar = _scroll.GetVScrollBar();
|
||||
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
|
||||
}
|
||||
|
||||
private void Request()
|
||||
{
|
||||
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
|
||||
@@ -84,10 +194,12 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
private void Result(CommandResultMessage r) => Show(_status, r);
|
||||
|
||||
private void Show(Label label, CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
label.Text = r.Message;
|
||||
label.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
Request();
|
||||
}
|
||||
|
||||
@@ -98,10 +210,17 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (w.EntityVersion != _entityVersion) RefreshList();
|
||||
_entityVersion = w.EntityVersion;
|
||||
_detailVersion = w.DetailVersion;
|
||||
foreach (var c in _header.GetChildren()) c.QueueFree();
|
||||
foreach (var c in _details.GetChildren()) c.QueueFree();
|
||||
foreach (var box in new[] { _notices, _inputs, _workforce, _production, _chainFooter, _plants, _history })
|
||||
foreach (var c in box.GetChildren()) c.QueueFree();
|
||||
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
|
||||
{
|
||||
_title.Text = T("Industrie");
|
||||
_subtitle.Text = T("Scegli un'industria nell'elenco in alto.");
|
||||
_ownerLine.Text = "";
|
||||
_valuation.Text = "";
|
||||
_limit.Text = "";
|
||||
_ring.Set(0, Palette.Amber);
|
||||
_graph.Visible = false;
|
||||
BuildControls(null);
|
||||
return;
|
||||
}
|
||||
@@ -109,12 +228,24 @@ public partial class IndustryPanel : VBoxContainer
|
||||
BuildHeader(w, ind, card);
|
||||
BuildControls(ind);
|
||||
UpdateControls(ind, card);
|
||||
BuildDetails(w, ind, card);
|
||||
var sheet = card?.Sheet;
|
||||
if (card is null || sheet is null)
|
||||
{
|
||||
_graph.Visible = false;
|
||||
foreach (var box in new[] { _inputs, _workforce, _production, _plants })
|
||||
box.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
BuildInputs(w, sheet);
|
||||
BuildWorkforce(w, sheet);
|
||||
BuildProduction(w, card, sheet);
|
||||
BuildChain(w, ind, card, sheet);
|
||||
BuildPlants(w, ind, card, sheet);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ elenco
|
||||
|
||||
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
|
||||
/// <summary>Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
|
||||
private void RefreshList()
|
||||
{
|
||||
var w = _session.World;
|
||||
@@ -126,7 +257,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (!same)
|
||||
{
|
||||
_ids.Clear();
|
||||
_list.Clear();
|
||||
_chooser.Clear();
|
||||
}
|
||||
for (int n = 0; n < ordered.Count; n++)
|
||||
{
|
||||
@@ -137,13 +268,12 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (!same)
|
||||
{
|
||||
_ids.Add(ind.Id);
|
||||
_list.AddItem(text);
|
||||
_chooser.AddItem(text, n);
|
||||
}
|
||||
else if (_list.GetItemText(n) != text)
|
||||
else if (_chooser.GetItemText(n) != text)
|
||||
{
|
||||
_list.SetItemText(n, text);
|
||||
_chooser.SetItemText(n, text);
|
||||
}
|
||||
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
|
||||
}
|
||||
if (!same) SyncSelection();
|
||||
}
|
||||
@@ -151,175 +281,374 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private void SyncSelection()
|
||||
{
|
||||
int index = _ids.IndexOf(_industry);
|
||||
if (index < 0)
|
||||
{
|
||||
_list.DeselectAll();
|
||||
return;
|
||||
}
|
||||
if (!_list.IsSelected(index)) _list.Select(index);
|
||||
_list.EnsureCurrentIsVisible();
|
||||
if (index >= 0 && _chooser.Selected != index) _chooser.Select(index);
|
||||
if (index < 0) _chooser.Select(-1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ scheda
|
||||
// ------------------------------------------------------------------ intestazione
|
||||
|
||||
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
|
||||
{
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
var title = UiTheme.TitleLabel(ind.Name, 30);
|
||||
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_header.AddChild(title);
|
||||
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
|
||||
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
|
||||
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
|
||||
var sheet = card?.Sheet;
|
||||
_title.Text = ind.Name;
|
||||
string level = sheet is null ? $"{T("Livello")} {ind.Level}" : $"{T("Livello")} {sheet.Level} {T("di")} {sheet.MaxLevel}";
|
||||
_subtitle.Text = $"{TypeName(w, ind.Type)} · {level}";
|
||||
string owner = ind.Owner == me ? T("la tua compagnia") : ind.Owner < 0 ? T("proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
string served = "";
|
||||
if (sheet is not null)
|
||||
{
|
||||
var names = sheet.ServingStations.Select(s => w.Stations.TryGetValue(s, out var st) ? st.Name : $"#{s}").Take(3).ToList();
|
||||
served = names.Count == 0
|
||||
? " · " + T("nessuna stazione la serve")
|
||||
: $" · {T("servita dalla stazione")} {string.Join(", ", names)}" +
|
||||
(sheet.ServingLine >= 0 && w.Lines.TryGetValue(sheet.ServingLine, out var line) ? $" ({T("linea")} {line.Name})" : "");
|
||||
}
|
||||
_ownerLine.Text = $"{T("Proprietà")}: {owner}{served}";
|
||||
_valuation.Text = card?.Valuation.ToString() ?? "—";
|
||||
float e = sheet?.Efficiency ?? ind.Efficiency;
|
||||
var limit = sheet is null ? IndustryLimit.None : (IndustryLimit)sheet.Limit;
|
||||
_ring.Set(e, limit is IndustryLimit.None ? Palette.Ok : e < 0.35f ? Palette.Danger : Palette.Amber);
|
||||
_limit.Text = sheet is null ? T("Efficienza") : $"{T("Efficienza")} · {LimitText(limit)}";
|
||||
|
||||
long today = Fmt.Today(w);
|
||||
if (ind.StoppedUntilDay >= today)
|
||||
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
|
||||
_notices.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
|
||||
else if (ind.PendingWork != 0)
|
||||
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
|
||||
_notices.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
|
||||
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
|
||||
if (ind.PartsShort)
|
||||
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
|
||||
|
||||
var stats = PanelKit.Row(8);
|
||||
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
|
||||
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
|
||||
_header.AddChild(stats);
|
||||
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
_header.AddChild(bar);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
|
||||
_notices.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
|
||||
}
|
||||
|
||||
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
|
||||
// ------------------------------------------------------------------ tre schede
|
||||
|
||||
private void BuildInputs(ClientWorld w, IndustrySheetInfo s)
|
||||
{
|
||||
if (s.Inputs.Count == 0)
|
||||
{
|
||||
_inputs.AddChild(Wrapped(T("Non consuma materie prime: estrae, coltiva o raccoglie da sé."), 13, Palette.TextSecondary));
|
||||
}
|
||||
foreach (var f in s.Inputs)
|
||||
{
|
||||
string unit = Unit(w, f.Good);
|
||||
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
|
||||
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_inputs.AddChild(Wrapped($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, unit, supplier: true));
|
||||
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
|
||||
_inputs.AddChild(PanelKit.Separator());
|
||||
}
|
||||
if (s.Inputs.Count > 0)
|
||||
_inputs.AddChild(PanelKit.Pair($"{T("Copertura degli ingressi")} ({s.CoverageWindowDays} {T("giorni")})", ColoredValue(Fmt.Pct(s.CovInput, 0), CoverageColor(s.CovInput))));
|
||||
}
|
||||
|
||||
private void BuildWorkforce(ClientWorld w, IndustrySheetInfo s)
|
||||
{
|
||||
WorkforceBlock(w, s.Workers, s.CovWorkers, s.CoverageWindowDays, staff: false);
|
||||
_workforce.AddChild(PanelKit.Separator());
|
||||
WorkforceBlock(w, s.Staff, s.CovStaff, s.CoverageWindowDays, staff: true);
|
||||
var limit = (IndustryLimit)s.Limit;
|
||||
if (limit is IndustryLimit.Workers or IndustryLimit.Staff)
|
||||
{
|
||||
var wf = limit == IndustryLimit.Staff ? s.Staff : s.Workers;
|
||||
string who = limit == IndustryLimit.Staff ? T("il personale qualificato") : T("i lavoratori");
|
||||
_workforce.AddChild(UiTheme.Notice($"{T("Collo di bottiglia")}: {who}. {T("Mancano")} {wf.Missing} {T("persone: portale in treno dalle città vicine.")}"));
|
||||
}
|
||||
}
|
||||
|
||||
private void WorkforceBlock(ClientWorld w, WorkforceInfo f, float coverage30, int window, bool staff)
|
||||
{
|
||||
var color = staff ? Palette.Staff : Palette.Workers;
|
||||
if (f.Jobs <= 0)
|
||||
{
|
||||
_workforce.AddChild(UiTheme.Text(staff ? T("Nessun posto per il personale") : T("Nessun posto per i lavoratori"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
|
||||
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
|
||||
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
|
||||
// OnSite sono i posti coperti da chi vive negli alloggi dell'industria, non i presenti
|
||||
_workforce.AddChild(Wrapped($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("in sede")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||
if (f.Missing > 0)
|
||||
{
|
||||
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
|
||||
_workforce.AddChild(Wrapped($"{T("Mancano")} {f.Missing}" + (reason.Length > 0 ? " · " + reason : ""), 12, Palette.Amber));
|
||||
}
|
||||
foreach (var src in f.Sources)
|
||||
{
|
||||
string town = w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}";
|
||||
string via = src.Walking ? T("a piedi") : src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var line) ? line.Name : Fmt.Company(w, src.Carrier);
|
||||
string time = src.Walking || src.Minutes <= 0 ? "" : $" · {Fmt.Number(src.Minutes, 0)} min";
|
||||
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
|
||||
}
|
||||
if (f.SourceCount > f.Sources.Count)
|
||||
_workforce.AddChild(Wrapped($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
foreach (var f in s.Outputs)
|
||||
{
|
||||
string unit = Unit(w, f.Good);
|
||||
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
|
||||
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_production.AddChild(Wrapped($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, unit, supplier: false));
|
||||
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Separator());
|
||||
}
|
||||
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
|
||||
_production.AddChild(PanelKit.Pair(T("Prezzo di vendita"), PanelKit.Value(s.SalePrice < 0 ? "—" : Fmt.PricePrecise(s.SalePrice))));
|
||||
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
|
||||
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ catena produttiva
|
||||
|
||||
private void BuildChain(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
var left = new List<ChainNode>();
|
||||
foreach (var f in s.Inputs)
|
||||
foreach (var p in f.Partners.Take(2))
|
||||
left.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.Number(p.MonthlyUnits, 0)} {Unit(w, f.Good)}/{T("mese")}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||
foreach (var (wf, staff) in new[] { (s.Workers, false), (s.Staff, true) })
|
||||
foreach (var src in wf.Sources.Take(staff ? 1 : 2))
|
||||
left.Add(new ChainNode(w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}",
|
||||
$"{src.Headcount} {(staff ? T("tecnici") : T("lavoratori"))}", staff ? ChainEdge.Staff : ChainEdge.Workers));
|
||||
var right = new List<ChainNode>();
|
||||
foreach (var f in s.Outputs)
|
||||
foreach (var p in f.Partners.Take(3))
|
||||
right.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.PricePrecise(p.Price)}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||
string outputs = string.Join(", ", s.Outputs.Select(f => GoodName(w, f.Good)));
|
||||
_graph.Set(left, new ChainNode(ind.Name, $"{T("Livello")} {s.Level} · {outputs}", ChainEdge.Goods), right);
|
||||
_graph.Visible = true;
|
||||
|
||||
// azioni della catena: linea verso l'industria e offerta di acquisto
|
||||
var actions = PanelKit.Row(10);
|
||||
var plan = UiTheme.Primary(T("Crea una linea verso questa industria"));
|
||||
plan.CustomMinimumSize = new Vector2(0, 44);
|
||||
int id = ind.Id;
|
||||
plan.Pressed += () => PlanLineRequested?.Invoke(id);
|
||||
actions.AddChild(plan);
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
if (ind.Owner != me)
|
||||
{
|
||||
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
|
||||
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
|
||||
buy.Pressed += () =>
|
||||
{
|
||||
_buyStatus.Text = T("Offerta inviata…");
|
||||
_buyStatus.AddThemeColorOverride("font_color", Palette.TextSecondary);
|
||||
_session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), r => Show(_buyStatus, r));
|
||||
};
|
||||
actions.AddChild(buy);
|
||||
}
|
||||
_chainFooter.AddChild(actions);
|
||||
if (ind.Owner == me)
|
||||
_chainFooter.AddChild(Wrapped(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||
else if (ind.Owner < 0 && !s.ForSale)
|
||||
_chainFooter.AddChild(Wrapped(T("Industria inattiva: non è in vendita finché non riprende a produrre."), 12, Palette.TextSecondary));
|
||||
else if (!s.ForSale)
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
|
||||
else if (!s.BuyUnlocked)
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Disponibile al livello")} «{Fmt.Tier(w, s.BuyTier)}» ({T("avanzamento")} {Fmt.Progress(s.BuyProgress)})", 12, Palette.TextSecondary));
|
||||
else
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Prezzo chiesto dai proprietari")}: {card.Valuation}", 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ impianti e crescita
|
||||
|
||||
private void BuildPlants(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||
{
|
||||
var condColor = MaintenancePanel.ConditionColor((int)ind.Condition);
|
||||
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
|
||||
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
|
||||
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||
_plants.AddChild(Wrapped($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
|
||||
if (s.ReserveFraction >= 0)
|
||||
_plants.AddChild(PanelKit.Pair(T("Giacimento residuo"), ColoredValue(Fmt.Pct(s.ReserveFraction, 0), s.Depletion < 1 ? Palette.Amber : Palette.Text)));
|
||||
if (s.EventCapacity < 1) _plants.AddChild(PanelKit.Pair(T("Capacità ridotta da un evento"), ColoredValue("×" + Fmt.Number(s.EventCapacity, 2), Palette.Amber)));
|
||||
|
||||
// crescita trimestrale: punteggio in corso, soglie, componenti
|
||||
_plants.AddChild(PanelKit.Separator());
|
||||
_plants.AddChild(FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}"));
|
||||
var bar = new ScoreBar();
|
||||
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
|
||||
_plants.AddChild(bar);
|
||||
_plants.AddChild(Wrapped($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
|
||||
var g = w.Data.Balance.Growth;
|
||||
_plants.AddChild(Wrapped($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
|
||||
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
|
||||
if (!s.Served)
|
||||
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
|
||||
else if (s.Level >= s.MaxLevel)
|
||||
_plants.AddChild(UiTheme.Text(T("Livello massimo raggiunto"), 12, Palette.Ok));
|
||||
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
if (ind.Owner == me)
|
||||
{
|
||||
_plants.AddChild(PanelKit.Separator());
|
||||
_plants.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||
_plants.AddChild(Wrapped($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||
}
|
||||
|
||||
_history.AddChild(PanelKit.Separator());
|
||||
_history.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
|
||||
if (card.Stops.Count == 0) _history.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
|
||||
foreach (var stop in Enumerable.Reverse(card.Stops).Take(6))
|
||||
_history.AddChild(UiTheme.Text($"{Fmt.Date(w, stop.Day)} · {StopName(stop.Kind)} · {stop.Days} {T("giorni")}", 13, stop.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary));
|
||||
}
|
||||
|
||||
/// <summary>Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
|
||||
private void BuildControls(IndustryInfo? ind)
|
||||
{
|
||||
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
|
||||
int me = _session.World.Summary?.CompanyId ?? 0;
|
||||
var key = ind is null || ind.Owner != me ? (-1, -1) : (ind.Id, ind.Owner);
|
||||
if (key == _controlsKey) return;
|
||||
_controlsKey = key;
|
||||
foreach (var c in _controls.GetChildren()) c.QueueFree();
|
||||
_budgetButtons.Clear();
|
||||
_partsOrder = null;
|
||||
if (ind is null) return;
|
||||
_overhaul = _upgrade = null;
|
||||
if (ind is null || ind.Owner != me) return;
|
||||
var w = _session.World;
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
int id = ind.Id;
|
||||
if (ind.Owner == me)
|
||||
_controls.AddChild(PanelKit.Separator());
|
||||
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
|
||||
var row = PanelKit.Row(6);
|
||||
var group = new ButtonGroup();
|
||||
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
|
||||
{
|
||||
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
|
||||
var row = PanelKit.Row(6);
|
||||
var group = new ButtonGroup();
|
||||
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.For(budget);
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
|
||||
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
|
||||
_budgetButtons.Add(b);
|
||||
row.AddChild(b);
|
||||
}
|
||||
_controls.AddChild(row);
|
||||
var p = w.Data.Balance.IndustryMaintenance.For(budget);
|
||||
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
|
||||
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
|
||||
_budgetButtons.Add(b);
|
||||
row.AddChild(b);
|
||||
}
|
||||
_controls.AddChild(row);
|
||||
|
||||
var order = PanelKit.Row(6);
|
||||
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
|
||||
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
|
||||
caption.MouseFilter = MouseFilterEnum.Pass;
|
||||
order.AddChild(caption);
|
||||
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
order.AddChild(_partsOrder);
|
||||
var orderButton = new Button { Text = T("Ordina ricambi") };
|
||||
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
|
||||
order.AddChild(orderButton);
|
||||
_controls.AddChild(order);
|
||||
var order = PanelKit.Row(6);
|
||||
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
|
||||
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
|
||||
caption.MouseFilter = MouseFilterEnum.Pass;
|
||||
order.AddChild(caption);
|
||||
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
order.AddChild(_partsOrder);
|
||||
var orderButton = new Button { Text = T("Ordina ricambi") };
|
||||
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
|
||||
order.AddChild(orderButton);
|
||||
_controls.AddChild(order);
|
||||
|
||||
var actions = PanelKit.Row(6);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||
actions.AddChild(overhaul);
|
||||
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||
actions.AddChild(upgrade);
|
||||
_controls.AddChild(actions);
|
||||
}
|
||||
else if (ind.Owner < 0)
|
||||
{
|
||||
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
|
||||
var price = PanelKit.Value("—");
|
||||
price.Name = "Price";
|
||||
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
|
||||
var buy = UiTheme.Primary(T("Acquista"));
|
||||
buy.Pressed += () =>
|
||||
{
|
||||
if (_session.World.IndustryCards.TryGetValue(id, out var c))
|
||||
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
|
||||
else
|
||||
Request();
|
||||
};
|
||||
_controls.AddChild(buy);
|
||||
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
|
||||
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
|
||||
}
|
||||
else
|
||||
{
|
||||
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
|
||||
}
|
||||
var actions = PanelKit.Row(6);
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||
overhaul.SetMeta(BaseTooltip, overhaul.TooltipText);
|
||||
actions.AddChild(overhaul);
|
||||
_overhaul = overhaul;
|
||||
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||
upgrade.SetMeta(BaseTooltip, upgrade.TooltipText);
|
||||
actions.AddChild(upgrade);
|
||||
_upgrade = upgrade;
|
||||
_controls.AddChild(actions);
|
||||
}
|
||||
|
||||
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
|
||||
{
|
||||
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
|
||||
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
|
||||
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
|
||||
|
||||
// revisione e ammodernamento: il server li rifiuta durante un fermo, con un lavoro già in
|
||||
// programma o (l'ammodernamento) al livello massimo; il pulsante lo dice prima
|
||||
string busy = ind.StoppedUntilDay >= Fmt.Today(_session.World) ? T("L'industria è ferma: riprova a fermo finito.")
|
||||
: ind.PendingWork != 0 ? T("C'è già un lavoro in programma.") : "";
|
||||
var sheet = card?.Sheet;
|
||||
string top = sheet is not null && sheet.Level >= sheet.MaxLevel ? T("Livello massimo raggiunto") : "";
|
||||
Gate(_overhaul, busy);
|
||||
Gate(_upgrade, busy.Length > 0 ? busy : top);
|
||||
}
|
||||
|
||||
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
|
||||
private const string BaseTooltip = "base_tooltip";
|
||||
|
||||
/// <summary>Abilita il pulsante, o lo disabilita con il motivo in testa al suggerimento.</summary>
|
||||
private static void Gate(Button? button, string reason)
|
||||
{
|
||||
if (card is null)
|
||||
{
|
||||
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
|
||||
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
|
||||
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
|
||||
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||
|
||||
if (ind.Owner == me)
|
||||
{
|
||||
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||
}
|
||||
|
||||
_details.AddChild(PanelKit.Separator());
|
||||
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
|
||||
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
|
||||
|
||||
_details.AddChild(PanelKit.Separator());
|
||||
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
|
||||
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
|
||||
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
|
||||
{
|
||||
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
|
||||
_details.AddChild(l);
|
||||
}
|
||||
if (button is null) return;
|
||||
button.Disabled = reason.Length > 0;
|
||||
string tip = button.GetMeta(BaseTooltip, "").AsString();
|
||||
button.TooltipText = reason.Length > 0 ? reason + "\n" + tip : tip;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pezzi
|
||||
|
||||
private static HBoxContainer FlowHeader(string name, string value, Color? color = null)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var l = UiTheme.Text(name, 15, color, bold: true);
|
||||
l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
row.AddChild(l);
|
||||
row.AddChild(UiTheme.Text(value, 14, bold: true));
|
||||
return row;
|
||||
}
|
||||
|
||||
private static ProgressBar Bar(float fraction, Color color)
|
||||
{
|
||||
var bar = new ProgressBar { MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
return bar;
|
||||
}
|
||||
|
||||
private static Control PartnerLine(ClientWorld w, ChainPartnerInfo p, string unit, bool supplier)
|
||||
{
|
||||
string link = p.Line >= 0 && w.Lines.TryGetValue(p.Line, out var line)
|
||||
? $"{T("linea")} {line.Name}"
|
||||
: $"{T("non collegata")} · {Fmt.Number(p.DistanceKm, 1)} km";
|
||||
string amount = (ChainPartnerKind)p.Kind == ChainPartnerKind.Hub ? "" : $" · {Fmt.Number(p.MonthlyUnits, 0)} {unit}/{T("mese")}";
|
||||
string text = $"{(supplier ? "←" : "→")} {PartnerName(w, p)}{amount} · {Fmt.PricePrecise(p.Price)} · {link}";
|
||||
return Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
|
||||
}
|
||||
|
||||
private static string PartnerName(ClientWorld w, ChainPartnerInfo p) => (ChainPartnerKind)p.Kind switch
|
||||
{
|
||||
ChainPartnerKind.Industry => w.Industries.TryGetValue(p.Target, out var i) ? i.Name : $"#{p.Target}",
|
||||
ChainPartnerKind.Hub => w.Hubs.TryGetValue(p.Target, out var h) ? h.Name : $"#{p.Target}",
|
||||
_ => w.Towns.TryGetValue(p.Target, out var t) ? t.Name : $"#{p.Target}",
|
||||
};
|
||||
|
||||
private static int PartnerIndustry(ChainPartnerInfo p) => (ChainPartnerKind)p.Kind == ChainPartnerKind.Industry ? p.Target : -1;
|
||||
|
||||
private static bool English => TranslationServer.GetLocale().StartsWith("en");
|
||||
|
||||
private static string GoodName(ClientWorld w, int good) =>
|
||||
good >= 0 && good < w.Data.Goods.Count ? (English ? w.Data.Goods[good].NameEn : w.Data.Goods[good].NameIt) : $"#{good}";
|
||||
|
||||
private static string Unit(ClientWorld w, int good) => good >= 0 && good < w.Data.Goods.Count ? w.Data.Goods[good].Unit : "";
|
||||
|
||||
private static string TypeName(ClientWorld w, string type)
|
||||
{
|
||||
var def = w.Data.Industries.FirstOrDefault(d => d.Id == type);
|
||||
return def is null ? type : English ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
private static Color CoverageColor(float coverage) => coverage >= 0.9f ? Palette.Ok : coverage >= 0.5f ? Palette.Amber : Palette.Danger;
|
||||
|
||||
private static Control StockRow(string caption, int have, int target, Color color)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
@@ -335,6 +664,21 @@ public partial class IndustryPanel : VBoxContainer
|
||||
|
||||
// ------------------------------------------------------------------ testi
|
||||
|
||||
/// <summary>Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.</summary>
|
||||
public static string LimitText(IndustryLimit limit) => limit switch
|
||||
{
|
||||
IndustryLimit.None => T("a piena capacità"),
|
||||
IndustryLimit.Inputs => T("limitata dalle materie prime"),
|
||||
IndustryLimit.Workers => T("limitata dai lavoratori"),
|
||||
IndustryLimit.Staff => T("limitata dal personale"),
|
||||
IndustryLimit.Profit => T("limitata dalla redditività"),
|
||||
IndustryLimit.Condition => T("limitata dagli impianti"),
|
||||
IndustryLimit.Depletion => T("limitata dal giacimento"),
|
||||
IndustryLimit.Event => T("limitata da un evento"),
|
||||
IndustryLimit.Stopped => T("ferma"),
|
||||
_ => T("inattiva"),
|
||||
};
|
||||
|
||||
public static string StopName(byte kind) => kind switch
|
||||
{
|
||||
1 => T("Guasto"),
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.</summary>
|
||||
public partial class EfficiencyRing : Control
|
||||
{
|
||||
private float _value;
|
||||
private Color _color = Palette.Amber;
|
||||
|
||||
public EfficiencyRing() => CustomMinimumSize = new Vector2(112, 112);
|
||||
|
||||
public void Set(float value, Color color)
|
||||
{
|
||||
_value = Math.Clamp(value, 0, 1);
|
||||
_color = color;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
var c = Size / 2;
|
||||
float r = Math.Min(Size.X, Size.Y) / 2 - 8;
|
||||
DrawArc(c, r, 0, Mathf.Tau, 64, Palette.Inner, 10, true);
|
||||
if (_value > 0) DrawArc(c, r, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * _value, 64, _color, 10, true);
|
||||
string text = Fmt.Pct(_value, 0);
|
||||
var font = UiTheme.BodyBold;
|
||||
const int size = 24;
|
||||
var s = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
|
||||
DrawString(font, new Vector2(c.X - s.X / 2, c.Y + s.Y / 4), text, HorizontalAlignment.Left, -1, size, Palette.Text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Barra del punteggio di crescita: il riempimento è il punteggio del trimestre in corso, le tacche
|
||||
/// sono le soglie di declassamento (rossa) e di promozione (verde), la lineetta l'ultimo trimestre.
|
||||
/// </summary>
|
||||
public partial class ScoreBar : Control
|
||||
{
|
||||
private float _score, _last = -1, _down, _up;
|
||||
|
||||
public ScoreBar() => CustomMinimumSize = new Vector2(0, 26);
|
||||
|
||||
public void Set(float score, float last, float down, float up)
|
||||
{
|
||||
(_score, _last, _down, _up) = (Math.Clamp(score, 0, 1), last, down, up);
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
float h = 12, y = 7, w = Size.X;
|
||||
DrawRect(new Rect2(0, y, w, h), Palette.Inner);
|
||||
var fill = _score >= _up ? Palette.Ok : _score < _down ? Palette.Danger : Palette.Amber;
|
||||
DrawRect(new Rect2(0, y, w * _score, h), fill);
|
||||
DrawLine(new Vector2(w * _down, 2), new Vector2(w * _down, y + h + 5), Palette.Danger, 2);
|
||||
DrawLine(new Vector2(w * _up, 2), new Vector2(w * _up, y + h + 5), Palette.Ok, 2);
|
||||
if (_last >= 0) DrawLine(new Vector2(w * Math.Clamp(_last, 0, 1), y - 3), new Vector2(w * Math.Clamp(_last, 0, 1), y + h + 3), Palette.Text, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).</summary>
|
||||
public enum ChainEdge
|
||||
{
|
||||
/// <summary>Merci su una linea della compagnia: linea piena ambra.</summary>
|
||||
Goods,
|
||||
/// <summary>Lavoratori pendolari: tratteggio blu.</summary>
|
||||
Workers,
|
||||
/// <summary>Personale qualificato: puntinato azzurro.</summary>
|
||||
Staff,
|
||||
/// <summary>Partner possibile ma non collegato: tratteggio grigio.</summary>
|
||||
Unlinked,
|
||||
}
|
||||
|
||||
/// <summary>Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).</summary>
|
||||
public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
|
||||
|
||||
/// <summary>
|
||||
/// Grafo della catena produttiva: fornitori e città dei pendolari a sinistra, l'industria al centro,
|
||||
/// clienti a destra. I nodi delle industrie si aprono con un clic.
|
||||
/// </summary>
|
||||
public partial class ChainGraph : Control
|
||||
{
|
||||
private const float NodeW = 210, NodeH = 50, Gap = 10;
|
||||
private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
|
||||
private List<ChainNode> _left = [], _right = [];
|
||||
private ChainNode? _center;
|
||||
|
||||
public event Action<int>? IndustryClicked;
|
||||
|
||||
public ChainGraph()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 260);
|
||||
MouseFilter = MouseFilterEnum.Stop;
|
||||
}
|
||||
|
||||
public void Set(List<ChainNode> left, ChainNode center, List<ChainNode> right)
|
||||
{
|
||||
(_left, _center, _right) = (left, center, right);
|
||||
int rows = Math.Max(3, Math.Max(left.Count, right.Count));
|
||||
CustomMinimumSize = new Vector2(0, rows * (NodeH + Gap) + 10);
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
_hits.Clear();
|
||||
if (_center is null) return;
|
||||
float w = Size.X, h = Size.Y;
|
||||
float nodeW = Math.Min(NodeW, (w - 80) / 3);
|
||||
var centerRect = new Rect2(w / 2 - nodeW / 2, h / 2 - NodeH * 0.7f, nodeW, NodeH * 1.4f);
|
||||
var leftRects = Column(_left, 0, nodeW, h);
|
||||
var rightRects = Column(_right, w - nodeW, nodeW, h);
|
||||
for (int i = 0; i < _left.Count; i++)
|
||||
Edge(new Vector2(leftRects[i].End.X, leftRects[i].GetCenter().Y), new Vector2(centerRect.Position.X, centerRect.GetCenter().Y), _left[i].Edge);
|
||||
for (int i = 0; i < _right.Count; i++)
|
||||
Edge(new Vector2(centerRect.End.X, centerRect.GetCenter().Y), new Vector2(rightRects[i].Position.X, rightRects[i].GetCenter().Y), _right[i].Edge);
|
||||
for (int i = 0; i < _left.Count; i++) Node(leftRects[i], _left[i], false);
|
||||
for (int i = 0; i < _right.Count; i++) Node(rightRects[i], _right[i], false);
|
||||
Node(centerRect, _center, true);
|
||||
}
|
||||
|
||||
private static List<Rect2> Column(List<ChainNode> nodes, float x, float width, float height)
|
||||
{
|
||||
float total = nodes.Count * NodeH + Math.Max(0, nodes.Count - 1) * Gap;
|
||||
float y = (height - total) / 2;
|
||||
var rects = new List<Rect2>(nodes.Count);
|
||||
foreach (var _ in nodes)
|
||||
{
|
||||
rects.Add(new Rect2(x, y, width, NodeH));
|
||||
y += NodeH + Gap;
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
private void Edge(Vector2 from, Vector2 to, ChainEdge edge)
|
||||
{
|
||||
switch (edge)
|
||||
{
|
||||
case ChainEdge.Goods:
|
||||
DrawLine(from, to, Palette.Amber, 3, true);
|
||||
break;
|
||||
case ChainEdge.Workers:
|
||||
DrawDashedLine(from, to, Palette.Workers, 2.5f, 10);
|
||||
break;
|
||||
case ChainEdge.Staff:
|
||||
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
|
||||
break;
|
||||
default:
|
||||
// grigio leggibile sul fondo della scheda (il bordo dei pannelli sparirebbe)
|
||||
DrawDashedLine(from, to, Palette.TextSecondary, 2, 8);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Node(Rect2 rect, ChainNode node, bool center)
|
||||
{
|
||||
bool unlinked = !center && node.Edge == ChainEdge.Unlinked;
|
||||
var border = center ? Palette.Amber : node.Edge switch
|
||||
{
|
||||
ChainEdge.Goods => Palette.AmberDark,
|
||||
ChainEdge.Workers => Palette.Workers,
|
||||
ChainEdge.Staff => Palette.Staff,
|
||||
_ => Palette.Inner,
|
||||
};
|
||||
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
|
||||
// partner non collegato: bordo tratteggiato grigio, come «Opportunità non collegata» nell'immagine 07
|
||||
if (unlinked) DashedRect(rect.Grow(-1), Palette.TextSecondary);
|
||||
var font = UiTheme.BodyBold;
|
||||
float width = rect.Size.X - 16;
|
||||
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
|
||||
center ? Palette.AmberLight : Palette.Text);
|
||||
DrawString(UiTheme.Body, rect.Position + new Vector2(8, center ? 48 : 39), node.Subtitle, HorizontalAlignment.Left, width, 12, Palette.TextSecondary);
|
||||
if (node.Industry >= 0) _hits.Add((rect, node));
|
||||
}
|
||||
|
||||
private void DashedRect(Rect2 r, Color color)
|
||||
{
|
||||
var (a, b, c, d) = (r.Position, new Vector2(r.End.X, r.Position.Y), r.End, new Vector2(r.Position.X, r.End.Y));
|
||||
DrawDashedLine(a, b, color, 1.5f, 6);
|
||||
DrawDashedLine(b, c, color, 1.5f, 6);
|
||||
DrawDashedLine(c, d, color, 1.5f, 6);
|
||||
DrawDashedLine(d, a, color, 1.5f, 6);
|
||||
}
|
||||
|
||||
public override void _GuiInput(InputEvent e)
|
||||
{
|
||||
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
|
||||
foreach (var (rect, node) in _hits)
|
||||
{
|
||||
if (!rect.HasPoint(click.Position)) continue;
|
||||
IndustryClicked?.Invoke(node.Industry);
|
||||
AcceptEvent();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
@@ -11,7 +12,8 @@ namespace RailEnterprise.Client.Panels;
|
||||
/// <summary>
|
||||
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
|
||||
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
|
||||
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
|
||||
/// la scorta di ricambi, rinnovo della flotta (ere e obsolescenza, ADR 0020). Le cartelle, i registri
|
||||
/// e il quadro della flotta arrivano su richiesta dal server: età, successori e valori non si calcolano qui.
|
||||
/// </summary>
|
||||
public partial class MaintenancePanel : VBoxContainer
|
||||
{
|
||||
@@ -29,12 +31,19 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
private readonly VBoxContainer _workshop = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
|
||||
private readonly HBoxContainer _orderRow = PanelKit.Row();
|
||||
private readonly VBoxContainer _fleet = PanelKit.Column(6);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly List<int> _trainIds = [];
|
||||
private readonly List<int> _depotIds = [];
|
||||
private int _train = -1, _depot = -1;
|
||||
private int _entityVersion = -1, _detailVersion = -1;
|
||||
private double _request;
|
||||
private long _fleetDay = long.MinValue;
|
||||
private double _sinceFleet = double.MaxValue;
|
||||
// quadro della flotta mostrato: la sezione si ricostruisce solo quando ne arriva uno nuovo, così i
|
||||
// pulsanti «Rinnova» non si ricreano sotto il cursore a ogni aggiornamento della cartella
|
||||
private FleetReport? _fleetShown;
|
||||
private bool _fleetBuilt;
|
||||
private bool _updating;
|
||||
|
||||
public event Action<bool>? HeatMapToggled;
|
||||
@@ -69,6 +78,9 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
AddChild(_workshop);
|
||||
AddChild(_workshopDetails);
|
||||
AddChild(_orderRow);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Rinnovo della flotta"), 14, bold: true));
|
||||
AddChild(_fleet);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
|
||||
@@ -113,10 +125,26 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
|
||||
}
|
||||
var w = _session.World;
|
||||
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
||||
_sinceFleet += delta;
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _fleetDay || (w.Fleet is null && _sinceFleet > 5)) RequestFleet(today);
|
||||
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r) => _status.Text = r.Message;
|
||||
private void RequestFleet(long day)
|
||||
{
|
||||
_fleetDay = day;
|
||||
_sinceFleet = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
// un rinnovo prenotato o completato cambia il quadro della flotta
|
||||
RequestFleet(Fmt.Today(_session.World));
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
@@ -160,6 +188,7 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
|
||||
BuildCard();
|
||||
BuildWorkshop();
|
||||
if (!_fleetBuilt || !ReferenceEquals(w.Fleet, _fleetShown)) BuildFleet();
|
||||
}
|
||||
|
||||
private string DueText(TrainInfo t)
|
||||
@@ -212,6 +241,12 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
{
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
|
||||
if (w.Fleet?.Vehicles.FirstOrDefault(f => f.Vehicle == v.Vehicle) is { } info)
|
||||
{
|
||||
var value = UiTheme.Text(VehicleOutlook(info), 12, info.Superseded ? Palette.Amber : Palette.TextSecondary);
|
||||
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_cardDetails.AddChild(value);
|
||||
}
|
||||
foreach (var c in v.Components)
|
||||
{
|
||||
var row = PanelKit.Row(6);
|
||||
@@ -261,8 +296,98 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
actions.AddChild(b);
|
||||
}
|
||||
_cardControls.AddChild(actions);
|
||||
// rinnovo: l'intervento con effetto «renew» dei dati, vende i veicoli superati e compra i successori
|
||||
if (w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Effect == InterventionEffect.Renew) is { } renewal)
|
||||
{
|
||||
var renew = new Button { Text = renewal.NameIt };
|
||||
renew.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), renewal.Id), Result);
|
||||
_cardControls.AddChild(renew);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ rinnovo della flotta
|
||||
|
||||
/// <summary>Riga di obsolescenza di un veicolo: superato, successore con prestazioni e prezzo, valori, costo di manutenzione.</summary>
|
||||
private string VehicleOutlook(FleetVehicleInfo v)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (v.Superseded)
|
||||
{
|
||||
parts.Add(string.Format(T("superato dal {0}"), v.SupersededYear));
|
||||
var next = _session.World.Data.Vehicles.FirstOrDefault(d => d.Id == v.Successor);
|
||||
if (next is not null)
|
||||
parts.Add(string.Format(T("successore {0} ({1} kW, {2} km/h, {3})"), next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
||||
}
|
||||
if (!v.InProduction) parts.Add(T("fuori produzione"));
|
||||
parts.Add(string.Format(T("valore {0}"), v.BookValue));
|
||||
parts.Add(string.Format(T("rivendita {0}"), v.Resale));
|
||||
if (v.MaintenanceFactor > 1.001f) parts.Add(string.Format(T("manutenzione ×{0:0.##}"), v.MaintenanceFactor));
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
|
||||
private void BuildFleet()
|
||||
{
|
||||
foreach (var c in _fleet.GetChildren()) c.QueueFree();
|
||||
var w = _session.World;
|
||||
var report = w.Fleet;
|
||||
_fleetShown = report;
|
||||
_fleetBuilt = true;
|
||||
if (report is null)
|
||||
{
|
||||
_fleet.AddChild(UiTheme.Text(T("Quadro della flotta in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
_fleet.AddChild(PanelKit.Pair(T("Era"), PanelKit.Value(EraName(report.Era))));
|
||||
if (report.NextEra.Length > 0)
|
||||
_fleet.AddChild(PanelKit.Pair(T("Prossima era"), PanelKit.Value($"{EraName(report.NextEra)} · {report.NextEraYear}")));
|
||||
_fleet.AddChild(PanelKit.Pair(T("Valore della flotta"), PanelKit.Value(report.BookValueTotal.ToString())));
|
||||
var superseded = report.Vehicles.Where(v => v.Superseded).ToList();
|
||||
if (superseded.Count == 0)
|
||||
{
|
||||
_fleet.AddChild(UiTheme.Text(T("Nessun veicolo superato"), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
foreach (var v in superseded.Take(8))
|
||||
{
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
string where = v.Train >= 0 && w.Trains.TryGetValue(v.Train, out var t) ? t.Name
|
||||
: v.Depot >= 0 && w.Depots.TryGetValue(v.Depot, out var d) ? d.Name : "";
|
||||
_fleet.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {where} · {v.AgeYears:0.#}/{v.LifeYears} {T("anni")}", 13, bold: true));
|
||||
var line = UiTheme.Text(VehicleOutlook(v), 12, Palette.Amber);
|
||||
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_fleet.AddChild(line);
|
||||
}
|
||||
if (superseded.Count > 8)
|
||||
_fleet.AddChild(UiTheme.Text(string.Format(T("e altri {0} veicoli superati"), superseded.Count - 8), 12, Palette.TextSecondary));
|
||||
foreach (var r in report.Trains)
|
||||
{
|
||||
string name = w.Trains.TryGetValue(r.Train, out var t) ? t.Name : $"#{r.Train}";
|
||||
var row = PanelKit.Row(6);
|
||||
var text = UiTheme.Text(string.Format(T("{0}: {1} veicoli da rinnovare, spesa netta {2}"), name, r.Vehicles, r.NetCost), 13,
|
||||
r.Affordable ? Palette.Text : Palette.Danger);
|
||||
text.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
row.AddChild(text);
|
||||
if (r.Booked)
|
||||
{
|
||||
// rinnovo già prenotato: niente pulsante, ripremerlo rifarebbe la prenotazione
|
||||
row.AddChild(UiTheme.Text(T("rinnovo prenotato"), 13, Palette.TextSecondary));
|
||||
}
|
||||
else
|
||||
{
|
||||
int train = r.Train;
|
||||
string intervention = report.RenewalIntervention;
|
||||
var button = new Button { Text = T("Rinnova") };
|
||||
button.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
||||
row.AddChild(button);
|
||||
}
|
||||
_fleet.AddChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Nome italiano dell'era dal suo id in eras.json (il quadro della flotta manda l'id).</summary>
|
||||
private string EraName(string id) => _session.World.Data.Eras.Eras.FirstOrDefault(e => e.Id == id)?.NameIt ?? id;
|
||||
|
||||
// ------------------------------------------------------------------ registro officina
|
||||
|
||||
private void BuildWorkshop()
|
||||
|
||||
@@ -11,8 +11,11 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
|
||||
/// Ogni azione è un comando; la lista si aggiorna con i delta del server.
|
||||
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro, vendita
|
||||
/// dei veicoli liberi e rinnovo dei treni con veicoli superati. Ogni azione è un comando; la lista si
|
||||
/// aggiorna con i delta del server. Catalogo, obsolescenza, successori e valori di rivendita vengono dal
|
||||
/// quadro della flotta (FleetReport, ADR 0020), chiesto all'apertura, a ogni nuovo giorno e dopo i comandi:
|
||||
/// il pannello non calcola nulla.
|
||||
/// </summary>
|
||||
public partial class TrainsPanel : VBoxContainer
|
||||
{
|
||||
@@ -20,10 +23,12 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private readonly OptionButton _depot = new();
|
||||
private readonly OptionButton _vehicle = new();
|
||||
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
|
||||
private readonly Label _modelInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly ItemList _inDepot = new() { SelectMode = ItemList.SelectModeEnum.Multi, CustomMinimumSize = new Vector2(0, 120) };
|
||||
private readonly LineEdit _name = new() { PlaceholderText = T("Nome del treno") };
|
||||
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 140) };
|
||||
private readonly OptionButton _line = new();
|
||||
private readonly Label _renewInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly List<int> _depotIds = [];
|
||||
private readonly List<VehicleDef> _catalog = [];
|
||||
@@ -31,6 +36,9 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private readonly List<int> _trainIds = [];
|
||||
private readonly List<int> _lineIds = [];
|
||||
private int _version = -1;
|
||||
private FleetReport? _fleetShown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action<int>? TrainSelected;
|
||||
|
||||
@@ -51,6 +59,8 @@ public partial class TrainsPanel : VBoxContainer
|
||||
buy.AddChild(_vehicle);
|
||||
buy.AddChild(_count);
|
||||
AddChild(buy);
|
||||
_modelInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_modelInfo);
|
||||
var buyButton = UiTheme.Primary(T("Compra veicoli"));
|
||||
buyButton.Pressed += Buy;
|
||||
AddChild(buyButton);
|
||||
@@ -64,6 +74,9 @@ public partial class TrainsPanel : VBoxContainer
|
||||
composeButton.Pressed += Compose;
|
||||
compose.AddChild(composeButton);
|
||||
ComposeButton = composeButton;
|
||||
var sellButton = new Button { Text = T("Vendi") };
|
||||
sellButton.Pressed += Sell;
|
||||
compose.AddChild(sellButton);
|
||||
AddChild(compose);
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
|
||||
@@ -79,15 +92,38 @@ public partial class TrainsPanel : VBoxContainer
|
||||
var home = new Button { Text = T("Manda al deposito") };
|
||||
home.Pressed += SendHome;
|
||||
AddChild(home);
|
||||
var renew = new Button { Text = T("Rinnova i veicoli superati") };
|
||||
renew.Pressed += Renew;
|
||||
AddChild(renew);
|
||||
_renewInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_renewInfo);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
_depot.ItemSelected += _ => Refresh(force: true);
|
||||
_trains.ItemSelected += i => TrainSelected?.Invoke(_trainIds[(int)i]);
|
||||
_vehicle.ItemSelected += _ => ShowModel();
|
||||
_trains.ItemSelected += i =>
|
||||
{
|
||||
TrainSelected?.Invoke(_trainIds[(int)i]);
|
||||
ShowRenewal();
|
||||
};
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_session.World.EntityVersion != _version) Refresh(force: false);
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Fleet is null && _sinceRequest > 5)) RequestFleet(today);
|
||||
bool fleetChanged = !ReferenceEquals(w.Fleet, _fleetShown);
|
||||
if (w.EntityVersion != _version || fleetChanged) Refresh(force: fleetChanged);
|
||||
}
|
||||
|
||||
private void RequestFleet(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
||||
}
|
||||
|
||||
private int Company => _session.World.Summary?.CompanyId ?? 0;
|
||||
@@ -95,7 +131,9 @@ public partial class TrainsPanel : VBoxContainer
|
||||
private void Refresh(bool force)
|
||||
{
|
||||
var w = _session.World;
|
||||
var fleet = w.Fleet;
|
||||
_version = w.EntityVersion;
|
||||
_fleetShown = fleet;
|
||||
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
|
||||
_depotIds.Clear();
|
||||
_depot.Clear();
|
||||
@@ -109,16 +147,33 @@ public partial class TrainsPanel : VBoxContainer
|
||||
|
||||
if (_catalog.Count == 0 || force)
|
||||
{
|
||||
int keep = _vehicle.Selected;
|
||||
string? keep = _vehicle.Selected >= 0 && _vehicle.Selected < _catalog.Count ? _catalog[_vehicle.Selected].Id : null;
|
||||
_catalog.Clear();
|
||||
_vehicle.Clear();
|
||||
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
|
||||
if (fleet is not null)
|
||||
{
|
||||
_catalog.Add(def);
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
|
||||
// catalogo del server: solo i modelli in produzione, i superati segnati con il successore
|
||||
foreach (var m in fleet.Models)
|
||||
{
|
||||
if (Def(m.Type) is not { } def) continue;
|
||||
_catalog.Add(def);
|
||||
string mark = m.Superseded ? $" · {T("superato")}" + (m.Successor.Length > 0 ? $" → {Def(m.Successor)?.NameIt ?? m.Successor}" : "") : "";
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}{mark}");
|
||||
}
|
||||
}
|
||||
_vehicle.Selected = keep >= 0 && keep < _catalog.Count ? keep : 0;
|
||||
else
|
||||
{
|
||||
// in attesa del quadro del server: i modelli dell'anno, senza segni
|
||||
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
|
||||
{
|
||||
_catalog.Add(def);
|
||||
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
|
||||
}
|
||||
}
|
||||
int index = keep is null ? -1 : _catalog.FindIndex(d => d.Id == keep);
|
||||
_vehicle.Selected = index >= 0 ? index : _catalog.Count > 0 ? 0 : -1;
|
||||
}
|
||||
ShowModel();
|
||||
|
||||
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
|
||||
_vehicleIds.Clear();
|
||||
@@ -126,18 +181,25 @@ public partial class TrainsPanel : VBoxContainer
|
||||
foreach (var v in w.Vehicles.Values.Where(v => v.Owner == Company && v.Depot == depot && v.Train < 0).OrderBy(v => v.Id))
|
||||
{
|
||||
_vehicleIds.Add(v.Id);
|
||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||
_inDepot.AddItem($"{def?.NameIt ?? v.Type} #{v.Id}");
|
||||
var info = fleet?.Vehicles.FirstOrDefault(x => x.Vehicle == v.Id);
|
||||
string extra = info is null
|
||||
? ""
|
||||
: (info.Superseded ? $" · {T("superato")}" : "") + " · " + string.Format(T("rivendita {0}"), info.Resale);
|
||||
_inDepot.AddItem($"{Def(v.Type)?.NameIt ?? v.Type} #{v.Id}{extra}");
|
||||
if (info is { Superseded: true }) _inDepot.SetItemCustomFgColor(_inDepot.ItemCount - 1, Palette.Amber);
|
||||
}
|
||||
|
||||
var selectedTrain = _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
|
||||
var selectedTrain = SelectedTrain;
|
||||
_trainIds.Clear();
|
||||
_trains.Clear();
|
||||
foreach (var t in w.Trains.Values.Where(t => t.Owner == Company).OrderBy(t => t.Id))
|
||||
{
|
||||
_trainIds.Add(t.Id);
|
||||
string line = t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l) ? l.Name : T("senza linea");
|
||||
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}");
|
||||
var renewal = fleet?.Trains.FirstOrDefault(r => r.Train == t.Id);
|
||||
string mark = renewal is null ? "" : " · " + (renewal.Booked ? T("rinnovo prenotato") : T("da rinnovare"));
|
||||
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}{mark}");
|
||||
if (renewal is { Booked: false }) _trains.SetItemCustomFgColor(_trains.ItemCount - 1, Palette.Amber);
|
||||
}
|
||||
int ti = _trainIds.IndexOf(selectedTrain);
|
||||
if (ti >= 0) _trains.Select(ti);
|
||||
@@ -154,6 +216,40 @@ public partial class TrainsPanel : VBoxContainer
|
||||
}
|
||||
int li = _lineIds.IndexOf(selectedLine);
|
||||
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
|
||||
ShowRenewal();
|
||||
}
|
||||
|
||||
private VehicleDef? Def(string id) => _session.World.Data.Vehicles.FirstOrDefault(v => v.Id == id);
|
||||
|
||||
/// <summary>Modello scelto nel catalogo: superato o no, successore con prestazioni e prezzo, ultimo anno di produzione.</summary>
|
||||
private void ShowModel()
|
||||
{
|
||||
var fleet = _session.World.Fleet;
|
||||
if (fleet is null || _vehicle.Selected < 0 || _vehicle.Selected >= _catalog.Count) { _modelInfo.Text = ""; return; }
|
||||
var model = fleet.Models.FirstOrDefault(m => m.Type == _catalog[_vehicle.Selected].Id);
|
||||
if (model is null) { _modelInfo.Text = ""; return; }
|
||||
var parts = new List<string>();
|
||||
if (model.Superseded)
|
||||
{
|
||||
var next = Def(model.Successor);
|
||||
parts.Add(next is null
|
||||
? string.Format(T("Superato dal {0}."), model.SupersededYear)
|
||||
: string.Format(T("Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4})."),
|
||||
model.SupersededYear, next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
||||
}
|
||||
if (model.LastYear > 0) parts.Add(string.Format(T("In produzione fino al {0}."), model.LastYear));
|
||||
_modelInfo.Text = string.Join(" ", parts);
|
||||
}
|
||||
|
||||
/// <summary>Rinnovo del treno scelto: veicoli superati e spesa netta calcolati dal server.</summary>
|
||||
private void ShowRenewal()
|
||||
{
|
||||
int train = SelectedTrain;
|
||||
var renewal = train >= 0 ? _session.World.Fleet?.Trains.FirstOrDefault(r => r.Train == train) : null;
|
||||
_renewInfo.Text = renewal is null
|
||||
? ""
|
||||
: string.Format(T("Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite."), renewal.Vehicles, renewal.NetCost)
|
||||
+ (renewal.Booked ? " " + T("Rinnovo già prenotato.") : renewal.Affordable ? "" : " " + T("Cassa insufficiente."));
|
||||
}
|
||||
|
||||
public static string StateName(TrainState s) => s switch
|
||||
@@ -168,7 +264,12 @@ public partial class TrainsPanel : VBoxContainer
|
||||
_ => s.ToString(),
|
||||
};
|
||||
|
||||
private void Result(CommandResultMessage r) => _status.Text = r.Message;
|
||||
private void Result(CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
// acquisti, vendite e rinnovi cambiano il quadro della flotta
|
||||
RequestFleet(Fmt.Today(_session.World));
|
||||
}
|
||||
|
||||
private void Buy()
|
||||
{
|
||||
@@ -185,7 +286,14 @@ public partial class TrainsPanel : VBoxContainer
|
||||
_session.Command(new ComposeTrainCommand(new DepotId(_depotIds[_depot.Selected]), selected, name), Result);
|
||||
}
|
||||
|
||||
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
|
||||
private void Sell()
|
||||
{
|
||||
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => _vehicleIds[i]).ToList();
|
||||
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da vendere"); return; }
|
||||
foreach (int id in selected) _session.Command(new SellVehicleCommand(new VehicleId(id)), Result);
|
||||
}
|
||||
|
||||
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel && sel[0] < _trainIds.Count ? _trainIds[sel[0]] : -1;
|
||||
|
||||
private void Assign()
|
||||
{
|
||||
@@ -200,4 +308,13 @@ public partial class TrainsPanel : VBoxContainer
|
||||
if (train < 0 || _depot.Selected < 0) { _status.Text = T("Seleziona un treno e un deposito"); return; }
|
||||
_session.Command(new SendToDepotCommand(new TrainId(train), new DepotId(_depotIds[_depot.Selected])), Result);
|
||||
}
|
||||
|
||||
private void Renew()
|
||||
{
|
||||
int train = SelectedTrain;
|
||||
if (train < 0) { _status.Text = T("Seleziona un treno"); return; }
|
||||
string intervention = _session.World.Fleet?.RenewalIntervention ?? "";
|
||||
if (intervention.Length == 0) { _status.Text = T("Quadro della flotta in arrivo dal server…"); return; }
|
||||
_session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user