using Godot; using RailEnterprise.Client.App; using RailEnterprise.Client.Net; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Protocol.Client; using RailEnterprise.Protocol.Messages; using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client.Panels; /// /// «La tua scalata» a tutto schermo (immagine di riferimento 08): in alto il binario dei livelli con /// il treno che avanza verso il prossimo, sotto ogni stazione il nome, quando è stato raggiunto (o /// l'avanzamento, o il patrimonio richiesto) e gli sblocchi; a sinistra lo storico del patrimonio /// netto con i livelli raggiunti e i requisiti del prossimo livello; a destra lo stato patrimoniale, /// il conto economico e i prestiti. Tutti i numeri arrivano dal server (ClimbReport, ADR 0018): il /// pannello li chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e li mostra com'è. /// public partial class ClimbPanel : VBoxContainer { private readonly GameSession _session; private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary); private readonly Label _worth = UiTheme.Text("", 30, Palette.AmberLight, bold: true); private readonly TierTrack _track = new(); private readonly HBoxContainer _stations = PanelKit.Row(8); private readonly Label _historyCaption = UiTheme.Text("", 13, Palette.TextSecondary); private readonly SeriesChart _chart = new(250); private readonly Label _nextTitle = UiTheme.Text("", 16, bold: true); private readonly HBoxContainer _requirements = PanelKit.Row(24); private readonly VBoxContainer _balance = PanelKit.Column(6); private readonly Label _incomeTitle = UiTheme.Text("", 20, bold: true); private readonly VBoxContainer _income = PanelKit.Column(6); private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) }; private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill }; private readonly Button _repay = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill }; private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary); private ClimbReport? _shown; private long _requestedDay = long.MinValue; private double _sinceRequest = double.MaxValue; public event Action? CloseRequested; public ClimbPanel(GameSession session) { _session = session; AddThemeConstantOverride("separation", 16); SizeFlagsVertical = SizeFlags.ExpandFill; var header = PanelKit.Row(24); var titles = PanelKit.Column(0); titles.AddChild(UiTheme.TitleLabel(T("La tua scalata"), 44)); titles.AddChild(_subtitle); header.AddChild(titles); var worth = PanelKit.Column(0); worth.SizeFlagsHorizontal = SizeFlags.ShrinkEnd; worth.SizeFlagsVertical = SizeFlags.ShrinkCenter; var worthCaption = UiTheme.Text(T("Patrimonio netto"), 13, Palette.TextSecondary); worthCaption.HorizontalAlignment = HorizontalAlignment.Right; _worth.HorizontalAlignment = HorizontalAlignment.Right; worth.AddChild(worthCaption); worth.AddChild(_worth); header.AddChild(worth); var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) }; close.Pressed += () => CloseRequested?.Invoke(); header.AddChild(close); AddChild(header); // binario dei livelli var trackCard = Card(); var trackCol = (VBoxContainer)trackCard.GetChild(0); trackCol.AddChild(_track); trackCol.AddChild(_stations); AddChild(trackCard); var body = PanelKit.Row(20); body.SizeFlagsVertical = SizeFlags.ExpandFill; AddChild(body); var left = Column(body, 1.15f); var historyHeader = PanelKit.Row(8); var historyTitle = UiTheme.Text(T("Patrimonio netto"), 20, bold: true); historyTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill; historyHeader.AddChild(historyTitle); _historyCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter; historyHeader.AddChild(_historyCaption); left.AddChild(historyHeader); left.AddChild(_chart); left.AddChild(_nextTitle); left.AddChild(_requirements); var right = Column(body, 0.85f); right.AddChild(UiTheme.Text(T("Stato patrimoniale"), 20, bold: true)); right.AddChild(_balance); right.AddChild(new Control { CustomMinimumSize = new Vector2(0, 6) }); right.AddChild(_incomeTitle); right.AddChild(_income); right.AddChild(new Control { SizeFlagsVertical = SizeFlags.ExpandFill }); var loanRow = PanelKit.Row(10); loanRow.AddChild(_amount); loanRow.AddChild(_borrow); loanRow.AddChild(_repay); right.AddChild(loanRow); _status.AutowrapMode = TextServer.AutowrapMode.WordSmart; right.AddChild(_status); _borrow.Text = T("Chiedi un prestito"); _borrow.Pressed += Borrow; _repay.Pressed += Repay; _amount.ValueChanged += _ => UpdateLoanButtons(); _subtitle.Text = T("In attesa del quadro dal server…"); } private static PanelContainer Card() { var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill }; card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24)); card.AddChild(PanelKit.Column(10)); return card; } 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, 12, 24)); var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill }; frame.AddChild(scroll); var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill }; margin.AddThemeConstantOverride("margin_right", 10); scroll.AddChild(margin); var col = PanelKit.Column(12); col.SizeFlagsVertical = SizeFlags.ExpandFill; 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.Climb is null && _sinceRequest > 5)) Request(today); if (w.Climb is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report); } private void Request(long day) { _requestedDay = day; _sinceRequest = 0; _session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 }); } // ------------------------------------------------------------------ dati di comodo (solo lettura) private static int YearOf(ClientWorld w, long day) => w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).Year : 0; private static string TierName(TierInfo t) => TranslationServer.GetLocale().StartsWith("en") ? t.NameEn : t.NameIt; private static string Short(Money m) => m.ToString("short"); /// Sblocco nella lingua dell'interfaccia (i valori arrivano dal server). public static string UnlockText(UnlockInfo u) => u.Kind switch { UnlockInfo.LoanLimit => $"{T("Fido fino a")} {Short(new Money(u.Value))}", UnlockInfo.Crews => $"{u.Value} {T("squadre di cantiere")}", UnlockInfo.Trading => T("Compravendita in proprio"), UnlockInfo.BuyIndustry => T("Acquisto di industrie"), UnlockInfo.Ipo => T("Quotazione in borsa"), UnlockInfo.HostileTakeover => T("Scalate ai concorrenti"), UnlockInfo.Concessions => T("Concessioni"), _ => "", }; // ------------------------------------------------------------------ aggiornamento private void Refresh(ClientWorld w, ClimbReport report) { _shown = report; string company = Fmt.Company(w, report.Company); _subtitle.Text = $"{company}, {T("fondata nel")} {YearOf(w, report.FoundedDay)} {T("con")} {report.InitialCapital}"; _worth.Text = report.BalanceNetWorth.ToString(); RefreshTrack(w, report); RefreshHistory(w, report); RefreshRequirements(report); RefreshBalance(report); RefreshIncome(report); UpdateLoanButtons(); } private void RefreshTrack(ClientWorld w, ClimbReport report) { var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier); _track.Set(report.Tiers.Count, report.Tier, report.NextTier > 0 ? report.Progress : 1, next is null ? "" : $"{Fmt.Progress(report.Progress)} {T("verso")} {TierName(next)}"); foreach (var c in _stations.GetChildren()) c.QueueFree(); foreach (var t in report.Tiers) { bool current = t.Level == report.Tier, isNext = t.Level == report.NextTier; var col = PanelKit.Column(2); col.SizeFlagsHorizontal = SizeFlags.ExpandFill; var name = UiTheme.TitleLabel(TierName(t), 30, current ? Palette.AmberLight : t.Reached || isNext ? Palette.Text : Palette.TextSecondary); name.HorizontalAlignment = HorizontalAlignment.Center; col.AddChild(name); string status = t.Level == 1 ? $"{T("dal")} {YearOf(w, t.ReachedDay)}" : t.Reached ? (t.ReachedDay >= 0 ? $"{T("raggiunta nel")} {YearOf(w, t.ReachedDay)}" : T("raggiunta")) : isNext ? $"{T("avanzamento")} {Fmt.Progress(report.Progress)}" : $"{T("patrimonio")} {Short(t.NetWorthRequired)}"; var statusLabel = UiTheme.Text(status, 14, current ? Palette.AmberLight : Palette.Text, bold: true); statusLabel.HorizontalAlignment = HorizontalAlignment.Center; col.AddChild(statusLabel); col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 8) }); foreach (var u in t.Unlocks) { var l = UiTheme.Text(UnlockText(u), 13, Palette.TextSecondary); l.HorizontalAlignment = HorizontalAlignment.Center; l.AutowrapMode = TextServer.AutowrapMode.WordSmart; col.AddChild(l); } _stations.AddChild(col); } } private void RefreshHistory(ClientWorld w, ClimbReport report) { var values = report.History.Select(p => (double)p.Value.Cents).ToList(); var labels = report.History.Select(p => YearOf(w, p.Day).ToString()).ToList(); _chart.Show(values, labels, v => new Money((long)v).ToString("short"), SeriesChart.Style.Line, Palette.Amber, T("Lo storico cresce anno dopo anno")); // i livelli raggiunti si segnano sul punto dell'anno della promozione (un punto per anno di // calendario, l'ultimo è oggi); in mancanza sul primo punto dopo la promozione var markers = new List<(int Index, string Label)>(); foreach (var t in report.Tiers.Where(t => t.Level > 1 && t.Reached && t.ReachedDay >= 0)) { int year = YearOf(w, t.ReachedDay); int index = report.History.FindIndex(p => YearOf(w, p.Day) == year); if (index < 0) index = report.History.FindIndex(p => p.Day >= t.ReachedDay); if (index >= 0) markers.Add((index, TierName(t))); } _chart.SetMarkers(markers); if (report.History.Count >= 2) { var first = report.History[0]; var last = report.History[^1]; int years = Math.Max(0, YearOf(w, last.Day) - YearOf(w, first.Day)); _historyCaption.Text = $"{T("da")} {first.Value} {T("a")} {Short(last.Value)} {T("in")} {years} {(years == 1 ? T("anno") : T("anni"))}"; } else _historyCaption.Text = ""; } private void RefreshRequirements(ClimbReport report) { foreach (var c in _requirements.GetChildren()) c.QueueFree(); var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier); if (next is null) { _nextTitle.Text = T("Hai raggiunto il livello più alto"); return; } _nextTitle.Text = $"{T("Per diventare")} {TierName(next)}"; _requirements.AddChild(Requirement($"{T("Patrimonio netto di")} {Short(report.NetWorthRequired)}", report.NetWorthFraction, report.NetWorthMet, $"{Short(report.NetWorth)}, {Fmt.Progress(report.NetWorthFraction)}")); _requirements.AddChild(Requirement($"{report.TownsRequired} {T("città oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}", report.TownsFraction, report.TownsMet, $"{report.Towns} {(report.Towns == 1 ? T("collegata su") : T("collegate su"))} {report.TownsRequired}")); _requirements.AddChild(Requirement($"{T("Rating creditizio")} {report.RatingRequired}", report.RatingFraction, report.RatingMet, $"{T("attuale")} {report.Rating}")); } private static Control Requirement(string caption, float fraction, bool met, string value) { var col = PanelKit.Column(6); col.SizeFlagsHorizontal = SizeFlags.ExpandFill; col.AddChild(UiTheme.Text(caption, 14)); var color = met ? Palette.Ok : Palette.Amber; 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)); col.AddChild(bar); col.AddChild(UiTheme.Text((met ? "✓ " : "") + value, 13, met ? Palette.Ok : Palette.TextSecondary)); return col; } private static string AssetName(byte kind) => kind switch { ClimbReport.AssetTrack => T("Binari e opere"), ClimbReport.AssetStations => T("Stazioni e depositi"), ClimbReport.AssetVehicles => T("Materiale rotabile"), ClimbReport.AssetIndustries => T("Industrie possedute"), ClimbReport.AssetGoods => T("Merce propria"), _ => "", }; private void RefreshBalance(ClimbReport report) { foreach (var c in _balance.GetChildren()) c.QueueFree(); foreach (var a in report.Assets) { // le voci di base si vedono sempre, industrie e merce solo se ci sono bool always = a.Kind is ClimbReport.AssetTrack or ClimbReport.AssetStations or ClimbReport.AssetVehicles; if (always || a.Value.Cents != 0) _balance.AddChild(Line(AssetName(a.Kind), a.Value.ToString())); } if (report.Portfolio.Cents != 0) _balance.AddChild(Line(T("Partecipazioni"), report.Portfolio.ToString())); _balance.AddChild(Line(T("Cassa"), report.Cash.ToString())); _balance.AddChild(PanelKit.Separator()); _balance.AddChild(Line(T("Totale attivo"), report.TotalAssets.ToString(), bold: true)); string loans = report.Loans.Cents > 0 ? $"{T("Prestiti al")} {Fmt.Pct(report.LoansRate, 1)}" : T("Prestiti"); _balance.AddChild(Line(loans, report.Loans.ToString())); if (report.Overdraft.Cents > 0) _balance.AddChild(Line(T("Scoperto di cassa"), report.Overdraft.ToString(), color: Palette.Danger)); _balance.AddChild(Line(T("Patrimonio netto"), report.BalanceNetWorth.ToString(), bold: true, color: Palette.AmberLight)); } private void RefreshIncome(ClimbReport report) { _incomeTitle.Text = $"{T("Conto economico")} {report.IncomeYear}{(report.IncomePartial ? " " + T("(finora)") : "")}"; foreach (var c in _income.GetChildren()) c.QueueFree(); foreach (var i in report.Income) { string name = i.Kind switch { ClimbReport.IncomeFares => T("Ricavi da tariffe e noli"), ClimbReport.IncomeOther => T("Altri ricavi"), ClimbReport.IncomeOperating => T("Costi operativi"), ClimbReport.IncomeMaintenance => T("Manutenzione"), ClimbReport.IncomeInterest => T("Interessi"), _ => "", }; if (i.Kind == ClimbReport.IncomeOther && i.Value.Cents == 0) continue; // i costi si mostrano in valore assoluto: l'etichetta dice già che sono costi bool cost = i.Kind is ClimbReport.IncomeOperating or ClimbReport.IncomeMaintenance or ClimbReport.IncomeInterest; var value = cost ? new Money(Math.Abs(i.Value.Cents)) : i.Value; _income.AddChild(Line(name, value.ToString())); } _income.AddChild(PanelKit.Separator()); _income.AddChild(Line(T("Utile netto"), report.Profit.ToString(), bold: true, color: report.Profit.IsNegative ? Palette.Danger : Palette.AmberLight)); } private static Control Line(string caption, string value, bool bold = false, Color? color = null) { var row = PanelKit.Row(8); var c = UiTheme.Text(caption, 14, bold ? Palette.Text : Palette.TextSecondary, bold); c.SizeFlagsHorizontal = SizeFlags.ExpandFill; var v = UiTheme.Text(value, 14, color ?? Palette.Text, bold); v.HorizontalAlignment = HorizontalAlignment.Right; row.AddChild(c); row.AddChild(v); return row; } // ------------------------------------------------------------------ prestiti (comandi al server) /// Prestito da rimborsare per primo: quello con il tasso più alto (scelta dell'interfaccia). private LoanInfo? LoanToRepay() => _shown?.LoanList.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Loan).FirstOrDefault(); private Money Amount => Money.FromLire((long)_amount.Value); private void UpdateLoanButtons() { var report = _shown; var loan = LoanToRepay(); var repay = loan is null ? Amount : Money.Min(Amount, loan.Remaining); _repay.Text = $"{T("Rimborsa")} {repay}"; _repay.Disabled = loan is null; _borrow.Disabled = report is null || !report.LoansAllowed; _borrow.TooltipText = report is null ? "" : report.LoansAllowed ? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}" : T("In amministrazione controllata non si possono chiedere prestiti"); } private void Borrow() => _session.Command(new TakeLoanCommand(Amount), r => { _status.Text = r.Message; Request(Fmt.Today(_session.World)); }); private void Repay() { var loan = LoanToRepay(); if (loan is null) return; _session.Command(new RepayLoanCommand(new LoanId(loan.Loan), Money.Min(Amount, loan.Remaining)), r => { _status.Text = r.Message; Request(Fmt.Today(_session.World)); }); } /// /// Binario dei livelli (immagine 08): rotaie e traversine da una stazione all'altra, ambra fino al /// treno, cerchi pieni per i livelli raggiunti, anello per quello attuale, il treno e la sua etichetta. /// private sealed partial class TierTrack : Control { private int _count = 5, _tier = 1; private float _progress; private string _label = ""; public TierTrack() { CustomMinimumSize = new Vector2(0, 112); MouseFilter = MouseFilterEnum.Ignore; } public void Set(int count, int tier, float progress, string label) { _count = Math.Max(1, count); _tier = Math.Clamp(tier, 1, _count); _progress = Math.Clamp(progress, 0, 1); _label = label; QueueRedraw(); } private float X(int level) => (level - 0.5f) * Size.X / _count; public override void _Draw() { const float y = 78; float x0 = X(1), x1 = X(_count); float trainX = _tier >= _count ? x1 : X(_tier) + (X(_tier + 1) - X(_tier)) * _progress; var dim = Palette.Rails.Lerp(Palette.Border, 0.4f); // traversine, poi le due rotaie for (float x = x0; x <= x1; x += 12) DrawLine(new Vector2(x, y - 9), new Vector2(x, y + 9), x <= trainX ? Palette.WithAlpha(Palette.Amber, 0.45f) : Palette.Border, 3); foreach (float dy in new[] { -5f, 5f }) { DrawLine(new Vector2(x0, y + dy), new Vector2(trainX, y + dy), Palette.Amber, 3); if (trainX < x1) DrawLine(new Vector2(trainX, y + dy), new Vector2(x1, y + dy), dim, 3); } for (int level = 1; level <= _count; level++) { var c = new Vector2(X(level), y); bool reached = level <= _tier; if (level == _tier) { DrawCircle(c, 32, Palette.Panel); DrawArc(c, 31, 0, MathF.Tau, 48, Palette.Amber, 2.5f, true); } DrawCircle(c, 21, reached ? Palette.Amber : Palette.Panel); DrawArc(c, 21, 0, MathF.Tau, 40, reached ? Palette.AppBackground : Palette.Border.Lerp(Palette.TextSecondary, 0.35f), 3, true); } if (_label.Length > 0 && _tier < _count) DrawTrain(new Vector2(trainX, y - 16)); } /// Locomotiva stilizzata con l'etichetta dell'avanzamento sopra. private void DrawTrain(Vector2 at) { var body = Palette.AmberLight; DrawRect(new Rect2(at.X - 30, at.Y - 22, 46, 20), body); DrawRect(new Rect2(at.X + 10, at.Y - 34, 20, 32), body); DrawRect(new Rect2(at.X - 24, at.Y - 32, 8, 10), body); foreach (float dx in new[] { -18f, -2f, 14f }) { DrawCircle(new Vector2(at.X + dx, at.Y + 4), 6, Palette.AppBackground); DrawArc(new Vector2(at.X + dx, at.Y + 4), 6, 0, MathF.Tau, 16, body, 2.5f, true); } var font = UiTheme.BodyBold; var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 15); float x = Math.Clamp(at.X - dims.X / 2, 4, Size.X - dims.X - 4); DrawString(font, new Vector2(x, at.Y - 44), _label, HorizontalAlignment.Left, -1, 15, Palette.AmberLight); } } }