F6: scheda industria e connessione, correzioni della revisione
Correzioni dalla revisione della scheda industria e della schermata di
connessione.
- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
contratti a piedi, quelli della compagnia della sessione e, se
l'industria è sua, quelli di tutti i vettori, come il Registro degli
impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
NewGame non si confonde più con gli eventi del mondo che arrivano
mentre si aspetta il Welcome.
- Schermata di connessione:
- all'apertura avvia la strada scelta l'ultima volta;
- cambiando strada chiude la sessione dell'altra;
- senza sessione «Connetti e riprendi» la apre;
- il cambio di lingua passa la sessione alla schermata nuova;
- la scelta del salvataggio si tiene per id;
- Load e nuova partita chiedono conferma;
- stato del server su 3×2 con la versione del protocollo, salvataggi
su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
- collegamenti e nodi non collegati sono leggibili;
- testo per l'industria inattiva;
- revisione e ammodernamento disabilitati, con il motivo, quando il
server li rifiuterebbe;
- l'esito dell'acquisto compare accanto al pulsante;
- le righe lunghe vanno a capo;
- «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
schermo.
- Pilota automatico:
- la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
- 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.
Refs #42.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
45462bf9ec
commit
0667a4a544
17 files changed
+514
-156
No files matched your search
@@ -7,7 +7,6 @@ Aderisci con le tue azioni,,Tender your shares
|
||||
adesso,,just now
|
||||
Aggiorna,,Refresh
|
||||
al giorno,,per day
|
||||
al lavoro ora,,at work now
|
||||
Alto,,High
|
||||
Ambra,,Amber
|
||||
Amministrazione controllata,,Receivership
|
||||
@@ -345,7 +344,6 @@ carica,,load
|
||||
cavaliere bianco,,white knight
|
||||
città senza servizi per il personale,,towns without services for staff
|
||||
Client collegati,,Connected clients
|
||||
Collegato a,,Connected to
|
||||
Collo di bottiglia,,Bottleneck
|
||||
Condizione degli impianti,,Plant condition
|
||||
Connetti a un server,,Connect to a server
|
||||
@@ -358,7 +356,6 @@ Copertura degli ingressi,,Input coverage
|
||||
Crea una linea verso questa industria,,Build a line to this industry
|
||||
Creazione della nuova partita sul server…,,Creating the new game on the server…
|
||||
da,,from
|
||||
dati compatibili,,compatible data
|
||||
degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans.
|
||||
dei ricavi,,of revenue
|
||||
del capitale,,of the capital
|
||||
@@ -588,7 +585,6 @@ Scegli un'industria nell'elenco in alto.,,Choose an industry from the list above
|
||||
Scheda dell'industria,,Industry sheet
|
||||
scorta,,stock
|
||||
serve,,needs
|
||||
Server locale spento: scegli «Gioca in locale» per avviarlo,,Local server off: choose «Play locally» to start it
|
||||
"Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui.",,"Server on this computer, started and stopped with the game. Games stay here."
|
||||
servita dalla stazione,,served by station
|
||||
servita dalla tua linea,,served by your line
|
||||
@@ -663,7 +659,6 @@ città oltre,,towns over
|
||||
collegata su,,connected out of
|
||||
collegate su,,connected out of
|
||||
merci su linea,,goods on a line
|
||||
Prezzo medio realizzato,,Average realised price
|
||||
Rating creditizio,,Credit rating
|
||||
attuale,,current
|
||||
Binari e opere,,Track and structures
|
||||
@@ -782,3 +777,16 @@ Verifica connessione,,Test connection
|
||||
Versione,,Version
|
||||
Versione del gioco,,Game version
|
||||
viaggio medio,,average trip
|
||||
Sostituire la partita?,,Replace the game?
|
||||
Sostituisci la partita,,Replace the game
|
||||
Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with the save «{1}» for every connected client ({2}). Anything not saved will be lost.
|
||||
Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with a new game for every connected client ({1}). Anything not saved will be lost.
|
||||
Server raggiungibile,,Server reachable
|
||||
Server locale spento: «Connetti e riprendi» lo avvia,,Local server off: «Connect and resume» starts it
|
||||
protocollo,,protocol
|
||||
in sede,,on site
|
||||
Prezzo di vendita,,Selling price
|
||||
Offerta inviata…,,Offer sent…
|
||||
Industria inattiva: non è in vendita finché non riprende a produrre.,,Inactive industry: not for sale until it starts producing again.
|
||||
L'industria è ferma: riprova a fermo finito.,,The industry is stopped: try again when the stop is over.
|
||||
C'è già un lavoro in programma.,,Work is already scheduled.
|
||||
|
@@ -209,13 +209,14 @@ public partial class AutoPilot : Node
|
||||
var anchor = MapScale.V(near);
|
||||
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
||||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
||||
// dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di
|
||||
// un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo
|
||||
// (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom
|
||||
_game.OpenIndustry(industry.Id);
|
||||
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
||||
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
|
||||
// al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda
|
||||
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
||||
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
||||
_game.Map.CenterOn(MapScale.V(industry.Position));
|
||||
_game.Map.SetZoom(0.3f);
|
||||
await Shot("12_industria", 40);
|
||||
_game.ScrollPanel(1);
|
||||
await Shot("12b_industria_scorte", 20);
|
||||
@@ -270,12 +271,17 @@ public partial class AutoPilot : Node
|
||||
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
|
||||
Session.Send(new Save { Name = "Collaudo" });
|
||||
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
|
||||
var connect = new ConnectScreen(World.Data, remember: false);
|
||||
_game.AddChild(connect);
|
||||
// livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la
|
||||
// schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa
|
||||
_game.CloseTools();
|
||||
var layer = new CanvasLayer { Layer = 10 };
|
||||
_game.AddChild(layer);
|
||||
var connect = new ConnectScreen(World.Data, remember: false, autoStart: false);
|
||||
layer.AddChild(connect);
|
||||
await Frame();
|
||||
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
|
||||
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
|
||||
await Shot("20_connessione", 30);
|
||||
connect.QueueFree();
|
||||
layer.QueueFree();
|
||||
}
|
||||
}
|
||||
@@ -35,13 +35,15 @@ public partial class Main : Node
|
||||
{
|
||||
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
|
||||
}
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
if (i >= 0 && _data is not null)
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null);
|
||||
if (_autopilot is not null)
|
||||
{
|
||||
// collaudo: mappa piccola e seme fisso per il server locale
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
|
||||
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
|
||||
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
|
||||
@@ -57,7 +59,9 @@ public partial class Main : Node
|
||||
}
|
||||
|
||||
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
|
||||
private void ShowMenu(string status = "")
|
||||
/// <param name="autoStart">Avvia subito la strada scelta l'ultima volta (server locale o in rete).</param>
|
||||
/// <param name="handover">Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).</param>
|
||||
private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
|
||||
{
|
||||
if (_data is null)
|
||||
{
|
||||
@@ -67,7 +71,7 @@ public partial class Main : Node
|
||||
Swap(label);
|
||||
return;
|
||||
}
|
||||
var screen = new ConnectScreen(_data);
|
||||
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
|
||||
screen.PlayRequested += ShowGame;
|
||||
screen.LanguageChanged += code =>
|
||||
{
|
||||
@@ -76,7 +80,8 @@ public partial class Main : Node
|
||||
cfg.SetValue("ui", "locale", code);
|
||||
cfg.Save(SettingsPath);
|
||||
TranslationServer.SetLocale(code);
|
||||
ShowMenu();
|
||||
// la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
|
||||
ShowMenu(handover: screen.TakeSession());
|
||||
};
|
||||
Swap(screen);
|
||||
if (status.Length > 0) screen.SetStatus(status, error: true);
|
||||
@@ -89,7 +94,7 @@ public partial class Main : Node
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
if (server is null)
|
||||
{
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
|
||||
return;
|
||||
}
|
||||
var launcher = new LocalServerLauncher();
|
||||
@@ -105,7 +110,7 @@ public partial class Main : Node
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,10 +120,12 @@ public partial class Main : Node
|
||||
var game = new GameScreen(session);
|
||||
game.Exit += async () =>
|
||||
{
|
||||
// prima si chiude la partita (e il server locale), poi la schermata di connessione ne
|
||||
// avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono
|
||||
var s = _session;
|
||||
_session = null;
|
||||
ShowMenu();
|
||||
if (s is not null) await s.DisposeAsync();
|
||||
ShowMenu();
|
||||
};
|
||||
Swap(game);
|
||||
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
|
||||
|
||||
@@ -41,6 +41,9 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private readonly VBoxContainer _controls = PanelKit.Column(8);
|
||||
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;
|
||||
@@ -123,6 +126,8 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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);
|
||||
@@ -156,6 +161,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (id == _industry) return;
|
||||
_industry = id;
|
||||
_status.Text = "";
|
||||
_buyStatus.Text = "";
|
||||
_scroll.ScrollVertical = 0;
|
||||
SyncSelection();
|
||||
Request();
|
||||
@@ -188,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();
|
||||
}
|
||||
|
||||
@@ -327,7 +335,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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(UiTheme.Text($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||
_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());
|
||||
@@ -361,7 +369,8 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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";
|
||||
_workforce.AddChild(UiTheme.Text($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("al lavoro ora")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||
// 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);
|
||||
@@ -375,7 +384,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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(UiTheme.Text($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||
_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)
|
||||
@@ -386,14 +395,14 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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(UiTheme.Text($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||
_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 medio realizzato"), PanelKit.Value(s.AveragePrice < 0 ? "—" : Fmt.PricePrecise(s.AveragePrice))));
|
||||
_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)));
|
||||
}
|
||||
@@ -430,12 +439,19 @@ public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
|
||||
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
|
||||
buy.Pressed += () => _session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), Result);
|
||||
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(UiTheme.Text(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||
_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)
|
||||
@@ -452,7 +468,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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(UiTheme.Text($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||
_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))));
|
||||
@@ -466,9 +482,9 @@ public partial class IndustryPanel : VBoxContainer
|
||||
var bar = new ScoreBar();
|
||||
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
|
||||
_plants.AddChild(bar);
|
||||
_plants.AddChild(UiTheme.Text($"{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));
|
||||
_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(UiTheme.Text($"{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));
|
||||
_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));
|
||||
@@ -484,7 +500,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_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(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_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));
|
||||
}
|
||||
|
||||
@@ -505,6 +521,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
foreach (var c in _controls.GetChildren()) c.QueueFree();
|
||||
_budgetButtons.Clear();
|
||||
_partsOrder = null;
|
||||
_overhaul = _upgrade = null;
|
||||
if (ind is null || ind.Owner != me) return;
|
||||
var w = _session.World;
|
||||
int id = ind.Id;
|
||||
@@ -540,12 +557,16 @@ public partial class IndustryPanel : VBoxContainer
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -553,6 +574,26 @@ public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
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);
|
||||
|
||||
// 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 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 (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
|
||||
|
||||
@@ -148,21 +148,25 @@ public partial class ChainGraph : Control
|
||||
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
|
||||
break;
|
||||
default:
|
||||
DrawDashedLine(from, to, Palette.Border, 2, 8);
|
||||
// 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.Border,
|
||||
_ => 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,
|
||||
@@ -171,6 +175,15 @@ public partial class ChainGraph : Control
|
||||
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;
|
||||
|
||||
@@ -13,19 +13,24 @@ namespace RailEnterprise.Client.Screens;
|
||||
/// <summary>
|
||||
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
|
||||
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
|
||||
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione, sistema, tempo di
|
||||
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
|
||||
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
|
||||
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
|
||||
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
|
||||
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione e protocollo,
|
||||
/// sistema, tempo di attività, tick al secondo, latenza, client collegati), le partite salvate sul
|
||||
/// server e i pulsanti per riprendere o iniziare. All'apertura la schermata avvia il server locale o
|
||||
/// verifica il server in rete ricordato, con una sessione di prova che legge lo stato e l'elenco dei
|
||||
/// salvataggi; «Connetti e riprendi» la passa alla partita (e se non c'è ancora la apre). Nessuna
|
||||
/// logica di gioco: carica, nuova partita ed elenco sono richieste al server (Load, NewGame,
|
||||
/// ListSaves). Caricare o creare una partita sostituisce il mondo per tutti: si chiede conferma.
|
||||
/// </summary>
|
||||
public partial class ConnectScreen : Control
|
||||
{
|
||||
private const string SettingsPath = "user://settings.cfg";
|
||||
private const double SavesRefreshS = 5;
|
||||
private const double WelcomeTimeoutS = 30;
|
||||
/// <summary>Metadato della riga «Partita in corso» nell'elenco dei salvataggi.</summary>
|
||||
private const string CurrentGame = "";
|
||||
private readonly GameData _data;
|
||||
private readonly bool _remember;
|
||||
private readonly bool _remember, _autoStart;
|
||||
private GameSession? _handover;
|
||||
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
|
||||
@@ -35,28 +40,44 @@ public partial class ConnectScreen : Control
|
||||
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
|
||||
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
|
||||
private readonly GridContainer _stateRows = new() { Columns = 2 };
|
||||
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
private readonly List<string> _saveIds = [];
|
||||
/// <summary>Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).</summary>
|
||||
private readonly GridContainer _stateGrid = new() { Columns = 3 };
|
||||
private readonly List<(Label Caption, Label Value)> _stateCells = [];
|
||||
/// <summary>Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.</summary>
|
||||
private readonly Tree _saves = new()
|
||||
{
|
||||
Columns = 3, HideRoot = true, SelectMode = Tree.SelectModeEnum.Row, CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill,
|
||||
};
|
||||
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
|
||||
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly ConfirmationDialog _confirm = new() { Title = T("Sostituire la partita?"), DialogAutowrap = true, MinSize = new Vector2I(520, 0) };
|
||||
private Action? _onConfirm;
|
||||
private GameSession? _session;
|
||||
private bool _busy, _local;
|
||||
private bool _busy, _local, _closed, _resumeAfterConnect;
|
||||
private double _sinceSaves = double.MaxValue;
|
||||
private SaveList? _shownSaves;
|
||||
/// <summary>Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.</summary>
|
||||
private string _selectedSave = CurrentGame;
|
||||
private Action<IMessage>? _awaitingWelcome;
|
||||
private double _waiting;
|
||||
/// <summary>Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.</summary>
|
||||
private ServerInfo? _infoSeen;
|
||||
private double _infoAt;
|
||||
|
||||
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
|
||||
public event Action<GameSession>? PlayRequested;
|
||||
public event Action<string>? LanguageChanged;
|
||||
|
||||
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
|
||||
public ConnectScreen(GameData data, bool remember = true)
|
||||
/// <param name="autoStart">Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).</param>
|
||||
/// <param name="handover">Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.</param>
|
||||
public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
|
||||
{
|
||||
_data = data;
|
||||
_remember = remember;
|
||||
_autoStart = autoStart;
|
||||
_handover = handover;
|
||||
}
|
||||
|
||||
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
|
||||
@@ -117,7 +138,7 @@ public partial class ConnectScreen : Control
|
||||
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
|
||||
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
|
||||
_localCard.Pressed += () => SetMode(local: true, start: true);
|
||||
_remoteCard.Pressed += () => SetMode(local: false, start: false);
|
||||
_remoteCard.Pressed += () => SetMode(local: false, start: true);
|
||||
modes.AddChild(_localCard);
|
||||
modes.AddChild(_remoteCard);
|
||||
col.AddChild(modes);
|
||||
@@ -148,20 +169,42 @@ public partial class ConnectScreen : Control
|
||||
// stato del server
|
||||
var state = new PanelContainer();
|
||||
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
|
||||
var stateCol = PanelKit.Column(10);
|
||||
var stateCol = PanelKit.Column(12);
|
||||
var stateHead = PanelKit.Row(10);
|
||||
stateHead.AddChild(_dot);
|
||||
stateHead.AddChild(_stateTitle);
|
||||
stateCol.AddChild(stateHead);
|
||||
_stateRows.AddThemeConstantOverride("h_separation", 24);
|
||||
_stateRows.AddThemeConstantOverride("v_separation", 6);
|
||||
stateCol.AddChild(_stateRows);
|
||||
_stateGrid.AddThemeConstantOverride("h_separation", 24);
|
||||
_stateGrid.AddThemeConstantOverride("v_separation", 12);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
var cell = PanelKit.Column(2);
|
||||
cell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var caption = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
var value = UiTheme.Text("", 14, bold: true);
|
||||
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
cell.AddChild(caption);
|
||||
cell.AddChild(value);
|
||||
_stateGrid.AddChild(cell);
|
||||
_stateCells.Add((caption, value));
|
||||
}
|
||||
stateCol.AddChild(_stateGrid);
|
||||
state.AddChild(stateCol);
|
||||
col.AddChild(state);
|
||||
|
||||
// partite salvate sul server
|
||||
// partite salvate sul server: nome, data di gioco, quanto tempo fa
|
||||
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
|
||||
_saves.ItemActivated += _ => Resume();
|
||||
_saves.SetColumnExpand(0, true);
|
||||
_saves.SetColumnExpandRatio(0, 3);
|
||||
_saves.SetColumnExpand(1, true);
|
||||
_saves.SetColumnExpandRatio(1, 2);
|
||||
_saves.SetColumnExpand(2, true);
|
||||
_saves.SetColumnExpandRatio(2, 1);
|
||||
_saves.ItemSelected += () =>
|
||||
{
|
||||
if (_saves.GetSelected() is { } item) _selectedSave = item.GetMetadata(0).AsString();
|
||||
};
|
||||
_saves.ItemActivated += Resume;
|
||||
col.AddChild(_saves);
|
||||
var actions = PanelKit.Row(10);
|
||||
_resume.CustomMinimumSize = new Vector2(0, 48);
|
||||
@@ -193,6 +236,18 @@ public partial class ConnectScreen : Control
|
||||
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(notice);
|
||||
|
||||
// conferma prima di sostituire la partita sul server
|
||||
_confirm.OkButtonText = T("Sostituisci la partita");
|
||||
_confirm.CancelButtonText = T("Annulla");
|
||||
_confirm.Confirmed += () =>
|
||||
{
|
||||
var action = _onConfirm;
|
||||
_onConfirm = null;
|
||||
action?.Invoke();
|
||||
};
|
||||
_confirm.Canceled += () => _onConfirm = null;
|
||||
AddChild(_confirm);
|
||||
|
||||
bool remote = false;
|
||||
if (_remember)
|
||||
{
|
||||
@@ -204,7 +259,19 @@ public partial class ConnectScreen : Control
|
||||
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
|
||||
}
|
||||
}
|
||||
SetMode(local: !remote, start: false);
|
||||
if (_handover is not null)
|
||||
{
|
||||
// cambio di lingua: la sessione di prova (e il suo server locale) passa a questa schermata
|
||||
var session = _handover;
|
||||
_handover = null;
|
||||
SetMode(local: session.LocalServer is not null, start: false);
|
||||
Attach(session);
|
||||
}
|
||||
else
|
||||
{
|
||||
// all'apertura si avvia la strada scelta l'ultima volta, come nell'immagine 09
|
||||
SetMode(local: !remote, start: _autoStart);
|
||||
}
|
||||
ShowState();
|
||||
}
|
||||
|
||||
@@ -215,6 +282,7 @@ public partial class ConnectScreen : Control
|
||||
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
|
||||
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
|
||||
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
|
||||
card.AddThemeStyleboxOverride("disabled", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
|
||||
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
margin.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
|
||||
@@ -235,13 +303,25 @@ public partial class ConnectScreen : Control
|
||||
|
||||
// ------------------------------------------------------------------ modalità e sessione di prova
|
||||
|
||||
/// <summary>La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.</summary>
|
||||
private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
|
||||
|
||||
/// <summary>
|
||||
/// Cambia strada. La sessione dell'altra strada si chiude (e con lei il server locale), così
|
||||
/// «Connetti e riprendi» non apre mai la partita della strada non scelta. Con start si avvia il
|
||||
/// server locale o si verifica il server in rete indicato.
|
||||
/// </summary>
|
||||
private void SetMode(bool local, bool start)
|
||||
{
|
||||
_local = local;
|
||||
_localCard.SetPressedNoSignal(local);
|
||||
_remoteCard.SetPressedNoSignal(!local);
|
||||
_remoteFields.Visible = !local;
|
||||
if (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
|
||||
if (_session is not null && !SessionMatchesMode)
|
||||
{
|
||||
_ = Release();
|
||||
SetStatus("");
|
||||
}
|
||||
if (_remember)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
@@ -249,6 +329,11 @@ public partial class ConnectScreen : Control
|
||||
cfg.SetValue("server", "mode", local ? "local" : "remote");
|
||||
cfg.Save(SettingsPath);
|
||||
}
|
||||
if (start && _session is null && !_busy)
|
||||
{
|
||||
if (local) _ = StartLocal();
|
||||
else if (_address.Text.Trim().Length > 0) SubmitRemote();
|
||||
}
|
||||
ShowState();
|
||||
}
|
||||
|
||||
@@ -259,6 +344,7 @@ public partial class ConnectScreen : Control
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
if (server is null)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
|
||||
return;
|
||||
}
|
||||
@@ -272,15 +358,18 @@ public partial class ConnectScreen : Control
|
||||
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
|
||||
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
|
||||
session.LocalServer = launcher;
|
||||
Attach(session);
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: true)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
|
||||
}
|
||||
_busy = false;
|
||||
ShowState();
|
||||
if (!_closed) ShowState();
|
||||
}
|
||||
|
||||
private void SubmitRemote()
|
||||
@@ -288,6 +377,7 @@ public partial class ConnectScreen : Control
|
||||
string address = _address.Text.Trim();
|
||||
if (address.Length == 0)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indica l'indirizzo del server"), error: true);
|
||||
return;
|
||||
}
|
||||
@@ -295,6 +385,7 @@ public partial class ConnectScreen : Control
|
||||
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indirizzo non valido"), error: true);
|
||||
return;
|
||||
}
|
||||
@@ -321,15 +412,41 @@ public partial class ConnectScreen : Control
|
||||
try
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
|
||||
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: false)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
|
||||
}
|
||||
_busy = false;
|
||||
ShowState();
|
||||
if (!_closed) ShowState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prende la sessione appena aperta, se la schermata è ancora aperta e sulla stessa strada;
|
||||
/// altrimenti la chiude (con il suo server locale). Con «Connetti e riprendi» in attesa si entra
|
||||
/// subito in partita.
|
||||
/// </summary>
|
||||
private bool Adopt(GameSession session, bool local)
|
||||
{
|
||||
if (_closed || _local != local)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
_ = session.DisposeAsync();
|
||||
return false;
|
||||
}
|
||||
Attach(session);
|
||||
if (_resumeAfterConnect)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
Play();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Attach(GameSession session)
|
||||
@@ -352,17 +469,20 @@ public partial class ConnectScreen : Control
|
||||
await s.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
|
||||
/// <summary>Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).</summary>
|
||||
public GameSession? TakeSession()
|
||||
{
|
||||
var s = _session;
|
||||
if (s is not null) s.MessageApplied -= OnMessage;
|
||||
_session = null;
|
||||
_awaitingWelcome = null;
|
||||
return s;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
// una connessione ancora in corso si chiude da sola quando arriva (Adopt)
|
||||
_closed = true;
|
||||
if (_session is not null) _ = Release();
|
||||
}
|
||||
|
||||
@@ -372,6 +492,7 @@ public partial class ConnectScreen : Control
|
||||
{
|
||||
if (_session is null) return;
|
||||
_session.Poll();
|
||||
if (_session is null) return; // Play durante Poll: la sessione è passata alla partita
|
||||
if (!_session.IsOpen)
|
||||
{
|
||||
SetStatus(T("Il server ha chiuso la connessione"), error: true);
|
||||
@@ -398,27 +519,65 @@ public partial class ConnectScreen : Control
|
||||
|
||||
private void Resume()
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
|
||||
if (index <= 0 || index > _saveIds.Count)
|
||||
if (_busy || _awaitingWelcome is not null) return;
|
||||
if (_session is null)
|
||||
{
|
||||
// nessuna sessione ancora: «Connetti e riprendi» apre la strada scelta ed entra in partita
|
||||
_resumeAfterConnect = true;
|
||||
if (_local) _ = StartLocal();
|
||||
else SubmitRemote();
|
||||
return;
|
||||
}
|
||||
if (!SessionMatchesMode) return;
|
||||
string id = _selectedSave;
|
||||
var save = _shownSaves?.Saves.FirstOrDefault(s => s.SaveId == id);
|
||||
if (id == CurrentGame || save is null)
|
||||
{
|
||||
Play();
|
||||
return;
|
||||
}
|
||||
string id = _saveIds[index - 1];
|
||||
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
|
||||
AwaitWelcome();
|
||||
_session.Send(new Load { SaveId = id });
|
||||
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso."),
|
||||
CurrentGameText(), save.Name, ConnectedText()), () =>
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
SetStatus($"{T("Caricamento di")} {save.Name}…");
|
||||
AwaitWelcome();
|
||||
_session.Send(new Load { SaveId = id });
|
||||
});
|
||||
}
|
||||
|
||||
private void NewGameOnServer()
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
var summary = _session.World.Summary;
|
||||
SetStatus(T("Creazione della nuova partita sul server…"));
|
||||
AwaitWelcome();
|
||||
// il seme lo sceglie il client: la generazione resta deterministica sul server
|
||||
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
|
||||
if (_session is null || _awaitingWelcome is not null || !SessionMatchesMode) return;
|
||||
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso."),
|
||||
CurrentGameText(), ConnectedText()), () =>
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
var summary = _session.World.Summary;
|
||||
SetStatus(T("Creazione della nuova partita sul server…"));
|
||||
AwaitWelcome();
|
||||
// il seme lo sceglie il client: la generazione resta deterministica sul server
|
||||
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
|
||||
});
|
||||
}
|
||||
|
||||
private void Confirm(string text, Action action)
|
||||
{
|
||||
_onConfirm = action;
|
||||
_confirm.DialogText = text;
|
||||
_confirm.PopupCentered();
|
||||
}
|
||||
|
||||
private string CurrentGameText()
|
||||
{
|
||||
var summary = _session?.World.Summary;
|
||||
return summary is null ? "—" : $"{summary.CompanyName}, {summary.Date}";
|
||||
}
|
||||
|
||||
private string ConnectedText()
|
||||
{
|
||||
var info = _session?.World.Server;
|
||||
return info is null ? "?" : info.Sessions.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
|
||||
@@ -431,9 +590,10 @@ public partial class ConnectScreen : Control
|
||||
_awaitingWelcome = null;
|
||||
Play();
|
||||
}
|
||||
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
|
||||
else if (m is Notification { Event.Day: < 0 } note)
|
||||
{
|
||||
// caricamento o creazione rifiutati: il server risponde con un avviso
|
||||
// caricamento o creazione rifiutati: l'avviso del server ha il giorno −1; gli eventi
|
||||
// del mondo (giorno della partita) arrivano anche qui e non interrompono l'attesa
|
||||
_awaitingWelcome = null;
|
||||
SetStatus(note.Event.Text, error: true);
|
||||
}
|
||||
@@ -459,6 +619,12 @@ public partial class ConnectScreen : Control
|
||||
{
|
||||
var info = _session?.World.Server;
|
||||
var summary = _session?.World.Summary;
|
||||
double now = Time.GetTicksMsec() / 1000.0;
|
||||
if (!ReferenceEquals(info, _infoSeen))
|
||||
{
|
||||
_infoSeen = info;
|
||||
_infoAt = now;
|
||||
}
|
||||
string title;
|
||||
Color dot;
|
||||
if (_busy)
|
||||
@@ -468,62 +634,67 @@ public partial class ConnectScreen : Control
|
||||
}
|
||||
else if (_session is not null)
|
||||
{
|
||||
title = $"{T("Collegato a")} {_session.ServerLabel}";
|
||||
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
|
||||
dot = Palette.Ok;
|
||||
}
|
||||
else
|
||||
{
|
||||
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
|
||||
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
|
||||
dot = Palette.TextSecondary;
|
||||
}
|
||||
_stateTitle.Text = title;
|
||||
_dot.Color = dot;
|
||||
var rows = new List<(string, string)>
|
||||
var cells = new (string, string)[]
|
||||
{
|
||||
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
|
||||
(T("Versione"), info is null ? "—" : $"{info.Version}, {T("protocollo")} {Frame.ProtocolVersion}"),
|
||||
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
|
||||
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds)),
|
||||
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds + (long)(now - _infoAt))),
|
||||
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
|
||||
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
|
||||
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
|
||||
};
|
||||
if (_stateRows.GetChildCount() != rows.Count * 2)
|
||||
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
|
||||
{
|
||||
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
|
||||
foreach (var (caption, _) in rows)
|
||||
{
|
||||
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
|
||||
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
|
||||
}
|
||||
_stateCells[i].Caption.Text = cells[i].Item1;
|
||||
_stateCells[i].Value.Text = cells[i].Item2;
|
||||
}
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
|
||||
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
|
||||
}
|
||||
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
|
||||
_resume.Disabled = !ready;
|
||||
bool ready = SessionMatchesMode && !_busy && _awaitingWelcome is null;
|
||||
// senza sessione «Connetti e riprendi» apre la connessione; «Nuova partita» vuole il server collegato
|
||||
_resume.Disabled = _busy || _awaitingWelcome is not null || (_session is not null && !ready);
|
||||
_newGame.Disabled = !ready;
|
||||
_probe.Disabled = _busy;
|
||||
_localCard.Disabled = _busy;
|
||||
_remoteCard.Disabled = _busy;
|
||||
}
|
||||
|
||||
/// <summary>Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.</summary>
|
||||
private void ShowSaves()
|
||||
{
|
||||
var w = _session!.World;
|
||||
_shownSaves = w.Saves;
|
||||
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
|
||||
_saves.Clear();
|
||||
_saveIds.Clear();
|
||||
string company = w.Summary?.CompanyName ?? "";
|
||||
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
|
||||
var root = _saves.CreateItem();
|
||||
var current = _saves.CreateItem(root);
|
||||
current.SetText(0, $"{T("Partita in corso")} · {w.Summary?.CompanyName ?? ""}");
|
||||
current.SetText(1, w.Summary?.Date ?? "");
|
||||
current.SetText(2, T("in corso"));
|
||||
current.SetMetadata(0, CurrentGame);
|
||||
current.SetCustomColor(2, Palette.Ok);
|
||||
TreeItem selected = current;
|
||||
double now = Time.GetUnixTimeFromSystem();
|
||||
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs))
|
||||
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
|
||||
{
|
||||
_saveIds.Add(s.SaveId);
|
||||
string kind = s.Autosave ? $" ({T("automatico")})" : "";
|
||||
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
|
||||
var item = _saves.CreateItem(root);
|
||||
item.SetText(0, s.Autosave ? $"{s.Name} ({T("automatico")})" : s.Name);
|
||||
item.SetText(1, s.GameDate);
|
||||
item.SetText(2, Ago(now - s.SavedUnixMs / 1000.0));
|
||||
item.SetMetadata(0, s.SaveId);
|
||||
for (int c = 1; c < 3; c++) item.SetCustomColor(c, Palette.TextSecondary);
|
||||
if (s.SaveId == _selectedSave) selected = item;
|
||||
}
|
||||
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
|
||||
// salvataggio scelto sparito dall'elenco: si torna alla partita in corso
|
||||
_selectedSave = selected.GetMetadata(0).AsString();
|
||||
selected.Select(0);
|
||||
}
|
||||
|
||||
private static string Uptime(long seconds)
|
||||
|
||||
@@ -125,6 +125,9 @@ public partial class GameScreen : Node
|
||||
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
|
||||
}
|
||||
|
||||
/// <summary>Chiude lo strumento o la schermata a tutto schermo aperta e torna alla mappa.</summary>
|
||||
public void CloseTools() => _toolbar.Select(Tool.None);
|
||||
|
||||
/// <summary>Apre le «Finanze» a tutto schermo: conto economico, rating e prestiti.</summary>
|
||||
public void OpenFinance()
|
||||
{
|
||||
@@ -210,12 +213,7 @@ public partial class GameScreen : Node
|
||||
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
|
||||
middle.AddChild(mapArea);
|
||||
_mapArea = mapArea;
|
||||
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
|
||||
_toasts.OffsetLeft = 16;
|
||||
_toasts.OffsetRight = -16;
|
||||
_toasts.OffsetTop = 12;
|
||||
_toasts.MouseFilter = Control.MouseFilterEnum.Ignore;
|
||||
mapArea.AddChild(_toasts);
|
||||
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
|
||||
middle.AddChild(side);
|
||||
@@ -241,6 +239,9 @@ public partial class GameScreen : Node
|
||||
sideCol.AddChild(miniHeader);
|
||||
sideCol.AddChild(_minimap);
|
||||
root.AddChild(_ticker);
|
||||
// avvisi sopra tutta l'interfaccia, in alto sull'area visibile: la mappa o la schermata a
|
||||
// tutto schermo (con la mappa nascosta un avviso dentro di lei non si vedrebbe)
|
||||
hud.AddChild(_toasts);
|
||||
|
||||
BuildDisconnectedOverlay(hud);
|
||||
AddChild(_overlay);
|
||||
@@ -350,6 +351,7 @@ public partial class GameScreen : Node
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
PlaceToasts();
|
||||
_session.Poll();
|
||||
_disconnected.Visible = !_session.IsOpen;
|
||||
UpdateChronicle();
|
||||
@@ -837,7 +839,18 @@ public partial class GameScreen : Node
|
||||
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
|
||||
}
|
||||
|
||||
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
|
||||
/// <summary>Allinea gli avvisi in cima all'area visibile: la mappa o la schermata a tutto schermo.</summary>
|
||||
private void PlaceToasts()
|
||||
{
|
||||
if (_toasts.GetChildCount() == 0) return;
|
||||
Control? area = _full.Visible ? _full : _mapArea;
|
||||
if (area is null) return;
|
||||
var rect = area.GetGlobalRect();
|
||||
_toasts.Position = rect.Position + new Vector2(16, 12);
|
||||
_toasts.Size = new Vector2(Math.Max(0, rect.Size.X - 32), 0);
|
||||
}
|
||||
|
||||
/// <summary>Messaggio temporaneo in alto sull'area visibile (mappa o schermata a tutto schermo).</summary>
|
||||
private void Toast(string text, bool error = false)
|
||||
{
|
||||
var notice = UiTheme.Notice(text);
|
||||
@@ -848,5 +861,6 @@ public partial class GameScreen : Node
|
||||
if (IsInstanceValid(notice)) notice.QueueFree();
|
||||
};
|
||||
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
|
||||
PlaceToasts();
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -189,7 +189,7 @@ Record (ognuno chiude con `flags`):
|
||||
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
|
||||
`nextDueDays: i32`, `maintenanceDepot: i32`
|
||||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6)
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6); `day` −1 = avviso del server alla sola sessione che ha chiesto `Load` o `NewGame` e se l'è visto rifiutare (gli eventi del mondo hanno sempre il giorno della partita, ≥ 0)
|
||||
- `WorldEventInfo { id: i32, type: string (id di events.json), entity: u8 (1 città, 2 industria, 7 deposito), entityIndex: i32, good: i32 (−1 se nessuno), startDay: i64 (dopo `day` per un evento estratto oggi, che inizia domani), endDay: i64 (primo giorno senza l'evento: il server lo toglie quel mattino), severity: u8, effects: [f32] }`: `effects` sono i moltiplicatori nell'ordine degli effetti del tipo nel catalogo (ADR 0017)
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
|
||||
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
|
||||
@@ -211,10 +211,10 @@ Record (ognuno chiude con `flags`):
|
||||
- `FinanceLineInfo { kind: u8 (LedgerEntry), section: u8 (0 ricavi, 1 costi, 2 investimenti e finanziamenti) }`, `IncomeColumnInfo { kind: u8 (0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso), year: i32, month: u8 (1–12, 0 per gli anni), values: [AmountInfo] (solo le voci diverse da zero, kind = LedgerEntry, con segno), profit: Money (utile operativo del motore), cashFlow: Money }`, `RatingThresholdInfo { rating: string, minScore, loanRate: f32 }`, `FinanceLoanInfo { loan: i32, principal, remaining: Money, annualRate: f32 (fisso), monthsLeft: i32, payment, nextInterest: Money, maturityDay: i64 }`
|
||||
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
|
||||
- `WarehouseInfo { station, capacity, incoming: i32 (merce propria in viaggio verso la stazione), goods: [WarehouseGoodInfo] }` (stazioni vive della compagnia)
|
||||
- `IndustrySheetInfo { level, maxLevel: u8, efficiency: f32, limit: u8 (fattore più basso sotto 1: 0 nessuno, 1 materie prime, 2 lavoratori, 3 personale, 4 redditività, 5 impianti, 6 giacimento, 7 evento, 8 ferma, 9 inattiva), covInput, covWorkers, covStaff: f32 (coperture medie mobili), coverageWindowDays: i32 (finestra delle coperture), profitFactor, depletion, eventCapacity: f32, reserveFraction: f32 (−1 senza giacimento), storageDays: i32, inputs: [IndustryFlowInfo], outputs: [IndustryFlowInfo], workers: WorkforceInfo, staff: WorkforceInfo, averagePrice: f64 (centesimi; −1 se non calcolabile), annualProfit: Money (utile annuo stimato dalle medie mobili), lastScore, shipped, coverage, profit, score: f32 (punteggio di crescita del trimestre in corso e componenti), upgradeThreshold, downgradeThreshold: f32, upgradeQuarters, quartersAbove: u8, quarterDay, quarterDays: i32, served: bool (servita da un vettore: solo allora cambia livello), servingStations: [i32], servingLine: i32 (−1 nessuna), forSale, buyUnlocked: bool, buyTier: u8, buyProgress: f32 }`
|
||||
- `IndustrySheetInfo { level, maxLevel: u8, efficiency: f32, limit: u8 (fattore più basso sotto 1: 0 nessuno, 1 materie prime, 2 lavoratori, 3 personale, 4 redditività, 5 impianti, 6 giacimento, 7 evento, 8 ferma, 9 inattiva), covInput, covWorkers, covStaff: f32 (coperture medie mobili), coverageWindowDays: i32 (finestra delle coperture), profitFactor, depletion, eventCapacity: f32, reserveFraction: f32 (−1 senza giacimento), storageDays: i32, inputs: [IndustryFlowInfo], outputs: [IndustryFlowInfo], workers: WorkforceInfo, staff: WorkforceInfo, salePrice: f64 (prezzo di vendita del prodotto in centesimi: il prezzo globale del giorno, a cui le industrie vendono al mercato, ADR 0004; −1 senza prodotti o con più prodotti), annualProfit: Money (utile annuo stimato dalle medie mobili), lastScore, shipped, coverage, profit, score: f32 (punteggio di crescita del trimestre in corso e componenti), upgradeThreshold, downgradeThreshold: f32, upgradeQuarters, quartersAbove: u8, quarterDay, quarterDays: i32, served: bool (servita da un vettore: solo allora cambia livello), servingStations: [i32], servingLine: i32 (−1 nessuna), forSale, buyUnlocked: bool, buyTier: u8, buyProgress: f32 }`
|
||||
- `IndustryFlowInfo { good: i32, fullMonth: f32 (a piena capacità, unità al mese), currentMonth: f32 (all'efficienza di oggi), stock, storage: i32, days: f32 (ingressi: giorni di scorta; uscite: giorni al magazzino pieno; −1 senza consumo o produzione), limiting: bool (l'ingresso che limita), partners: [ChainPartnerInfo] }`
|
||||
- `ChainPartnerInfo { kind: u8 (0 industria, 1 hub, 2 città), target: i32, monthlyUnits: f32 (produzione o fabbisogno mensile del partner), price: f64 (centesimi: prezzo globale, locale o dell'hub), line: i32 (linea della compagnia con treni che serve entrambi; −1 non collegato), distanceKm: f32 }`: fornitori per gli ingressi, clienti per le uscite, prima i collegati poi i più vicini, al massimo `industry.outlook.partnersPerGood`
|
||||
- `WorkforceInfo { jobs: i32, present, onSite, coverage: f32, missing: i32, reason: u8 (come `EmploymentRow`), reasonLine: i32, averageMinutes: f32 (−1 senza pendolari in treno), sourceCount: i32, sources: [WorkforceSourceInfo] }` (al massimo `industry.outlook.workforceSources` provenienze)
|
||||
- `WorkforceInfo { jobs: i32, present: f32, onSite: f32 (persone in sede: posti coperti da chi vive negli alloggi dell'industria), coverage: f32, missing: i32, reason: u8 (come `EmploymentRow`), reasonLine: i32, averageMinutes: f32 (−1 senza pendolari in treno visibili), sourceCount: i32, sources: [WorkforceSourceInfo] }` (al massimo `industry.outlook.workforceSources` provenienze). Come nel Registro degli impieghi, provenienze, `sourceCount` e `averageMinutes` contano solo i contratti a piedi, quelli trasportati dalla compagnia della sessione e, se l'industria è sua, quelli di tutti i vettori
|
||||
- `WorkforceSourceInfo { town, headcount: i32, coverage: f32, line: i32, carrier: i32, minutes: f32, walking: bool }`
|
||||
- `WarehouseGoodInfo { good, units: i32 (in magazzino), buyPrice: f64 (centesimi, prossima unità; −1 nessun venditore), buyUnits: i32, sellPrice: f64 (−1 nessun compratore), sellUnits: i32 }` (beni in magazzino o scambiabili nel bacino)
|
||||
|
||||
|
||||
+12
-9
@@ -148,7 +148,8 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- fornitori e clienti (industrie, hub, città) con fabbisogno o produzione mensile, prezzo (globale, locale o dell'hub), distanza e la linea della compagnia che li collega;
|
||||
- forza lavoro dai contratti dei pendolari: posti, presenti, al lavoro, mancanti, motivo, provenienze, viaggio medio;
|
||||
- crescita: punteggio del trimestre in corso con le componenti, soglie, trimestri sopra soglia, servita o no;
|
||||
- prezzo medio realizzato, utile annuo stimato, stazioni e linea che la servono, sblocco dell'acquisto con l'avanzamento.
|
||||
- prezzo di vendita (prezzo globale del giorno), utile annuo stimato, stazioni e linea che la servono, sblocco dell'acquisto con l'avanzamento.
|
||||
La forza lavoro mostra solo i contratti a piedi, quelli della compagnia della sessione e, se l'industria è sua, quelli di tutti i vettori (come il Registro degli impieghi).
|
||||
`IndustryMath.GrowthScore` è ora l'unica formula del punteggio (anche per `IndustrySystem.Quarter`, hash invariati). Parametri di presentazione in `balance.json → industry.outlook` (`partnersPerGood` 3, `workforceSources` 4).
|
||||
- protocollo:
|
||||
- blocco 1 di `IndustryCard`: `IndustrySheetInfo` con `IndustryFlowInfo`, `ChainPartnerInfo`, `WorkforceInfo`, `WorkforceSourceInfo`;
|
||||
@@ -164,14 +165,16 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- schermata iniziale e di connessione come l'immagine 09 (`ConnectScreen`, al posto di `MenuScreen`):
|
||||
- mappa decorativa con il titolo e «Dove gira il motore di gioco?»;
|
||||
- «Gioca in locale» e «Connetti a un server» con indirizzo, token e «Ricorda questo server»;
|
||||
- stato del server: versione, sistema, attivo da, tick al secondo, latenza, client collegati;
|
||||
- «Partite salvate sul server», «Connetti e riprendi» (`Load` e attesa del `Welcome`), «Nuova partita sul server»;
|
||||
- testi in `strings.csv`; schermate `19_scheda_industria` e `20_connessione` in coda al pilota automatico (non provate qui: manca l'editor).
|
||||
- all'apertura avvia la strada scelta l'ultima volta (server locale, o verifica del server ricordato); cambiando strada la sessione dell'altra si chiude; senza sessione «Connetti e riprendi» la apre ed entra in partita; il cambio di lingua passa la sessione alla schermata nuova;
|
||||
- stato del server in tre colonne: versione e protocollo, sistema, attivo da (avanza sul client), tick al secondo, latenza, client collegati;
|
||||
- «Partite salvate sul server» in tre colonne (nome, data di gioco, quanto tempo fa), scelta tenuta per id; «Connetti e riprendi» (`Load` e attesa del `Welcome`), «Nuova partita sul server», entrambe con conferma perché sostituiscono il mondo per tutti; il rifiuto si riconosce dal giorno −1 dell'avviso del server;
|
||||
- gli avvisi in alto (esiti dei comandi) compaiono anche sulle schermate a tutto schermo; l'esito dell'offerta di acquisto compare accanto al pulsante;
|
||||
- testi in `strings.csv`; pilota automatico: `12_industria` e `12b_industria_scorte` sono ora la scheda a tutto schermo di un'industria dei privati (in cima con l'avviso dell'acquisto rifiutato, e in fondo), non più la mappa con il pannello laterale; `19_scheda_industria` e `20_connessione` (la schermata su un suo `CanvasLayer` sopra l'interfaccia) in coda (non provate qui: manca l'editor).
|
||||
- test:
|
||||
- `Economy/IndustryOutlookTests.cs`, 5: scheda dell'acciaieria servita (fornitore collegato, clienti al prezzo locale e all'hub, stazione e linea, crescita, sblocco, hash invariato), forza lavoro dai contratti, fattore limitante per ogni causa, pesi del punteggio, round-trip nella `IndustryCard` e carta vecchia senza scheda;
|
||||
- `ServerTests`: scheda via WebSocket attesa come risposta nuova, `ServerInfo` nel `Welcome`, elenco dei salvataggi dopo `Save`;
|
||||
- campioni del protocollo con i blocchi nuovi.
|
||||
200 test (181 senza i lenti).
|
||||
- `Economy/IndustryOutlookTests.cs`, 6: scheda dell'acciaieria servita (fornitore collegato, clienti al prezzo locale e all'hub, stazione e linea, crescita, sblocco, prezzo di vendita, hash invariato), forza lavoro dai contratti, pendolari di altri vettori nascosti (visibili al vettore e al proprietario), fattore limitante per ogni causa, pesi del punteggio, round-trip nella `IndustryCard` e carta vecchia senza scheda;
|
||||
- `ServerTests`: scheda via WebSocket attesa come risposta nuova, `ServerInfo` nel `Welcome`, elenco dei salvataggi dopo `Save`, `Load` rifiutato con l'avviso del server al giorno −1;
|
||||
- campioni del protocollo con i blocchi nuovi; `Welcome` senza blocco 1 (server F5) con stato del server assente nella copia locale.
|
||||
202 test (183 senza i lenti).
|
||||
- Restano della F6: ere e obsolescenza, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
@@ -183,7 +186,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
|
||||
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06, la scheda dell'industria alla 07, «La tua scalata» alla 08 e la schermata di connessione alla 09 (F6, non ancora provati in Godot: qui manca l'editor). Della 07 mancano le quantità consegnate su ogni collegamento della catena (il motore non le registra: si mostrano produzione o fabbisogno del partner, prezzo e linea) e quantità diverse per ingresso (il consumo segue la ricetta); lo stato del server nella 09 è quello del collegamento (ADR 0021).
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06, la scheda dell'industria alla 07, «La tua scalata» alla 08 e la schermata di connessione alla 09 (F6, non ancora provati in Godot: qui manca l'editor). Della 07 mancano le quantità consegnate su ogni collegamento della catena (il motore non le registra: si mostrano produzione o fabbisogno del partner, prezzo e linea) e quantità diverse per ingresso (il consumo segue la ricetta); lo stato del server nella 09 è quello del collegamento (ADR 0021): «Client collegati» resta quello del `Welcome` e «Attivo da» avanza con l'orologio del client; il server non salva prima di `Load` o `NewGame` (la conferma lo dice).
|
||||
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
|
||||
@@ -44,15 +44,20 @@ Il client non contiene logica di gioco e il formato dei salvataggi non deve camb
|
||||
- la linea che collega: la linea della compagnia, con treni, il cui bacino tocca sia l'industria
|
||||
sia il partner;
|
||||
- l'ordine: prima i collegati, poi per distanza;
|
||||
- la forza lavoro: posti, presenti, al lavoro, copertura, mancanti, motivo e provenienze, dai
|
||||
contratti dei pendolari (`World.Commutes`) raggruppati per città, linea e vettore;
|
||||
- la forza lavoro: posti, presenti, persone in sede, copertura, mancanti, motivo e provenienze,
|
||||
dai contratti dei pendolari (`World.Commutes`) raggruppati per città, linea e vettore. Come il
|
||||
Registro degli impieghi, la compagnia vede i contratti a piedi, quelli che trasporta lei e, se
|
||||
l'industria è sua, quelli di tutti i vettori: i dati degli altri vettori non escono;
|
||||
- la crescita: il punteggio del trimestre in corso e le sue componenti. `IndustryMath.GrowthScore`
|
||||
è ora l'unica formula: la usa anche `IndustrySystem.Quarter`, con aritmetica identica (test di
|
||||
determinismo invariati). Calcola anche le soglie, i trimestri sopra soglia e se un vettore serve
|
||||
l'industria (solo allora il livello cambia);
|
||||
- prezzo medio realizzato ≈ `RevenueEma × QuarterDays / QuarterShipped`, utile annuo dalle medie
|
||||
mobili, stazioni che servono l'industria e avanzamento verso il livello che sblocca l'acquisto
|
||||
(`ClimbOutlook`).
|
||||
- prezzo di vendita del prodotto: il prezzo globale del giorno, a cui le industrie vendono al
|
||||
mercato (ADR 0004). Una stima dai ricavi (`RevenueEma × QuarterDays / QuarterShipped`) mescolerebbe
|
||||
una media mobile con i totali del trimestre in corso e sbaglierebbe a inizio trimestre o quando
|
||||
la produzione cambia;
|
||||
- utile annuo dalle medie mobili, stazioni che servono l'industria e avanzamento verso il livello
|
||||
che sblocca l'acquisto (`ClimbOutlook`).
|
||||
2. I nuovi parametri di presentazione stanno in `balance.json → industry.outlook`:
|
||||
- `partnersPerGood` (3): partner per bene;
|
||||
- `workforceSources` (4): provenienze dei pendolari.
|
||||
|
||||
@@ -70,7 +70,7 @@ public sealed class WorkforceOutlook
|
||||
{
|
||||
public required int Jobs { get; init; }
|
||||
public required double Present { get; init; }
|
||||
/// <summary>Quota coperta da chi vive in sede (alloggi dell'industria).</summary>
|
||||
/// <summary>Persone in sede: posti coperti da chi vive negli alloggi dell'industria (posti × quota in sede).</summary>
|
||||
public required double OnSite { get; init; }
|
||||
/// <summary>Copertura media su coverageWindowDays (entra nell'efficienza).</summary>
|
||||
public required double Coverage { get; init; }
|
||||
@@ -78,11 +78,11 @@ public sealed class WorkforceOutlook
|
||||
public required int Missing { get; init; }
|
||||
public required UncoveredReason Reason { get; init; }
|
||||
public required LineId ReasonLine { get; init; }
|
||||
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone); −1 senza pendolari in treno.</summary>
|
||||
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone) dei contratti visibili; −1 se nessuno.</summary>
|
||||
public required double AverageMinutes { get; init; }
|
||||
/// <summary>Provenienze più numerose (al massimo industry.outlook.workforceSources).</summary>
|
||||
public required List<WorkforceSource> Sources { get; init; }
|
||||
/// <summary>Provenienze in tutto (anche quelle non elencate).</summary>
|
||||
/// <summary>Provenienze visibili in tutto (anche quelle non elencate).</summary>
|
||||
public required int SourceCount { get; init; }
|
||||
}
|
||||
|
||||
@@ -126,8 +126,11 @@ public sealed class IndustryOutlookReport
|
||||
public required List<IndustryFlow> Outputs { get; init; }
|
||||
public required WorkforceOutlook Workers { get; init; }
|
||||
public required WorkforceOutlook Staff { get; init; }
|
||||
/// <summary>Ricavo medio per unità del prodotto (centesimi); −1 se non stimabile (nessuna vendita o più prodotti).</summary>
|
||||
public required double AveragePrice { get; init; }
|
||||
/// <summary>
|
||||
/// Prezzo di vendita del prodotto (centesimi): il prezzo globale del giorno, quello a cui le
|
||||
/// industrie vendono al mercato (ADR 0004); −1 senza prodotti o con più prodotti.
|
||||
/// </summary>
|
||||
public required double SalePrice { get; init; }
|
||||
public required Money AnnualProfit { get; init; }
|
||||
public required GrowthOutlook Growth { get; init; }
|
||||
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.</summary>
|
||||
@@ -211,10 +214,9 @@ public static class IndustryOutlook
|
||||
});
|
||||
}
|
||||
|
||||
// ricavo medio per unità: ricavi medi giornalieri / unità spedite al giorno nel trimestre (un solo prodotto)
|
||||
double averagePrice = -1;
|
||||
if (recipe.Outputs.Count == 1 && ind.QuarterShipped > 0 && ind.QuarterDays > 0)
|
||||
averagePrice = ind.RevenueEma * ind.QuarterDays / ind.QuarterShipped;
|
||||
// prezzo di vendita: le industrie vendono al prezzo globale del giorno (ADR 0004). Una media dei
|
||||
// ricavi mescolerebbe la media mobile dei ricavi con i totali del trimestre in corso
|
||||
double salePrice = recipe.Outputs.Count == 1 ? w.Market.GlobalPrice[recipe.Outputs[0].GoodIndex] : -1;
|
||||
|
||||
var buyTier = data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.BuyIndustry);
|
||||
var owner = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
@@ -240,9 +242,9 @@ public static class IndustryOutlook
|
||||
StorageDays = ind.Def.StorageDays,
|
||||
Inputs = inputs,
|
||||
Outputs = outputs,
|
||||
Workers = Workforce(w, ind, PaxClass.Worker),
|
||||
Staff = Workforce(w, ind, PaxClass.Staff),
|
||||
AveragePrice = averagePrice,
|
||||
Workers = Workforce(w, ind, PaxClass.Worker, company),
|
||||
Staff = Workforce(w, ind, PaxClass.Staff, company),
|
||||
SalePrice = salePrice,
|
||||
AnnualProfit = Money.FromCentsRounded(IndustryMath.AnnualProfit(w, ind)),
|
||||
Growth = new GrowthOutlook
|
||||
{
|
||||
@@ -317,8 +319,13 @@ public static class IndustryOutlook
|
||||
return new EfficiencyFactors(pf, mc, depletion, capacity, reserve, stopped, limit);
|
||||
}
|
||||
|
||||
/// <summary>Lavoratori o personale: presenti, quota in sede, posti scoperti con il motivo e provenienze per città e linea.</summary>
|
||||
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls)
|
||||
/// <summary>
|
||||
/// Lavoratori o personale: presenti, persone in sede, posti scoperti con il motivo e provenienze per
|
||||
/// città e linea. Come il Registro degli impieghi (Projection.Employment), la compagnia vede i
|
||||
/// contratti a piedi e quelli che trasporta lei; quelli degli altri vettori solo se l'industria è
|
||||
/// sua. Presenti e copertura restano quelli dell'industria.
|
||||
/// </summary>
|
||||
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls, CompanyId company)
|
||||
{
|
||||
var ib = w.Data.Balance.Industry;
|
||||
bool staff = cls == PaxClass.Staff;
|
||||
@@ -331,6 +338,7 @@ public static class IndustryOutlook
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Workplace != me || c.Category != cls || c.Headcount <= 0) continue;
|
||||
if (!Visible(c, ind, company)) continue;
|
||||
var line = c.Route.Count > 0 ? c.Route[0] : LineId.None;
|
||||
int at = groups.FindIndex(x => x.Town == c.Town && x.Line == line && x.Carrier == c.Carrier && x.Walking == c.Walking);
|
||||
if (at < 0)
|
||||
@@ -370,6 +378,10 @@ public static class IndustryOutlook
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Contratto che la compagnia può vedere: a piedi, trasportato da lei, o verso una sua industria.</summary>
|
||||
public static bool Visible(CommuteContract c, Industry ind, CompanyId company) =>
|
||||
c.Walking || (company.IsValid && (c.Carrier == company || ind.Owner == company));
|
||||
|
||||
/// <summary>
|
||||
/// Fornitori di un input: industrie attive che producono il bene (unità al mese al ritmo attuale,
|
||||
/// prezzo globale: le industrie vendono al mercato, ADR 0004) e hub (capacità mensile, prezzo
|
||||
|
||||
@@ -92,7 +92,7 @@ public sealed class WorkforceSourceInfo
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lavoratori o personale: posti, presenti, quota in sede, copertura media, posti scoperti, motivo
|
||||
/// Lavoratori o personale: posti, presenti, persone in sede (posti coperti da chi vive negli alloggi), copertura media, posti scoperti, motivo
|
||||
/// (UncoveredReason) e linea del motivo, viaggio medio in treno (−1 senza), provenienze elencate e in tutto.
|
||||
/// </summary>
|
||||
public sealed class WorkforceInfo
|
||||
@@ -154,8 +154,8 @@ public sealed class IndustrySheetInfo
|
||||
public List<IndustryFlowInfo> Outputs { get; init; } = [];
|
||||
public WorkforceInfo Workers { get; init; } = new();
|
||||
public WorkforceInfo Staff { get; init; } = new();
|
||||
/// <summary>Ricavo medio per unità del prodotto (centesimi), −1 se non stimabile.</summary>
|
||||
public double AveragePrice { get; init; } = -1;
|
||||
/// <summary>Prezzo di vendita del prodotto (centesimi): prezzo globale del giorno; −1 senza prodotti o con più prodotti.</summary>
|
||||
public double SalePrice { get; init; } = -1;
|
||||
public Money AnnualProfit { get; init; }
|
||||
/// <summary>Crescita trimestrale: ultimo punteggio, componenti e punteggio del trimestre in corso, soglie, trimestri.</summary>
|
||||
public float LastScore { get; init; }
|
||||
@@ -189,7 +189,7 @@ public sealed class IndustrySheetInfo
|
||||
foreach (var f in Outputs) f.Write(ref w);
|
||||
Workers.Write(ref w);
|
||||
Staff.Write(ref w);
|
||||
w.F64(AveragePrice); w.Money(AnnualProfit);
|
||||
w.F64(SalePrice); w.Money(AnnualProfit);
|
||||
w.F32(LastScore); w.F32(Shipped); w.F32(Coverage); w.F32(Profit); w.F32(Score); w.F32(UpgradeThreshold); w.F32(DowngradeThreshold);
|
||||
w.U8(UpgradeQuarters); w.U8(QuartersAbove); w.I32(QuarterDay); w.I32(QuarterDays); w.Bool(Served);
|
||||
w.Count(ServingStations.Count);
|
||||
@@ -213,7 +213,7 @@ public sealed class IndustrySheetInfo
|
||||
for (int n = r.Count(), i = 0; i < n; i++) outputs.Add(IndustryFlowInfo.Read(ref r));
|
||||
var workers = WorkforceInfo.Read(ref r);
|
||||
var staff = WorkforceInfo.Read(ref r);
|
||||
double averagePrice = r.F64();
|
||||
double salePrice = r.F64();
|
||||
var profit = r.Money();
|
||||
float last = r.F32(), shipped = r.F32(), coverage = r.F32(), profitShare = r.F32(), score = r.F32(), up = r.F32(), down = r.F32();
|
||||
byte upQuarters = r.U8(), above = r.U8();
|
||||
@@ -225,7 +225,7 @@ public sealed class IndustrySheetInfo
|
||||
{
|
||||
Level = level, MaxLevel = maxLevel, Efficiency = efficiency, Limit = limit, CovInput = covInput, CovWorkers = covWorkers, CovStaff = covStaff,
|
||||
CoverageWindowDays = window, ProfitFactor = pf, Depletion = depletion, EventCapacity = eventCapacity, ReserveFraction = reserve, StorageDays = storageDays,
|
||||
Inputs = inputs, Outputs = outputs, Workers = workers, Staff = staff, AveragePrice = averagePrice, AnnualProfit = profit,
|
||||
Inputs = inputs, Outputs = outputs, Workers = workers, Staff = staff, SalePrice = salePrice, AnnualProfit = profit,
|
||||
LastScore = last, Shipped = shipped, Coverage = coverage, Profit = profitShare, Score = score, UpgradeThreshold = up, DowngradeThreshold = down,
|
||||
UpgradeQuarters = upQuarters, QuartersAbove = above, QuarterDay = quarterDay, QuarterDays = quarterDays, Served = served, ServingStations = stations,
|
||||
ServingLine = r.I32(), ForSale = r.Bool(), BuyUnlocked = r.Bool(), BuyTier = r.U8(), BuyProgress = r.F32(),
|
||||
|
||||
@@ -284,11 +284,18 @@ public sealed class GameHost : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static Notification Notice(string text) => new()
|
||||
/// <summary>
|
||||
/// Avviso del server a una sola sessione (Load o NewGame rifiutati): giorno −1, così il client lo
|
||||
/// distingue dagli eventi del mondo, che hanno sempre il giorno della partita.
|
||||
/// </summary>
|
||||
public static Notification Notice(string text) => new()
|
||||
{
|
||||
Event = new EventInfo { Severity = (byte)EventSeverity.Warning, Text = text },
|
||||
Event = new EventInfo { Day = ServerNoticeDay, Severity = (byte)EventSeverity.Warning, Text = text },
|
||||
};
|
||||
|
||||
/// <summary>Giorno degli avvisi del server (vedi <see cref="Notice"/>).</summary>
|
||||
public const long ServerNoticeDay = -1;
|
||||
|
||||
public Protocol.Messages.SaveInfo SaveNow(string name)
|
||||
{
|
||||
var info = _saves.Save(_world, name);
|
||||
|
||||
@@ -534,7 +534,7 @@ public static class Projection
|
||||
CovInput = (float)r.CovInput, CovWorkers = (float)r.CovWorkers, CovStaff = (float)r.CovStaff, CoverageWindowDays = r.CoverageWindowDays,
|
||||
ProfitFactor = (float)r.ProfitFactor, Depletion = (float)r.Depletion, EventCapacity = (float)r.EventCapacity, ReserveFraction = (float)r.ReserveFraction,
|
||||
StorageDays = r.StorageDays, Inputs = r.Inputs.Select(Flow).ToList(), Outputs = r.Outputs.Select(Flow).ToList(),
|
||||
Workers = Work(r.Workers), Staff = Work(r.Staff), AveragePrice = r.AveragePrice, AnnualProfit = r.AnnualProfit,
|
||||
Workers = Work(r.Workers), Staff = Work(r.Staff), SalePrice = r.SalePrice, AnnualProfit = r.AnnualProfit,
|
||||
LastScore = (float)g.LastScore, Shipped = (float)g.Current.Shipped, Coverage = (float)g.Current.Coverage, Profit = (float)g.Current.Profit,
|
||||
Score = (float)g.Current.Score, UpgradeThreshold = (float)g.UpgradeThreshold, DowngradeThreshold = (float)g.DowngradeThreshold,
|
||||
UpgradeQuarters = (byte)Math.Clamp(g.UpgradeQuarters, 0, 255), QuartersAbove = (byte)Math.Clamp(g.QuartersAbove, 0, 255),
|
||||
|
||||
@@ -128,6 +128,46 @@ public static class IndustryOutlookTests
|
||||
Assert.Equal(tier.Level, r.BuyTier);
|
||||
Assert.Approx(ClimbOutlook.Requirements(w, w.Player, tier).Progress, r.BuyProgress, 1e-12);
|
||||
Assert.Approx(IndustryMath.AnnualProfit(w, steel), r.AnnualProfit.Cents, 1);
|
||||
|
||||
// prezzo di vendita: il prezzo globale del giorno del prodotto (ADR 0004)
|
||||
Assert.Equal(w.Market.GlobalPrice[steelGood], r.SalePrice);
|
||||
}
|
||||
|
||||
[Test(Description = "La scheda non mostra i pendolari portati da altri vettori, come il Registro degli impieghi; li mostra solo se l'industria è della compagnia")]
|
||||
public static void WorkforceHidesOtherCarriers()
|
||||
{
|
||||
var (f, line, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var rival = new CompanyId(f.Me.Value + 1);
|
||||
var before = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
var town = w.Towns.First();
|
||||
var contract = new CommuteContract
|
||||
{
|
||||
Id = new ContractId(w.NextIds.Contract++), Town = town.Id, Workplace = WorkplaceRef.Of(steel.Id), Category = PaxClass.Worker,
|
||||
Headcount = 120, Carrier = rival, ExpectedMinutes = 400, Coverage = 0.9,
|
||||
};
|
||||
contract.Route.Add(new LineId(line));
|
||||
w.Commutes.Add(contract);
|
||||
|
||||
// per la compagnia del giocatore il contratto del rivale non c'è: né provenienza né viaggio medio
|
||||
var mine = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
Assert.False(mine.Sources.Any(x => x.Carrier == rival), "nessuna provenienza del rivale");
|
||||
Assert.Equal(before.SourceCount, mine.SourceCount);
|
||||
Assert.Equal(before.AverageMinutes, mine.AverageMinutes);
|
||||
var sheet = Projection.IndustryCard(w, steel, f.Me).Sheet!;
|
||||
Assert.False(sheet.Workers.Sources.Any(x => x.Carrier == rival.Value), "nemmeno nel messaggio");
|
||||
|
||||
// il rivale vede il suo contratto
|
||||
var theirs = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, rival);
|
||||
Assert.True(theirs.Sources.Any(x => x.Carrier == rival && x.Headcount == 120 && x.Town == town.Id), "il vettore vede i suoi pendolari");
|
||||
Assert.True(theirs.AverageMinutes > 0, "viaggio medio dai suoi contratti");
|
||||
|
||||
// l'industria della compagnia mostra i pendolari di tutti i vettori
|
||||
steel.Owner = f.Me;
|
||||
var owned = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
Assert.True(owned.Sources.Any(x => x.Carrier == rival), "il proprietario vede tutti i vettori");
|
||||
Assert.Equal(before.SourceCount + 1, owned.SourceCount);
|
||||
}
|
||||
|
||||
[Test(Description = "Forza lavoro della scheda: presenti, quota in sede, posti scoperti e provenienze dai contratti di pendolarismo")]
|
||||
@@ -140,7 +180,7 @@ public static class IndustryOutlookTests
|
||||
{
|
||||
foreach (var cls in new[] { PaxClass.Worker, PaxClass.Staff })
|
||||
{
|
||||
var o = IndustryOutlook.Workforce(w, ind, cls);
|
||||
var o = IndustryOutlook.Workforce(w, ind, cls, f.Me);
|
||||
bool staff = cls == PaxClass.Staff;
|
||||
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
|
||||
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
|
||||
@@ -148,7 +188,7 @@ public static class IndustryOutlookTests
|
||||
Assert.Equal(present, o.Present);
|
||||
Assert.Approx(jobs * (staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare), o.OnSite, 1e-9);
|
||||
Assert.Equal((int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)), o.Missing);
|
||||
var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0).ToList();
|
||||
var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0 && IndustryOutlook.Visible(c, ind, f.Me)).ToList();
|
||||
Assert.True(o.Sources.Count <= ib.Outlook.WorkforceSources && o.Sources.Count <= o.SourceCount, "provenienze entro il limite");
|
||||
if (o.SourceCount <= ib.Outlook.WorkforceSources)
|
||||
Assert.Equal(contracts.Sum(c => c.Headcount), o.Sources.Sum(s => s.Headcount));
|
||||
|
||||
@@ -144,7 +144,7 @@ public static class ProtocolTests
|
||||
Sources = [new WorkforceSourceInfo { Town = 0, Headcount = 120, Coverage = 0.95f, Line = 1, Carrier = 0, Minutes = 35, Walking = false }],
|
||||
},
|
||||
Staff = new WorkforceInfo { Jobs = 20, Present = 12, Missing = 8, Reason = 4, ReasonLine = -1, AverageMinutes = -1 },
|
||||
AveragePrice = 15_600, AnnualProfit = new Money(41_000_000), LastScore = 0.62f, Shipped = 0.8f, Coverage = 0.6f, Profit = 0.55f, Score = 0.69f,
|
||||
SalePrice = 15_600, AnnualProfit = new Money(41_000_000), LastScore = 0.62f, Shipped = 0.8f, Coverage = 0.6f, Profit = 0.55f, Score = 0.69f,
|
||||
UpgradeThreshold = 0.75f, DowngradeThreshold = 0.35f, UpgradeQuarters = 2, QuartersAbove = 1, QuarterDay = 45, QuarterDays = 90, Served = true,
|
||||
ServingStations = [2, 7], ServingLine = 1, ForSale = true, BuyUnlocked = false, BuyTier = 3, BuyProgress = 0.58f,
|
||||
},
|
||||
@@ -369,6 +369,31 @@ public static class ProtocolTests
|
||||
foreach (var id in Enum.GetValues<MessageId>()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
|
||||
}
|
||||
|
||||
[Test(Description = "Un Welcome senza blocco 1 (server F5) si legge con lo stato del server assente, stessi byte, e la copia locale lo lascia null")]
|
||||
public static void WelcomeWithoutServerInfoRoundTrips()
|
||||
{
|
||||
var old = new Welcome
|
||||
{
|
||||
SessionId = 9,
|
||||
Summary = new WorldSummary { Seed = 1, SizeKm = 64, StartYear = 1850, Date = "1 gennaio 1850", CompanyName = "Società", WidthCells = 64, HeightCells = 64, CellSizeM = 100, ChunkCells = 64 },
|
||||
DataHash = 7,
|
||||
};
|
||||
byte[] frame = Frame.Encode(old);
|
||||
var back = (Welcome)Frame.Decode(frame);
|
||||
Assert.True(back.Server is null, "nessuno stato del server");
|
||||
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(back)), "stessi byte");
|
||||
Assert.Equal(old.SessionId, back.SessionId);
|
||||
Assert.Equal("Società", back.Summary.CompanyName);
|
||||
|
||||
// la copia locale del client resta senza stato del server, anche dopo un Welcome che lo aveva
|
||||
var world = new RailEnterprise.Protocol.Client.ClientWorld(TestData.Data);
|
||||
var withInfo = (Welcome)Frame.Decode(Frame.Encode(new Welcome { Summary = old.Summary, Server = new ServerInfo { Version = "0.6.1" } }));
|
||||
world.Apply(withInfo);
|
||||
Assert.True(world.Server is not null, "stato del server dal Welcome F6");
|
||||
world.Apply(back);
|
||||
Assert.True(world.Server is null, "un Welcome F5 azzera lo stato del server");
|
||||
}
|
||||
|
||||
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
|
||||
public static void EveryCommandRoundTrips()
|
||||
{
|
||||
|
||||
@@ -496,6 +496,12 @@ public static class ServerTests
|
||||
Assert.Equal(1, list.Saves.Count);
|
||||
Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId);
|
||||
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
|
||||
// un Load rifiutato risponde con un avviso del server: giorno −1, distinto dagli eventi del mondo
|
||||
await client.Connection.SendAsync(new Load { SaveId = "non-esiste" });
|
||||
var refused = await client.WaitFor(() => client.Received.OfType<Notification>().FirstOrDefault(n => n.Event.Day < 0), "avviso del Load rifiutato");
|
||||
Assert.Equal(GameHost.ServerNoticeDay, refused.Event.Day);
|
||||
Assert.True(refused.Event.Text.StartsWith("Caricamento non riuscito", StringComparison.Ordinal), refused.Event.Text);
|
||||
Assert.False(client.Received.OfType<Notification>().Any(n => n.Event.Day >= 0 && n.Event.Text.StartsWith("Caricamento", StringComparison.Ordinal)), "nessun evento del mondo scambiato per l'avviso");
|
||||
}
|
||||
// ripresa con lo stesso id: stessa sessione, stato rimandato per intero
|
||||
await using (var again = await TestClient.ConnectAsync(server, resume: sessionId))
|
||||
|
||||
Reference in new issue
Block a user