diff --git a/client/ViaFerrea.Client/assets/i18n/strings.csv b/client/ViaFerrea.Client/assets/i18n/strings.csv
index 597e0f9..1f1b9a2 100644
--- a/client/ViaFerrea.Client/assets/i18n/strings.csv
+++ b/client/ViaFerrea.Client/assets/i18n/strings.csv
@@ -1,27 +1,52 @@
keys,it,en
Abitanti,,Population
Accetta,,Accept
+Acquista,,Buy
+Aderisci con le tue azioni,,Tender your shares
Aggiorna,,Refresh
+Alto,,High
Ambra,,Amber
+Amministrazione controllata,,Receivership
+Ammoderna,,Upgrade
+Ammodernamento,,Upgrade
+Ammodernamento di livello,,Level upgrade
+Ammodernamento programmato,,Upgrade scheduled
+Ancora nessun fatto da raccontare.,,Nothing to tell yet.
+Anno,,Year
Annulla,,Cancel
Anteprima non disponibile: ,,Preview unavailable:
+Appartiene a,,Belongs to
Assegna,,Assign
+Asta degli attivi,,Asset auction
Attendi il pieno alla prima fermata (max 2 giorni),,Wait for full load at the first stop (max 2 days)
Attiva,,Active
Avvio del server locale…,,Starting the local server…
+Azioni proprie (non votano),,Treasury shares (no vote)
+Base,,Base
+Base d'asta,,Reserve price
Binari,,Track
Binari di stazione,,Platforms
Blu,,Blue
+Budget di manutenzione,,Maintenance budget
+C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra.,,There is already a bid on this company: see the list on the left.
Cantiere,,Construction
+Capitalizz.,,Market cap
+Capitalizzazione,,Market cap
Carico,,Load
Cartella di manutenzione,,Maintenance record
Cartella in arrivo dal server…,,Record on its way from the server…
Cassa,,Cash
+Cassa dell'industria,,Industry cash
+Cavaliere bianco,,White knight
Celeste,,Light blue
+"Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita.",,"The highest bidder at closing buys the bankrupt company's trains, track, stations and industries."
Chiedi il prestito,,Request loan
+Chiudi,,Close
Chiusa,,Closed
+Chiusura,,Closes
Classe,,Class
Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea.,,Click a track to place a block signal: it splits the edge into sections and raises line capacity.
+"Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e",,"Click a company for its card, shareholder register and actions. Share price: the greater of net worth and"
"Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo.",,"Click a station, depot or free track to demolish it; part of the cost is refunded."
"Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare.",,"Click the map to place route points (Shift: no 45° snap), Enter to build, right click to cancel."
"Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni.",,"Click the map near a track, then connect it with the Track tool. Vehicles are bought and trains composed in the depot."
@@ -31,77 +56,160 @@ Collegamento in corso…,,Connecting…
Collegamento non riuscito,,Connection failed
Collegati,,Connect
Collegati a un server,,Connect to a server
+Colloca il,,Float
Come la linea o la flotta,,Same as line or fleet
+Compagnia,,Company
+Compagnia fallita: nessuna asta in corso.,,Bankrupt company: no auction running.
+Compagnie,,Companies
+Compagnie e borsa,,Companies and stock exchange
Componi,,Compose
+Compra,,Buy
Compra veicoli,,Buy vehicles
+Compravendita di azioni,,Share trading
Condizione,,Condition
Connessione persa,,Connection lost
Consuma,,Consumes
+Continua come osservatore,,Continue as observer
+Controllo,,Control
+Controvalore,,Value
Convenzioni,,Agreements
Coperto dalla riserva,,Covered by reserve
Costi dell'anno,,Costs this year
Costo,,Cost
+Costo dell'ammodernamento,,Upgrade cost
Costruisci,,Build
Crea linea,,Create line
+Cronaca finale,,Final chronicle
+Cronaca provvisoria,,Chronicle so far
Dati del gioco non trovati o non validi.,,Game data missing or invalid.
+Dati insufficienti,,Not enough data
+Debito,,Debt
Demolisci,,Demolish
Depositi e officine,,Depots and workshops
Deposito,,Depot
Deragliamento,,Derailment
+Difese del bersaglio,,Target's defences
Disconnesso,,Disconnected
+Dividendi (12 mesi),,Dividends (12 months)
+Dividendo,,Dividend
+Dividendo per azione,,Dividend per share
+Dividendo straordinario,,Extra dividend
Doppio binario,,Double track
Dove lavorano gli abitanti,,Where residents work
Efficienza,,Efficiency
Elettrificato,,Electrified
Esci,,Quit
+Espansiva,,Expansive
+Fallimento,,Bankruptcy
+Fatti salienti,,Highlights
+Fermo,,Shutdown
+Fermo programmato,,Planned shutdown
Finanze,,Finance
"Flotta, dal treno più usurato",,"Fleet, most worn first"
+Fondatore (tu),,Founder (you)
+Fondatore privato,,Private founder
+Fusione,,Merger
Galleria,,Tunnel
Gallerie,,Tunnels
Gestionale ferroviario dall'alto,,Top-down railway management
+Gestisci l'industria,,Manage the industry
Grano,,Wheat
Guasti nell'anno,,Failures this year
+Guasto,,Breakdown
Guasto grave,,Major failure
Guasto lieve,,Minor failure
+Hai aderito con tutte le tue azioni.,,You tendered all your shares.
+"Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi.",,"The world goes on: AI companies keep playing and you can watch as an observer, but the server no longer accepts your commands."
Il server non risponde più. La partita continua sul server.,,The server is not responding. The game goes on on the server.
+Impegno massimo,,Maximum commitment
Impianti,,Plant
Impieghi,,Jobs
+"In amministrazione controllata compri anche dal controllante, con il premio di riscatto.",,"In receivership you also buy from the controller, at the ransom premium."
+In attesa del listino del giorno…,,Waiting for today's share list…
+In vendita,,For sale
+Incidente grave,,Serious accident
+Incorpora la controllata,,Merge the subsidiary
Indica l'indirizzo del server,,Enter the server address
Indietro,,Back
Indirizzo (host:porta),,Address (host:port)
Indirizzo non valido,,Invalid address
+Industrie,,Industries
+Km di binari,,Track km
Km di servizio al giorno,,Service km per day
+L'acquisto di industrie si sblocca al livello,,Buying industries unlocks at level
+La compagnia è stata scalata,,The company was taken over
La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).,,The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
+La controlli da,,You have controlled it for
+La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena.,,The game is still running: this is the story so far. The final chronicle comes when your company leaves the stage.
+La quotazione si sblocca al livello,,Listing unlocks at level
+"La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.",,"Your company's story so far: charts, records, highlights and prestige."
+La tua compagnia,,Your company
+La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del,,Your company is the target. Defences: buy back the free float with cash; extra dividend of
+La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade.,,Your bid: shareholders tender every day until the target is reached or the bid expires.
+Lancia l'offerta,,Launch the bid
Lavoratori,,Workers
Lavoratori e personale,,Workers and staff
+Le azioni tornano al fondatore e alzano la tua quota.,,Shares return to the founder and raise your stake.
+Le scalate ostili si sbloccano al livello,,Hostile takeovers unlock at level
+Libro dei soci,,Shareholder register
Linea,,Line
Linee,,Lines
Linee della compagnia,,Company lines
+Listino,,Share list
+Listino del,,Share list of
+Liv.,,Lvl
Livello,,Level
+Lo storico si forma alla fine di ogni mese,,History builds up at the end of each month
Locomotiva,,Locomotive
Lunghezza,,Length
+Macchinari,,Machinery
Manda al deposito,,Send to depot
Manutenzione,,Maintenance
+Manutenzione al giorno,,Maintenance per day
Mappa di calore della condizione,,Condition heat map
+Margine,,Margin
Mercato,,Market
+Mercato (flottante),,Market (free float)
Merci e passeggeri in attesa,,Waiting goods and passengers
+Miglior offerta,,Best offer
Minimappa,,Minimap
Nel bacino,,In the catchment
+Nessun anno concluso: lo storico si scrive a fine anno.,,No year closed yet: history is written at year end.
+Nessun anno registrato,,No year recorded
+Nessun fermo finora,,No shutdowns so far
Nessun posto di lavoro servito dai tuoi treni.,,No workplace served by your trains.
Nessun tracciato,,No route
Nessun treno in officina,,No trains in the workshop
Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno.,,No agreements: industries offer one when your trains carry at least 20 commuters a day.
Nessuna linea,,No line
+Nessuna offerta in corso. Un'offerta dura,,No open bids. A bid lasts
+Nessuno,,None
Nome automatico,,Automatic name
Nome del treno,,Train name
Nome della linea,,Line name
+Non quotata: le sue azioni non sono sul mercato.,,Not listed: its shares are not on the market.
Notizie,,News
+Numero di azioni,,Number of shares
+Nuova mappa con la difficoltà,,New map at difficulty
+Nuova partita+,,New game+
+Nuova partita+ in preparazione,,Preparing New game+
+Offerta pubblica di acquisto,,Takeover bid
+Offerte pubbliche in corso,,Open takeover bids
Officine,,Workshops
+Offri all'asta,,Bid at auction
+Oggi il fondatore ha il,,The founder now holds
"Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché.",,"Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why."
+Operazioni,,Actions
Ordina,,Order
+Ordina ricambi,,Order parts
+Paga dividendo,,Pay dividend
+Partita conclusa,,Game over
+Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare.,,Game over: you are an observer. The world goes on and the AI companies keep playing.
Partita locale,,Local game
Partita locale non avviata,,Local game not started
+Patrimonio,,Net worth
Patrimonio netto,,Net worth
+Patrimonio netto anno per anno,,Net worth year by year
Pausa,,Pause
Pendenza massima,,Max gradient
Personale,,Staff
@@ -110,74 +218,156 @@ Politica della flotta,,Fleet policy
Ponte,,Bridge
Ponti,,Bridges
Posti di lavoro,,Workplaces
+Predatoria,,Predatory
+Premio,,Premium
Prenotato,,Booked
+Prestigio,,Prestige
Prestito,,Loan
Prezzi globali di oggi (la borsa arriva in seguito).,,Today's global prices (the stock market comes later).
+Prezzo chiesto dai proprietari,,Asking price
+Prezzo dell'azione a fine mese,,Month-end share price
+Prezzo per azione,,Share price
+Prezzo · var.,,Price · chg.
+Primati,,Records
Produce,,Produces
+Proprietari privati,,Private owners
+Proprietà,,Owner
Prossimo intervento,,Next intervention
+Prudente,,Prudent
+Quota obiettivo,,Target stake
Quota rispetto al terreno,,Height above ground
+Quotati in borsa,,Go public
+Quotazione in borsa,,Stock market listing
+Quote sulle,,Stakes of the
Raggio minimo,,Min radius
Rating,,Rating
+Recupero,,Recovery
+Recupero al giorno,,Recovery per day
Regione di,,Region of
Registro degli impieghi,,Employment register
Registro in arrivo dal server…,,Register on its way from the server…
Registro officina,,Workshop register
+Resa impianti,,Plant output
+Revisione,,Overhaul
+Revisione programmata,,Overhaul scheduled
+Riacquista,,Buy back
+Riacquista almeno il,,Buy back at least
+Riacquista azioni,,Buy back shares
+Riacquisto,,Buyback
+Riacquisto di azioni proprie,,Own share buyback
Ricambi,,Spare parts
+Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.,,Spare parts to order beyond the policy stock: they become explicit demand on your lines.
Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.,,Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
+Ricambi extra,,Extra parts
Ricambi già destinati,,Parts already allocated
+Ricavi,,Revenue
Rifiuta,,Reject
Rilevato,,Embankment
+Riscatto non riuscito in tempo,,Buyback not completed in time
+Rischio di fermo in un anno,,Breakdown risk within a year
+Ritira l'adesione,,Withdraw acceptance
Ritmo di lavoro (manca personale),,Work rate (staff shortage)
Rosso coppo,,Tile red
+"Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute.",,Pick an industry from the list or on the map. Plants wear out with use: the maintenance budget and the spare parts and machinery brought by train keep them healthy.
+Scegli una compagnia nel listino,,Pick a company from the list
"Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda.",,"Pick a tool on the left or click a train, station, industry or town to see its card."
+Scheda del proprietario,,Owner's card
+Scheda in arrivo dal server…,,Card on its way from the server…
Scorta desiderata,,Target stock
+Scorte,,Stock
Se la capacità manca per 30 giorni la convenzione salta con una penale.,,If capacity falls short for 30 days the agreement breaks with a penalty.
Segnali,,Signals
Seleziona i veicoli da comporre,,Select the vehicles to compose
Seleziona un treno,,Select a train
Seleziona un treno e un deposito,,Select a train and a depot
+Sentiment del mercato,,Market sentiment
Serve un deposito,,A depot is required
Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH.,,Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
Servizi,,Services
Servono almeno due fermate,,At least two stops are needed
Soddisfazione,,Satisfaction
+Sopra il,,Above
+Spesa di manutenzione nell'anno,,Maintenance spent this year
+Spread,,Spread
Stalli,,Stalls
Stato,,Status
Stazione,,Station
Storico,,History
+Storico annuale,,Yearly history
+Storico dei fermi,,Shutdown history
Svuota,,Clear
Token,,Token
Token del server,,Server token
Torna al menu,,Back to menu
+Torna alla partita,,Back to the game
+Totale,,Total
Treni,,Trains
Treni della compagnia,,Company trains
Treno di riserva in deposito,,Reserve train in depot
Trincea,,Cutting
+Tua quota,,Your stake
+Usura al giorno,,Wear per day
+Utile,,Profit
+Utile annuo,,Annual profit
Veicoli,,Vehicles
"Veicoli liberi nel deposito (selezione multipla, in ordine)",,"Free vehicles in the depot (multiple selection, in order)"
Velocità,,Speed
+Vendi,,Sell
Verde,,Green
Via Ferrea,,Via Ferrea
a piedi,,on foot
abitanti,,inhabitants
+agli azionisti; i dividendi alzano il sentiment del titolo.,,to shareholders; dividends raise the share's sentiment.
+al 20% e si fermano più spesso.,,at 20% and stop more often.
+al massimo il,,at most
al mese,,per month
+altrimenti la partita finisce. Intanto versi il,,or the game ends. Meanwhile you pay
+amministrazione controllata,,receivership
anni,,years
+attende,,waiting for
attende i ricambi,,waiting for parts
attendi il pieno,,wait for full load
+azioni,,shares
+azioni in circolazione: oltre il,,outstanding shares: above
capacità delle carrozze insufficiente sulla,,not enough coach capacity on
capacità mancante da,,capacity short for
carica,,load
+cavaliere bianco,,white knight
città senza servizi per il personale,,towns without services for staff
+consumo,,use
+controlla la compagnia,,controls the company
+controllata da,,controlled by
copertura,,coverage
da,,from
+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
+del capitale per ordine.,,of the capital per order.
+della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il,,of cash (the share price rises); white knight: an ally buys the free float at the bid price plus
+delle azioni entro il,,of the shares by
+di,,of
+dividendo straordinario,,extra dividend
+durata,,duration
+e il,,and
+e personale sufficiente,,and enough staff
+fallita,,bankrupt
+"fallita, attivi all'asta",,"bankrupt, assets at auction"
+ferma,,stopped
+ferma fino al,,stopped until
fermo in linea,,stranded on the line
fermo in salita,,stalled on grade
g,,d
giorni,,days
+giorni di fermo,,days of shutdown
+giorni e liquida le minoranze al prezzo di mercato.,,days and buys out the minorities at market price.
+giorni e offre un premio tra il,,days and offers a premium between
giorno,,day
+gli impianti rendono pieno; sotto calano fino a,,plants run at full output; below they drop to
guasto,,broken down
guasto lieve,,minor failure
hub mercato mondiale,,world market hub
+il fondatore ha,,the founder holds
+impegnato,,committed
in arrivo,,arriving
in attesa,,waiting
in attesa di via libera,,waiting for clearance
@@ -185,32 +375,70 @@ in coda,,queued
in deposito,,in depot
in marcia,,running
in officina,,in the workshop
+in scorta,,in stock
in servizio,,in service
in stazione,,at station
+incasso stimato,,estimated proceeds
intervento prenotato,,intervention booked
+la fusione è possibile dopo,,the merger is possible after
+la tua compagnia,,your company
large,Grande,Large
lavoratori,,workers
lavori,,jobs
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
linea,,line
+livello,,level
+macchinari,,machinery
+macchinari per il prossimo lavoro,,machinery for the next job
+macchinari per livello,,machinery per level
medium,Medio,Medium
+mesi,,months
mila km,,thousand km
+nessuna,,none
nessuna città raggiungibile entro,,no town reachable within
nessuna stazione serve il posto di lavoro,,no station serves the workplace
+non quotata,,not listed
+non è in vendita.,,not for sale.
+obiettivo,,target
+ordinati in più,,extra ordered
ore,,hours
+per,,for
+per azione,,per share
personale,,staff
+personale almeno al,,staff at least at
+portafoglio azioni,,share portfolio
+possiedi,,you hold
posti al giorno garantiti,,guaranteed seats a day
+privati,,private
+punti al giorno,,points per day
+quotata,,listed
+respinta dal consiglio,,rejected by the board
+riacquisto,,buyback
ricambi,,parts
+ricambi al mese per livello,,spare parts per month per level
rimorchiato,,towed
+riporta la condizione a 100.,,restores condition to 100.
riserva,,reserve
+scade il,,expires on
scaduta,,overdue
scaduto,,overdue
scarica,,unload
+scorta della politica,,policy stock
senza linea,,no line
senza percorso,,no route
+servono,,needs
+si controlla la compagnia.,,you control the company.
small,Piccolo,Small
soccorso tra,,rescue in
stallo,,stall
+sul mercato,,on the market
+sul prezzo di mercato.,,over the market price.
tecnici,,staff
tra,,in
treni,,trains
+tu,,you
+tua,,yours
+ultimi,,last
+vincitore,,winner
+"volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.",,"times annual profit, divided by the shares and multiplied by market sentiment."
+⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto.,,⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
diff --git a/client/ViaFerrea.Client/scripts/App/AutoPilot.cs b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs
index 997b2b9..2c7f22d 100644
--- a/client/ViaFerrea.Client/scripts/App/AutoPilot.cs
+++ b/client/ViaFerrea.Client/scripts/App/AutoPilot.cs
@@ -14,7 +14,9 @@ namespace ViaFerrea.Client.App;
///
/// Pilota automatico per il collaudo del client (-- --autopilot cartella): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
-/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo.
+/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo; poi apre
+/// officine e impieghi (F4), la scheda del proprietario di un'industria, «Compagnie e borsa» e la
+/// Cronaca provvisoria (F5).
///
public partial class AutoPilot : Node
{
@@ -73,6 +75,18 @@ public partial class AutoPilot : Node
return r.Created.Length > 0 ? r.Created[0] : -1;
}
+ /// Attende una condizione al massimo per il tempo indicato, senza fallire.
+ private async Task Wait(Func condition, double timeoutS)
+ {
+ ulong start = Time.GetTicksMsec();
+ while (!condition())
+ {
+ if (Time.GetTicksMsec() - start > timeoutS * 1000) return false;
+ await Frame();
+ }
+ return true;
+ }
+
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
@@ -184,5 +198,46 @@ public partial class AutoPilot : Node
_game.UseTool(Tool.Employment);
await Until(() => World.Employment is not null, "registro degli impieghi", 30);
await Shot("11_impieghi", 30);
+
+ await IndustriesAndMarket(site.A);
+ }
+
+ /// F5: scheda del proprietario di un'industria, borsa con il libro dei soci, Cronaca provvisoria.
+ private async Task IndustriesAndMarket(Vec2 near)
+ {
+ int me = World.Summary!.CompanyId;
+ 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();
+ _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
+ 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);
+ _game.ScrollPanel(0);
+
+ // borsa: azioni di una compagnia IA, qualche mese di prezzi, poi listino e libro dei soci
+ var ai = World.Companies.Values.Where(c => !c.IsPlayer && c.Listed && !c.Bankrupt).OrderBy(c => c.Id).FirstOrDefault();
+ if (ai is not null) await Ok(new BuySharesCommand(new CompanyId(ai.Id), 20_000, Money.Zero));
+ _game.OpenCompanies(ai?.Id ?? me);
+ Session.SetSpeed(8);
+ bool history = await Wait(() => ai is null || (World.CompanyCards.TryGetValue(ai.Id, out var card) && card.PriceHistory.Count >= 3), 200);
+ if (!history) GD.Print("autopilot: storico dei prezzi ancora corto");
+ Session.SetSpeed(1);
+ await Until(() => World.Tape is not null, "listino di borsa", 60);
+ await Shot("13_compagnie", 60);
+ _game.OpenCompanies(me);
+ await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
+ await Shot("14_compagnia_giocatore", 40);
+
+ // Cronaca provvisoria
+ _game.OpenChronicle();
+ await Until(() => _game.ChronicleVisible, "cronaca", 30);
+ await Shot("15_cronaca", 30);
}
}
diff --git a/client/ViaFerrea.Client/scripts/App/UiTheme.cs b/client/ViaFerrea.Client/scripts/App/UiTheme.cs
index bb6a520..1016826 100644
--- a/client/ViaFerrea.Client/scripts/App/UiTheme.cs
+++ b/client/ViaFerrea.Client/scripts/App/UiTheme.cs
@@ -12,6 +12,15 @@ public static class UiTheme
public static Font BodyBold { get; private set; } = ThemeDB.FallbackFont;
public static Font Title { get; private set; } = ThemeDB.FallbackFont;
+ ///
+ /// Tema costruito da . Il tema della finestra non attraversa i nodi che non
+ /// sono Control (Main, CanvasLayer): ogni radice dell'interfaccia lo riceve con .
+ ///
+ public static Theme? Current { get; private set; }
+
+ /// Assegna il tema a una radice dell'interfaccia (figlia di un nodo che non è un Control).
+ public static void Apply(Control root) => root.Theme = Current;
+
public static Theme Build()
{
Body = LoadFont("res://assets/fonts/IBMPlexSans-Regular.ttf");
@@ -35,22 +44,44 @@ public static class UiTheme
t.SetStylebox("pressed", "Button", Box(Palette.Amber, Palette.Amber, 8, 10));
t.SetStylebox("disabled", "Button", Box(Palette.AppBackground, Palette.Border, 8, 10));
t.SetStylebox("focus", "Button", Box(new Color(0, 0, 0, 0), Palette.AmberLight, 8, 10));
+ // pulsanti in IBM Plex Sans 600 come nell'immagine 05
+ t.SetFont("font", "Button", BodyBold);
t.SetColor("font_pressed_color", "Button", Palette.AppBackground);
t.SetColor("font_hover_color", "Button", Palette.Text);
t.SetColor("font_disabled_color", "Button", Palette.TextSecondary);
t.SetColor("font_hover_pressed_color", "Button", Palette.AppBackground);
+ // caselle e interruttori: niente riquadro da pulsante (altrimenti ereditano quello di Button)
+ var plain = new StyleBoxEmpty { ContentMarginLeft = 4, ContentMarginRight = 4, ContentMarginTop = 2, ContentMarginBottom = 2 };
+ foreach (string type in new[] { "CheckBox", "CheckButton" })
+ {
+ foreach (string state in new[] { "normal", "pressed", "hover", "hover_pressed", "disabled", "focus" }) t.SetStylebox(state, type, plain);
+ t.SetColor("font_pressed_color", type, Palette.Text);
+ t.SetColor("font_hover_color", type, Palette.Text);
+ t.SetColor("font_hover_pressed_color", type, Palette.Text);
+ t.SetFont("font", type, Body);
+ }
+
t.SetStylebox("normal", "LineEdit", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("focus", "LineEdit", Box(Palette.Inner, Palette.Amber, 8, 8));
t.SetColor("caret_color", "LineEdit", Palette.Amber);
t.SetStylebox("panel", "ItemList", Box(Palette.Inner, Palette.Border, 8, 6));
- t.SetColor("font_selected_color", "ItemList", Palette.AppBackground);
- t.SetStylebox("selected", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
- t.SetStylebox("selected_focus", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
+ // selezione su ambra scuro: restano leggibili anche le voci colorate (condizione, proprietario)
+ t.SetColor("font_selected_color", "ItemList", Palette.AmberLight);
+ t.SetStylebox("selected", "ItemList", Box(Palette.AmberDark, Palette.Amber, 4, 4));
+ t.SetStylebox("selected_focus", "ItemList", Box(Palette.AmberDark, Palette.Amber, 4, 4));
+
+ // cursori: binario vuoto e parte piena in ambra
+ var track = Box(Palette.Border, Palette.Border, 3, 0);
+ track.ContentMarginTop = track.ContentMarginBottom = 3;
+ t.SetStylebox("slider", "HSlider", track);
+ t.SetStylebox("grabber_area", "HSlider", Box(Palette.Amber, Palette.Amber, 3, 0));
+ t.SetStylebox("grabber_area_highlight", "HSlider", Box(Palette.AmberLight, Palette.AmberLight, 3, 0));
t.SetStylebox("background", "ProgressBar", Box(Palette.Border, Palette.Border, 4, 0));
t.SetStylebox("fill", "ProgressBar", Box(Palette.Workers, Palette.Workers, 4, 0));
t.SetColor("font_color", "ProgressBar", Palette.Text);
+ Current = t;
return t;
}
diff --git a/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs
index 157489d..fc32bd9 100644
--- a/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs
+++ b/client/ViaFerrea.Client/scripts/Hud/Toolbar.cs
@@ -5,9 +5,12 @@ using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// Strumenti e pannelli della barra sinistra (immagine 01).
-public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Market, Finance, Demolish }
+public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
-/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.
+///
+/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
+/// sono compatti e la colonna scorre con la rotella se la finestra è più bassa della barra.
+///
public partial class Toolbar : PanelContainer
{
private readonly Dictionary _buttons = [];
@@ -20,14 +23,22 @@ public partial class Toolbar : PanelContainer
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 6));
CustomMinimumSize = new Vector2(88, 0);
+ var scroll = new ScrollContainer
+ {
+ HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled,
+ VerticalScrollMode = ScrollContainer.ScrollMode.ShowNever,
+ SizeFlagsVertical = SizeFlags.ExpandFill,
+ };
+ AddChild(scroll);
var col = new VBoxContainer();
- col.AddThemeConstantOverride("separation", 6);
- AddChild(col);
+ col.AddThemeConstantOverride("separation", 4);
+ scroll.AddChild(col);
foreach (var (tool, label) in new[]
{
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
- (Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
+ (Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
+ (Tool.Demolish, "Demolisci"),
})
{
var b = new ToolButton(tool, T(label));
@@ -55,7 +66,7 @@ public partial class Toolbar : PanelContainer
{
_tool = tool;
_label = label;
- CustomMinimumSize = new Vector2(76, 72);
+ CustomMinimumSize = new Vector2(76, 56);
Flat = true;
TooltipText = label;
MouseEntered += QueueRedraw;
@@ -77,11 +88,11 @@ public partial class Toolbar : PanelContainer
if (_active) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Inner, 8, 0), new Rect2(Vector2.Zero, Size));
else if (IsHovered()) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var color = _active ? Palette.Amber : Palette.Text;
- var c = new Vector2(Size.X / 2, 26);
+ var c = new Vector2(Size.X / 2, 20);
DrawGlyph(c, color);
var font = _active ? UiTheme.BodyBold : UiTheme.Body;
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 13);
- DrawString(font, new Vector2((Size.X - dims.X) / 2, 60), _label, HorizontalAlignment.Left, -1, 13, color);
+ DrawString(font, new Vector2((Size.X - dims.X) / 2, 48), _label, HorizontalAlignment.Left, -1, 13, color);
}
private void DrawGlyph(Vector2 c, Color col)
@@ -131,6 +142,19 @@ public partial class Toolbar : PanelContainer
DrawArc(c + new Vector2(-6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
DrawArc(c + new Vector2(6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
break;
+ case Tool.Industries:
+ // fabbrica: tetto a shed e ciminiera
+ DrawPolyline([c + new Vector2(-11, 10), c + new Vector2(-11, -2), c + new Vector2(-5, -7), c + new Vector2(-5, -2),
+ c + new Vector2(1, -7), c + new Vector2(1, -2), c + new Vector2(7, -7), c + new Vector2(7, 10), c + new Vector2(-11, 10)], col, w);
+ DrawLine(c + new Vector2(10, 10), c + new Vector2(10, -11), col, w);
+ DrawLine(c + new Vector2(7, -11), c + new Vector2(10, -11), col, w);
+ break;
+ case Tool.Companies:
+ // palazzo della borsa: frontone, colonne e basamento
+ DrawPolyline([c + new Vector2(-11, -5), c + new Vector2(0, -11), c + new Vector2(11, -5), c + new Vector2(-11, -5)], col, w);
+ for (int i = -1; i <= 1; i++) DrawLine(c + new Vector2(i * 7, -3), c + new Vector2(i * 7, 7), col, w);
+ DrawLine(c + new Vector2(-11, 10), c + new Vector2(11, 10), col, w);
+ break;
case Tool.Market:
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
diff --git a/client/ViaFerrea.Client/scripts/Net/GameSession.cs b/client/ViaFerrea.Client/scripts/Net/GameSession.cs
index 3223eb5..c1b4f08 100644
--- a/client/ViaFerrea.Client/scripts/Net/GameSession.cs
+++ b/client/ViaFerrea.Client/scripts/Net/GameSession.cs
@@ -20,6 +20,9 @@ public sealed class GameSession : IAsyncDisposable
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
+
+ /// Preset di difficoltà della partita (dal Welcome; serve a «Nuova partita+»).
+ public string Difficulty { get; private set; } = "";
public LocalServerLauncher? LocalServer { get; set; }
/// Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.
@@ -52,7 +55,7 @@ public sealed class GameSession : IAsyncDisposable
}, ct);
var world = new ClientWorld(data);
world.Apply(welcome);
- return new GameSession(connection, world, label);
+ return new GameSession(connection, world, label) { Difficulty = welcome.Difficulty };
}
catch
{
@@ -86,6 +89,9 @@ public sealed class GameSession : IAsyncDisposable
case DailyDigest digest when RequestedSpeed == digest.Speed:
RequestedSpeed = null;
break;
+ case Welcome welcome:
+ Difficulty = welcome.Difficulty;
+ break;
case Pong pong when pong.Nonce == _pingNonce:
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
break;
diff --git a/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs b/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs
new file mode 100644
index 0000000..6bc6d33
--- /dev/null
+++ b/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs
@@ -0,0 +1,946 @@
+using Godot;
+using ViaFerrea.Client.App;
+using ViaFerrea.Client.Net;
+using ViaFerrea.Core.Commands;
+using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Economy;
+using ViaFerrea.Protocol.Client;
+using ViaFerrea.Protocol.Messages;
+using static ViaFerrea.Client.App.Localization;
+
+namespace ViaFerrea.Client.Panels;
+
+///
+/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
+/// 05): listino delle compagnie, offerte pubbliche in corso con adesioni e difese, scheda della
+/// compagnia scelta (libro dei soci, prezzo mensile, storico annuale) e operazioni: compravendita,
+/// quotazione, dividendo, riacquisto, offerta pubblica, fusione, offerte alle aste delle fallite.
+/// I dati arrivano dal listino giornaliero (MarketTape) e dalle schede chieste al server; ogni
+/// operazione è un comando e l'esito (anche il rifiuto per livello) si mostra com'è.
+///
+public partial class CompaniesPanel : VBoxContainer
+{
+ private const float WPrice = 80, WCap = 86, WWorth = 86, WMine = 56;
+
+ private readonly GameSession _session;
+ private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
+ private readonly VBoxContainer _banner = PanelKit.Column(6);
+ private readonly VBoxContainer _rows = PanelKit.Column(4);
+ private readonly VBoxContainer _bids = PanelKit.Column(8);
+ private readonly VBoxContainer _card = PanelKit.Column(8);
+ private readonly SeriesChart _chart = new(150);
+ private readonly Label _chartCaption = UiTheme.Text("", 14, bold: true);
+ private readonly VBoxContainer _register = PanelKit.Column(6);
+ private readonly VBoxContainer _history = PanelKit.Column(4);
+ private readonly VBoxContainer _actions = PanelKit.Column(8);
+ private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
+ private readonly Dictionary _rowById = [];
+ private readonly Dictionary _bidProgress = [];
+ private string _bidsKey = "", _actionsKey = "", _bannerKey = "", _rowsKey = "";
+ private int _selected = -1;
+ private int _tapeVersion = -1, _entityVersion = -1, _detailVersion = -1;
+ private double _requestSelected, _requestAll = double.MaxValue, _sinceRefresh = double.MaxValue;
+ private Action? _updateEstimates;
+
+ public event Action? CloseRequested;
+ public event Action? ChronicleRequested;
+
+ public CompaniesPanel(GameSession session)
+ {
+ _session = session;
+ AddThemeConstantOverride("separation", 14);
+ SizeFlagsVertical = SizeFlags.ExpandFill;
+
+ var header = PanelKit.Row(12);
+ var titles = PanelKit.Column(0);
+ titles.AddChild(UiTheme.TitleLabel(T("Compagnie e borsa"), 40));
+ titles.AddChild(_subtitle);
+ header.AddChild(titles);
+ var chronicle = new Button { Text = T("Cronaca provvisoria"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(0, 40) };
+ chronicle.TooltipText = T("La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.");
+ chronicle.Pressed += () => ChronicleRequested?.Invoke();
+ header.AddChild(chronicle);
+ var close = new Button { Text = T("Chiudi"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(96, 40) };
+ close.Pressed += () => CloseRequested?.Invoke();
+ header.AddChild(close);
+ AddChild(header);
+ AddChild(_banner);
+
+ var body = PanelKit.Row(16);
+ body.SizeFlagsVertical = SizeFlags.ExpandFill;
+ AddChild(body);
+
+ var left = Column(body, 1.5f);
+ left.AddChild(UiTheme.Text(T("Listino"), 16, bold: true));
+ var sm = session.World.Data.Balance.StockMarket;
+ left.AddChild(Wrapped($"{T("Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e")} " +
+ $"{Fmt.Number(sm.EarningsMultiple, 0)} {T("volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.")}", 12, Palette.TextSecondary));
+ left.AddChild(TableHeader());
+ left.AddChild(_rows);
+ left.AddChild(PanelKit.Separator());
+ left.AddChild(UiTheme.Text(T("Offerte pubbliche in corso"), 16, bold: true));
+ left.AddChild(_bids);
+
+ var center = Column(body, 1f);
+ center.AddChild(_card);
+ center.AddChild(_chartCaption);
+ center.AddChild(_chart);
+ center.AddChild(UiTheme.Text(T("Libro dei soci"), 16, bold: true));
+ center.AddChild(_register);
+
+ var right = Column(body, 0.9f);
+ right.AddChild(UiTheme.Text(T("Storico annuale"), 16, bold: true));
+ right.AddChild(_history);
+ right.AddChild(PanelKit.Separator());
+ right.AddChild(UiTheme.Text(T("Operazioni"), 16, bold: true));
+ right.AddChild(_actions);
+ _status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ right.AddChild(_status);
+
+ Select(session.World.Summary?.CompanyId ?? 0);
+ }
+
+ /// Compagnia della scheda (−1 se nessuna).
+ public int Selected => _selected;
+
+ public void Select(int company)
+ {
+ _selected = company;
+ _requestSelected = double.MaxValue;
+ _sinceRefresh = double.MaxValue;
+ _status.Text = "";
+ foreach (var (id, row) in _rowById) row.SetSelected(id == company);
+ }
+
+ private static VBoxContainer Column(HBoxContainer body, float ratio)
+ {
+ var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
+ frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 16));
+ var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
+ frame.AddChild(scroll);
+ // margine destro: la barra di scorrimento non tocca i numeri allineati a destra
+ var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ margin.AddThemeConstantOverride("margin_right", 10);
+ scroll.AddChild(margin);
+ var col = PanelKit.Column(10);
+ margin.AddChild(col);
+ body.AddChild(frame);
+ return col;
+ }
+
+ public override void _Process(double delta)
+ {
+ var w = _session.World;
+ _requestSelected += delta;
+ _requestAll += delta;
+ _sinceRefresh += delta;
+ // tutte le schede ogni 5 s (quote del giocatore e soci dei bersagli), quella aperta ogni secondo
+ if (_requestAll >= 5)
+ {
+ _requestAll = 0;
+ _requestSelected = 0;
+ foreach (int id in w.Companies.Values.Where(c => !c.Merged).Select(c => c.Id).Order())
+ _session.Send(new RequestDetail { Kind = DetailKind.Company, Target = id });
+ }
+ else if (_requestSelected >= 1 && _selected >= 0)
+ {
+ _requestSelected = 0;
+ _session.Send(new RequestDetail { Kind = DetailKind.Company, Target = _selected });
+ }
+ bool changed = w.TapeVersion != _tapeVersion || w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion;
+ if (changed && _sinceRefresh >= 0.25) Refresh();
+ }
+
+ private void Result(CommandResultMessage r)
+ {
+ _status.Text = r.Message;
+ _status.AddThemeColorOverride("font_color", r.Ok ? Palette.Ok : Palette.Danger);
+ _requestAll = double.MaxValue;
+ }
+
+ private void Refresh()
+ {
+ var w = _session.World;
+ _sinceRefresh = 0;
+ _tapeVersion = w.TapeVersion;
+ _entityVersion = w.EntityVersion;
+ _detailVersion = w.DetailVersion;
+ int me = Me(w);
+ double portfolio = w.Companies.Values.Where(c => c.Id != me && !c.Merged && !c.Bankrupt).Sum(c => Mine(w, c.Id) * PriceCents(w, c.Id));
+ _subtitle.Text = (w.Tape is { } tape ? $"{T("Listino del")} {Fmt.Date(w, tape.Day)}" : T("In attesa del listino del giorno…")) +
+ $" · {T("portafoglio azioni")} {Money.FromCentsRounded(portfolio)}";
+ RefreshBanner(w);
+ RefreshRows(w);
+ RefreshBids(w);
+ RefreshCard(w);
+ RefreshHistory(w);
+ RefreshActions(w);
+ _updateEstimates?.Invoke();
+ }
+
+ // ------------------------------------------------------------------ dati di comodo (solo lettura)
+
+ private static int Me(ClientWorld w) => w.Summary?.CompanyId ?? 0;
+
+ private static SharePrice? Quote(ClientWorld w, int id) => w.Tape?.Shares.FirstOrDefault(s => s.Company == id);
+
+ /// Prezzo per azione in centesimi: dal listino se c'è, altrimenti dalla scheda dell'entità.
+ private static double PriceCents(ClientWorld w, int id) =>
+ Quote(w, id) is { PriceCents: > 0 } q ? q.PriceCents : w.Companies.TryGetValue(id, out var c) ? c.SharePriceCents : 0;
+
+ private static long Outstanding(ClientWorld w, int id)
+ {
+ if (Quote(w, id) is { Outstanding: > 0 } q) return q.Outstanding;
+ if (w.CompanyCards.TryGetValue(id, out var card)) return card.TotalShares - card.Treasury;
+ return w.Data.Balance.StockMarket.Shares;
+ }
+
+ /// Azioni della compagnia del giocatore nella compagnia indicata (dal libro dei soci).
+ private static long Mine(ClientWorld w, int id)
+ {
+ int me = Me(w);
+ if (!w.CompanyCards.TryGetValue(id, out var card)) return 0;
+ return card.Holdings.Where(h => id == me ? h.Holder == HoldingInfo.Founder : h.Holder == me).Sum(h => h.Shares);
+ }
+
+ /// Vero/falso se il libro dei soci è noto, null se la scheda non è ancora arrivata.
+ private static bool? Holds(ClientWorld w, int id) => w.CompanyCards.ContainsKey(id) ? Mine(w, id) > 0 : null;
+
+ // ------------------------------------------------------------------ amministrazione controllata
+
+ private void RefreshBanner(ClientWorld w)
+ {
+ int me = Me(w);
+ var info = w.Companies.GetValueOrDefault(me);
+ long today = Fmt.Today(w);
+ string key = info is { Receivership: true } ? $"{info.ReceivershipUntilDay}|{info.ControlledBy}|{today}|{info.FounderShare:0.000}" : "";
+ if (key == _bannerKey) return;
+ _bannerKey = key;
+ foreach (var c in _banner.GetChildren()) c.QueueFree();
+ if (info is not { Receivership: true }) return;
+ var sm = w.Data.Balance.StockMarket;
+ var box = new PanelContainer();
+ box.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 14));
+ var row = PanelKit.Row(16);
+ box.AddChild(row);
+ var col = PanelKit.Column(4);
+ col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
+ col.AddChild(UiTheme.Text($"{T("Amministrazione controllata")} · {T("controlla la compagnia")} {Fmt.Company(w, info.ControlledBy)}", 16, Palette.AmberLight, bold: true));
+ long left = Math.Max(0, info.ReceivershipUntilDay - today);
+ col.AddChild(Wrapped($"{T("Riacquista almeno il")} {Fmt.Pct(sm.RansomShare, 0)} {T("delle azioni entro il")} {Fmt.Date(w, info.ReceivershipUntilDay)} ({left} {T("giorni")}), " +
+ $"{T("altrimenti la partita finisce. Intanto versi il")} {Fmt.Pct(sm.ReceivershipDividend, 0)} {T("degli utili come dividendo e non puoi chiedere prestiti.")} " +
+ $"{T("Oggi il fondatore ha il")} {Fmt.Pct(info.FounderShare)}.", 13, Palette.Text));
+ row.AddChild(col);
+ var buy = UiTheme.Primary(T("Riacquista azioni"));
+ buy.SizeFlagsVertical = SizeFlags.ShrinkCenter;
+ buy.Pressed += () => Select(me);
+ row.AddChild(buy);
+ _banner.AddChild(box);
+ }
+
+ // ------------------------------------------------------------------ listino
+
+ private static Control TableHeader()
+ {
+ var row = PanelKit.Row(6);
+ var name = UiTheme.Text(T("Compagnia"), 12, Palette.TextSecondary);
+ name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
+ name.CustomMinimumSize = new Vector2(24, 0);
+ row.AddChild(new Control { CustomMinimumSize = new Vector2(10, 0) });
+ row.AddChild(name);
+ foreach (var (text, width) in new[] { (T("Prezzo · var."), WPrice), (T("Capitalizz."), WCap), (T("Patrimonio"), WWorth), (T("Tua quota"), WMine) })
+ {
+ var l = UiTheme.Text(text, 12, Palette.TextSecondary);
+ l.CustomMinimumSize = new Vector2(width, 0);
+ l.HorizontalAlignment = HorizontalAlignment.Right;
+ row.AddChild(l);
+ }
+ row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
+ return row;
+ }
+
+ private void RefreshRows(ClientWorld w)
+ {
+ int me = Me(w);
+ var companies = w.Companies.Values.Where(c => !c.Merged)
+ .OrderBy(c => c.Id == me ? 0 : c.Bankrupt ? 2 : 1)
+ .ThenByDescending(c => PriceCents(w, c.Id) * Outstanding(w, c.Id))
+ .ThenBy(c => c.Id).ToList();
+ string key = string.Join(",", companies.Select(c => c.Id));
+ if (key != _rowsKey)
+ {
+ _rowsKey = key;
+ foreach (var c in _rows.GetChildren()) c.QueueFree();
+ _rowById.Clear();
+ foreach (var c in companies)
+ {
+ int id = c.Id;
+ var row = new CompanyRow();
+ row.Pressed += () => Select(id);
+ _rowById[id] = row;
+ _rows.AddChild(row);
+ row.SetSelected(id == _selected);
+ }
+ }
+ foreach (var c in companies)
+ {
+ var q = Quote(w, c.Id);
+ double price = PriceCents(w, c.Id);
+ long outstanding = Outstanding(w, c.Id);
+ var parts = new List();
+ if (c.Id == me) parts.Add(T("la tua compagnia"));
+ if (c.Bankrupt)
+ {
+ parts.Add(T("fallita, attivi all'asta"));
+ }
+ else
+ {
+ parts.Add(Fmt.Tier(w, c.Tier));
+ if (c.Personality.Length > 0) parts.Add(Fmt.Personality(w, c.Personality));
+ if (!c.Listed) parts.Add(T("non quotata"));
+ if (c.ControlledBy >= 0) parts.Add($"{T("controllata da")} {Fmt.Company(w, c.ControlledBy)}");
+ if (c.Receivership) parts.Add(T("amministrazione controllata"));
+ }
+ double mine = c.Id == me ? c.FounderShare : outstanding > 0 && w.CompanyCards.ContainsKey(c.Id) ? (double)Mine(w, c.Id) / outstanding : -1;
+ _rowById[c.Id].Update(
+ Fmt.CompanyColor(w, c.Id), c.Name, string.Join(" · ", parts),
+ c.Bankrupt ? "—" : Fmt.Price(price), c.Listed && q is not null && !c.Bankrupt ? Fmt.Change(q.Change) : "—",
+ !c.Listed || q is null ? Palette.TextSecondary : q.Change > 0.0005f ? Palette.Ok : q.Change < -0.0005f ? Palette.Danger : Palette.TextSecondary,
+ c.Bankrupt ? "—" : Money.FromCentsRounded(price * outstanding).ToString("short"), c.NetWorth.ToString("short"),
+ mine < 0 ? "…" : mine <= 0 ? "—" : Fmt.Pct(mine), c.Listed && !c.Bankrupt, c.Bankrupt || c.Receivership);
+ }
+ }
+
+ /// Riga del listino: pulsante piatto con le colonne allineate.
+ private sealed partial class CompanyRow : Button
+ {
+ private readonly ColorRect _swatch = new() { CustomMinimumSize = new Vector2(10, 28), SizeFlagsVertical = SizeFlags.ShrinkCenter };
+ private readonly Label _name = UiTheme.Text("", 14, bold: true);
+ private readonly Label _sub = UiTheme.Text("", 12, Palette.TextSecondary);
+ private readonly Label _price = UiTheme.Text("", 14, bold: true);
+ private readonly Label _change = UiTheme.Text("", 12);
+ private readonly Label _cap = UiTheme.Text("", 13);
+ private readonly Label _worth = UiTheme.Text("", 13);
+ private readonly Label _mine = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
+
+ public CompanyRow()
+ {
+ CustomMinimumSize = new Vector2(0, 50);
+ FocusMode = FocusModeEnum.None;
+ AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
+ AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
+ SetSelected(false);
+ var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
+ row.AddThemeConstantOverride("separation", 6);
+ row.SetAnchorsPreset(LayoutPreset.FullRect);
+ row.OffsetLeft = 8;
+ row.OffsetRight = -8;
+ AddChild(row);
+ row.AddChild(_swatch);
+ var names = new VBoxContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
+ names.AddThemeConstantOverride("separation", -2);
+ foreach (var l in new[] { _name, _sub })
+ {
+ l.ClipText = true;
+ l.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
+ l.CustomMinimumSize = new Vector2(24, 0);
+ names.AddChild(l);
+ }
+ row.AddChild(names);
+ // prezzo con la variazione del giorno sotto
+ var price = new VBoxContainer { CustomMinimumSize = new Vector2(WPrice, 0), SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
+ price.AddThemeConstantOverride("separation", -2);
+ foreach (var l in new[] { _price, _change })
+ {
+ l.HorizontalAlignment = HorizontalAlignment.Right;
+ price.AddChild(l);
+ }
+ row.AddChild(price);
+ foreach (var (l, width) in new[] { (_cap, WCap), (_worth, WWorth), (_mine, WMine) })
+ {
+ l.CustomMinimumSize = new Vector2(width, 0);
+ l.HorizontalAlignment = HorizontalAlignment.Right;
+ l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
+ row.AddChild(l);
+ }
+ foreach (var l in new[] { _name, _sub, _price, _change, _cap, _worth, _mine }) l.MouseFilter = MouseFilterEnum.Ignore;
+ _swatch.MouseFilter = MouseFilterEnum.Ignore;
+ }
+
+ public void SetSelected(bool on)
+ {
+ AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
+ }
+
+ public void Update(Color color, string name, string sub, string price, string change, Color changeColor, string cap, string worth, string mine, bool listed, bool alarm)
+ {
+ _swatch.Color = color;
+ _name.Text = name;
+ _sub.Text = sub;
+ TooltipText = $"{name}\n{sub}";
+ _sub.AddThemeColorOverride("font_color", alarm ? Palette.Danger : Palette.TextSecondary);
+ _price.Text = price;
+ _price.AddThemeColorOverride("font_color", listed ? Palette.Text : Palette.TextSecondary);
+ _change.Text = change;
+ _change.AddThemeColorOverride("font_color", changeColor);
+ _cap.Text = cap;
+ _worth.Text = worth;
+ _mine.Text = mine;
+ }
+ }
+
+ // ------------------------------------------------------------------ offerte pubbliche
+
+ private void RefreshBids(ClientWorld w)
+ {
+ int me = Me(w);
+ var bids = w.Tape?.Bids ?? [];
+ string key = string.Join(";", bids.Select(b => $"{b.Bid},{b.Defenses},{b.Knight},{b.Accepted},{Holds(w, b.Target)}")) + "|" + string.Join(",", w.Companies.Values.Where(c => c.Bankrupt || c.Merged).Select(c => c.Id).Order());
+ if (key != _bidsKey)
+ {
+ _bidsKey = key;
+ _bidProgress.Clear();
+ foreach (var c in _bids.GetChildren()) c.QueueFree();
+ if (bids.Count == 0)
+ {
+ var sm = w.Data.Balance.StockMarket;
+ _bids.AddChild(Wrapped($"{T("Nessuna offerta in corso. Un'offerta dura")} {sm.BidDurationDays} {T("giorni e offre un premio tra il")} {Fmt.Pct(sm.BidPremiumMin, 0)} " +
+ $"{T("e il")} {Fmt.Pct(sm.BidPremiumMax, 0)} {T("sul prezzo di mercato.")}", 13, Palette.TextSecondary));
+ }
+ foreach (var b in bids) _bids.AddChild(BidBox(w, b, me));
+ }
+ long today = Fmt.Today(w);
+ foreach (var b in bids)
+ {
+ if (!_bidProgress.TryGetValue(b.Bid, out var p)) continue;
+ p.Text.Text = $"{T("impegnato")} {Fmt.Pct(b.CommittedShare)} {T("di")} {Fmt.Pct(b.TargetShare, 0)} · {T("scade il")} {Fmt.Date(w, b.ExpiresDay)} ({Math.Max(0, b.ExpiresDay - today)} {T("giorni")})";
+ p.Bar.MaxValue = Math.Max(0.0001, b.TargetShare);
+ p.Bar.Value = Math.Min(b.CommittedShare, b.TargetShare);
+ }
+ }
+
+ private Control BidBox(ClientWorld w, BidInfo b, int me)
+ {
+ bool mine = b.Target == me || b.Bidder == me;
+ var box = new PanelContainer();
+ box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, mine ? Palette.Amber : Palette.Border, 8, 12));
+ var col = PanelKit.Column(6);
+ box.AddChild(col);
+ col.AddChild(Wrapped($"{Fmt.Company(w, b.Bidder)} → {Fmt.Company(w, b.Target)}", 15, null, bold: true));
+ double market = PriceCents(w, b.Target);
+ string premium = market > 0 ? $" ({Fmt.Change(b.PricePerShare.Cents / market - 1)} {T("sul mercato")})" : "";
+ col.AddChild(Wrapped($"{Fmt.Price(b.PricePerShare.Cents)} {T("per azione")}{premium} · {T("obiettivo")} {Fmt.Pct(b.TargetShare, 0)}", 13, null));
+ var bar = new ProgressBar { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
+ bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
+ col.AddChild(bar);
+ var progress = UiTheme.Text("", 12, Palette.TextSecondary);
+ col.AddChild(progress);
+ _bidProgress[b.Bid] = (progress, bar);
+ if (DefenseText(w, b) is { Length: > 0 } defenses) col.AddChild(Wrapped(defenses, 12, Palette.AmberLight));
+
+ int bidId = b.Bid;
+ if (b.Target == me)
+ {
+ var sm = w.Data.Balance.StockMarket;
+ col.AddChild(Wrapped($"{T("La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del")} {Fmt.Pct(sm.ExtraDividendCashShare, 0)} " +
+ $"{T("della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il")} {Fmt.Pct(sm.WhiteKnightPremium, 0)}.", 12, Palette.TextSecondary));
+ var row = PanelKit.Row(6);
+ var buyback = new Button { Text = T("Riacquisto"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ buyback.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.Buyback }, Result);
+ row.AddChild(buyback);
+ var dividend = new Button { Text = T("Dividendo straordinario"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ dividend.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.ExtraDividend }, Result);
+ row.AddChild(dividend);
+ col.AddChild(row);
+ var knightRow = PanelKit.Row(6);
+ var knights = new OptionButton { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
+ var knightIds = w.Companies.Values.Where(c => c.Id != me && c.Id != b.Bidder && !c.Bankrupt && !c.Merged).OrderBy(c => c.Id).Select(c => c.Id).ToList();
+ foreach (int k in knightIds) knights.AddItem(Fmt.Company(w, k));
+ knightRow.AddChild(knights);
+ var knight = new Button { Text = T("Cavaliere bianco"), Disabled = knightIds.Count == 0 };
+ knight.Pressed += () =>
+ {
+ if (knights.Selected < 0 || knights.Selected >= knightIds.Count) return;
+ _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(knightIds[knights.Selected]) }, Result);
+ };
+ knightRow.AddChild(knight);
+ col.AddChild(knightRow);
+ }
+ else if (b.Bidder == me)
+ {
+ col.AddChild(Wrapped(T("La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade."), 12, Palette.TextSecondary));
+ }
+ else if (Holds(w, b.Target) != false)
+ {
+ var respond = b.Accepted ? new Button { Text = T("Ritira l'adesione") } : UiTheme.Primary(T("Aderisci con le tue azioni"));
+ bool accept = !b.Accepted;
+ respond.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), accept), Result);
+ col.AddChild(respond);
+ if (b.Accepted) col.AddChild(UiTheme.Text(T("Hai aderito con tutte le tue azioni."), 12, Palette.Ok));
+ }
+ return box;
+ }
+
+ private static string DefenseText(ClientWorld w, BidInfo b)
+ {
+ var parts = new List();
+ if ((b.Defenses & (1 << (int)BidDefense.None)) != 0) parts.Add(T("respinta dal consiglio"));
+ if ((b.Defenses & (1 << (int)BidDefense.Buyback)) != 0) parts.Add(T("riacquisto"));
+ if ((b.Defenses & (1 << (int)BidDefense.ExtraDividend)) != 0) parts.Add(T("dividendo straordinario"));
+ if ((b.Defenses & (1 << (int)BidDefense.WhiteKnight)) != 0) parts.Add($"{T("cavaliere bianco")} {Fmt.Company(w, b.Knight)}");
+ return parts.Count == 0 ? "" : $"{T("Difese del bersaglio")}: {string.Join(", ", parts)}";
+ }
+
+ // ------------------------------------------------------------------ scheda della compagnia
+
+ private void RefreshCard(ClientWorld w)
+ {
+ foreach (var c in _card.GetChildren()) c.QueueFree();
+ foreach (var c in _register.GetChildren()) c.QueueFree();
+ int me = Me(w);
+ if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
+ {
+ _chartCaption.Text = "";
+ _chart.Show([], [], v => "", SeriesChart.Style.Line, Palette.Amber, T("Scegli una compagnia nel listino"));
+ return;
+ }
+ var card = w.CompanyCards.GetValueOrDefault(_selected);
+ var head = PanelKit.Row(10);
+ var swatch = new ColorRect { Color = Fmt.CompanyColor(w, info.Id), CustomMinimumSize = new Vector2(12, 34), SizeFlagsVertical = SizeFlags.ShrinkCenter };
+ head.AddChild(swatch);
+ var title = UiTheme.TitleLabel(info.Name, 30);
+ title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
+ head.AddChild(title);
+ _card.AddChild(head);
+
+ var badges = new HFlowContainer();
+ badges.AddThemeConstantOverride("h_separation", 6);
+ badges.AddThemeConstantOverride("v_separation", 6);
+ badges.AddChild(UiTheme.Badge(Fmt.Tier(w, info.Tier)));
+ if (info.Id == me) badges.AddChild(Tag(T("la tua compagnia"), Palette.AmberLight));
+ if (info.Personality.Length > 0) badges.AddChild(Tag(Fmt.Personality(w, info.Personality), Palette.Staff));
+ badges.AddChild(Tag(info.Listed ? T("quotata") : T("non quotata"), info.Listed ? Palette.Ok : Palette.TextSecondary));
+ if (info.ControlledBy >= 0) badges.AddChild(Tag($"{T("controllata da")} {Fmt.Company(w, info.ControlledBy)}", Palette.Amber));
+ if (info.Receivership) badges.AddChild(Tag(T("amministrazione controllata"), Palette.Danger));
+ if (info.Bankrupt) badges.AddChild(Tag(T("fallita"), Palette.Danger));
+ _card.AddChild(badges);
+
+ double price = PriceCents(w, info.Id);
+ var stats1 = PanelKit.Row(8);
+ stats1.AddChild(PanelKit.Stat(T("Prezzo per azione"), PanelKit.Value(info.Bankrupt ? "—" : Fmt.Price(price))));
+ stats1.AddChild(PanelKit.Stat(T("Capitalizzazione"), PanelKit.Value(card?.MarketCap.ToString("short") ?? Money.FromCentsRounded(price * Outstanding(w, info.Id)).ToString("short"))));
+ stats1.AddChild(PanelKit.Stat(T("Patrimonio netto"), PanelKit.Value(info.NetWorth.ToString("short"))));
+ _card.AddChild(stats1);
+ var stats2 = PanelKit.Row(8);
+ var profit = PanelKit.Value(info.AnnualProfit.ToString("short"));
+ if (info.AnnualProfit.IsNegative) profit.AddThemeColorOverride("font_color", Palette.Danger);
+ stats2.AddChild(PanelKit.Stat(T("Utile annuo"), profit));
+ stats2.AddChild(PanelKit.Stat(T("Dividendi (12 mesi)"), PanelKit.Value(card?.DividendsYear.ToString("short") ?? "—")));
+ stats2.AddChild(PanelKit.Stat(T("Debito"), PanelKit.Value(card?.Debt.ToString("short") ?? "—")));
+ _card.AddChild(stats2);
+ _card.AddChild(PanelKit.Pair(T("Cassa"), PanelKit.Value(info.Cash.ToString())));
+ _card.AddChild(PanelKit.Pair(T("Sentiment del mercato"), PanelKit.Value("×" + Fmt.Number(info.Sentiment, 2))));
+ if (card is { ControlDays: >= 0 } && info.ControlledBy >= 0)
+ _card.AddChild(PanelKit.Pair(T("Controllo"), PanelKit.Value($"{Fmt.Company(w, info.ControlledBy)} · {card.ControlDays} {T("giorni")}")));
+
+ var prices = card?.PriceHistory ?? [];
+ _chartCaption.Text = prices.Count > 0 ? $"{T("Prezzo dell'azione a fine mese")} · {T("ultimi")} {prices.Count} {T("mesi")}" : T("Prezzo dell'azione a fine mese");
+ _chart.Show(prices, [], Fmt.PricePrecise, SeriesChart.Style.Line, Fmt.CompanyColor(w, info.Id),
+ card is null ? T("Scheda in arrivo dal server…") : T("Lo storico si forma alla fine di ogni mese"));
+
+ BuildRegister(w, info, card);
+ }
+
+ private void BuildRegister(ClientWorld w, CompanyInfo info, CompanyCard? card)
+ {
+ if (card is null)
+ {
+ _register.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
+ return;
+ }
+ int me = Me(w);
+ long outstanding = Math.Max(1, card.TotalShares - card.Treasury);
+ var holders = card.Holdings.Where(h => h.Shares > 0)
+ .OrderBy(h => h.Holder == HoldingInfo.Founder ? 0 : h.Holder == HoldingInfo.Market ? 2 : 1)
+ .ThenByDescending(h => h.Shares).ThenBy(h => h.Holder).ToList();
+
+ // barra a segmenti delle quote
+ var bar = new HBoxContainer { CustomMinimumSize = new Vector2(0, 14) };
+ bar.AddThemeConstantOverride("separation", 2);
+ foreach (var h in holders)
+ bar.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = Math.Max(0.002f, h.Shares / (float)card.TotalShares) });
+ if (card.Treasury > 0)
+ bar.AddChild(new ColorRect { Color = Palette.Border, SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = card.Treasury / (float)card.TotalShares });
+ _register.AddChild(bar);
+
+ double control = w.Data.Balance.StockMarket.ControlShare;
+ foreach (var h in holders)
+ {
+ double share = (double)h.Shares / outstanding;
+ string name = h.Holder switch
+ {
+ HoldingInfo.Founder => info.Id == me ? T("Fondatore (tu)") : T("Fondatore privato"),
+ HoldingInfo.Market => T("Mercato (flottante)"),
+ _ => Fmt.Company(w, h.Holder) + (h.Holder == me ? " (" + T("tu") + ")" : ""),
+ };
+ var row = PanelKit.Row(8);
+ row.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), CustomMinimumSize = new Vector2(10, 10), SizeFlagsVertical = SizeFlags.ShrinkCenter });
+ var n = UiTheme.Text(name, 13, h.Holder == me || (h.Holder == HoldingInfo.Founder && info.Id == me) ? Palette.AmberLight : Palette.Text);
+ n.SizeFlagsHorizontal = SizeFlags.ExpandFill;
+ n.ClipText = true;
+ n.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
+ n.CustomMinimumSize = new Vector2(40, 0);
+ row.AddChild(n);
+ var count = UiTheme.Text(Fmt.Shares(h.Shares), 13, Palette.TextSecondary);
+ count.HorizontalAlignment = HorizontalAlignment.Right;
+ row.AddChild(count);
+ var pct = UiTheme.Text(Fmt.Pct(share), 13, share > control && h.Holder != HoldingInfo.Market ? Palette.Amber : Palette.Text, bold: true);
+ pct.CustomMinimumSize = new Vector2(64, 0);
+ pct.HorizontalAlignment = HorizontalAlignment.Right;
+ row.AddChild(pct);
+ _register.AddChild(row);
+ }
+ if (card.Treasury > 0)
+ _register.AddChild(PanelKit.Pair(T("Azioni proprie (non votano)"), PanelKit.Value(Fmt.Shares(card.Treasury))));
+ _register.AddChild(Wrapped($"{T("Quote sulle")} {Fmt.Shares(outstanding)} {T("azioni in circolazione: oltre il")} {Fmt.Pct(control, 0)} {T("si controlla la compagnia.")}", 12, Palette.TextSecondary));
+ }
+
+ private static Color HolderColor(ClientWorld w, int holder) => holder switch
+ {
+ HoldingInfo.Founder => Palette.Amber,
+ HoldingInfo.Market => Palette.TextSecondary,
+ _ => Fmt.CompanyColor(w, holder),
+ };
+
+ // ------------------------------------------------------------------ storico annuale
+
+ private void RefreshHistory(ClientWorld w)
+ {
+ foreach (var c in _history.GetChildren()) c.QueueFree();
+ var card = _selected >= 0 ? w.CompanyCards.GetValueOrDefault(_selected) : null;
+ if (card is null || card.History.Count == 0)
+ {
+ _history.AddChild(Wrapped(card is null ? T("Scheda in arrivo dal server…") : T("Nessun anno concluso: lo storico si scrive a fine anno."), 13, Palette.TextSecondary));
+ return;
+ }
+ var grid = new GridContainer { Columns = 5, SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ grid.AddThemeConstantOverride("h_separation", 12);
+ grid.AddThemeConstantOverride("v_separation", 4);
+ foreach (string h in new[] { T("Anno"), T("Patrimonio"), T("Utile"), T("Treni"), T("Liv.") })
+ {
+ var l = UiTheme.Text(h, 12, Palette.TextSecondary);
+ l.HorizontalAlignment = h == T("Anno") ? HorizontalAlignment.Left : HorizontalAlignment.Right;
+ if (h == T("Patrimonio")) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
+ grid.AddChild(l);
+ }
+ foreach (var y in Enumerable.Reverse(card.History).Take(8))
+ {
+ grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
+ foreach (var (text, color) in new[]
+ {
+ (y.NetWorth.ToString("short"), Palette.Text),
+ (y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Text),
+ ($"{y.Trains}", Palette.Text),
+ ($"{y.Tier}", Palette.Text),
+ })
+ {
+ var l = UiTheme.Text(text, 13, color);
+ l.HorizontalAlignment = HorizontalAlignment.Right;
+ grid.AddChild(l);
+ }
+ }
+ _history.AddChild(grid);
+ }
+
+ // ------------------------------------------------------------------ operazioni
+
+ private void RefreshActions(ClientWorld w)
+ {
+ int me = Me(w);
+ if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
+ {
+ if (_actionsKey.Length > 0) Clear(_actions);
+ _actionsKey = "";
+ return;
+ }
+ var card = w.CompanyCards.GetValueOrDefault(_selected);
+ var meInfo = w.Companies.GetValueOrDefault(me);
+ bool auction = card is { AuctionEndDay: >= 0 };
+ bool bidOpen = w.Tape?.Bids.Any(b => b.Target == _selected) == true;
+ string key = $"{_selected}|{info.Listed}|{info.Bankrupt}|{info.Merged}|{info.ControlledBy == me}|{auction}|{bidOpen}|{meInfo?.Listed}|{meInfo?.Receivership}|{card is null}";
+ if (key == _actionsKey) return;
+ _actionsKey = key;
+ Clear(_actions);
+ _updateEstimates = null;
+ if (card is null)
+ {
+ _actions.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
+ return;
+ }
+ if (info.Id == me) BuildOwnActions(w, info);
+ else if (info.Bankrupt) BuildAuction(w, info, card);
+ else BuildTradeActions(w, info, bidOpen);
+ }
+
+ private static void Clear(Container c)
+ {
+ foreach (var child in c.GetChildren()) child.QueueFree();
+ }
+
+ /// Operazioni sulla compagnia del giocatore: quotazione, dividendo, riacquisto.
+ private void BuildOwnActions(ClientWorld w, CompanyInfo me)
+ {
+ var sm = w.Data.Balance.StockMarket;
+ var updates = new List();
+ if (!me.Listed)
+ {
+ _actions.AddChild(UiTheme.Text(T("Quotazione in borsa"), 14, bold: true));
+ var slider = new HSlider { MinValue = 1, MaxValue = Math.Round(sm.IpoMaxShare * 100), Step = 1, Value = Math.Round(sm.IpoMaxShare * 100 / 2), SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ var label = UiTheme.Text("", 13);
+ label.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ _actions.AddChild(slider);
+ _actions.AddChild(label);
+ void Estimate()
+ {
+ long shares = (long)Math.Round(sm.Shares * slider.Value / 100);
+ label.Text = $"{T("Colloca il")} {Fmt.Number(slider.Value, 0)}% {T("del capitale")} ({Fmt.Shares(shares)} {T("azioni")}): {T("incasso stimato")} ≈ {Money.FromCentsRounded(shares * PriceCents(_session.World, me.Id))}";
+ }
+ slider.ValueChanged += _ => Estimate();
+ updates.Add(Estimate);
+ var ipo = UiTheme.Primary(T("Quotati in borsa"));
+ ipo.Pressed += () => _session.Command(new IpoCommand(slider.Value / 100), Result);
+ _actions.AddChild(ipo);
+ if (Fmt.UnlockTier(w, u => u.Ipo) is { } tier)
+ _actions.AddChild(Wrapped($"{T("La quotazione si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
+ }
+ else
+ {
+ _actions.AddChild(UiTheme.Text(T("Dividendo"), 14, bold: true));
+ var row = PanelKit.Row(6);
+ var perShare = new SpinBox { MinValue = 0.01, MaxValue = 1000, Step = 0.01, Value = 0.01, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ perShare.TooltipText = T("Dividendo per azione");
+ row.AddChild(perShare);
+ var pay = new Button { Text = T("Paga dividendo") };
+ pay.Pressed += () => _session.Command(new PayDividendCommand(new Money((long)Math.Round(perShare.Value * 100))), Result);
+ row.AddChild(pay);
+ _actions.AddChild(row);
+ var total = UiTheme.Text("", 12, Palette.TextSecondary);
+ total.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ _actions.AddChild(total);
+ void Estimate() => total.Text = $"{T("Totale")} {new Money((long)Math.Round(perShare.Value * 100) * Outstanding(_session.World, me.Id))} {T("agli azionisti; i dividendi alzano il sentiment del titolo.")}";
+ perShare.ValueChanged += _ => Estimate();
+ updates.Add(Estimate);
+ }
+ if (me.Listed || me.Receivership)
+ {
+ _actions.AddChild(PanelKit.Separator());
+ _actions.AddChild(UiTheme.Text(T("Riacquisto di azioni proprie"), 14, bold: true));
+ updates.Add(QuantityRow(w, me.Id, T("Riacquista"), null, n => new BuySharesCommand(new CompanyId(me.Id), n, Money.Zero), null,
+ me.Receivership ? T("In amministrazione controllata compri anche dal controllante, con il premio di riscatto.") : T("Le azioni tornano al fondatore e alzano la tua quota.")));
+ }
+ _updateEstimates = () => { foreach (var u in updates) u(); };
+ }
+
+ /// Compravendita, offerta pubblica e fusione per le altre compagnie.
+ private void BuildTradeActions(ClientWorld w, CompanyInfo target, bool bidOpen)
+ {
+ var sm = w.Data.Balance.StockMarket;
+ int me = Me(w);
+ var updates = new List();
+ int id = target.Id;
+ if (target.Listed)
+ {
+ _actions.AddChild(UiTheme.Text(T("Compravendita di azioni"), 14, bold: true));
+ updates.Add(QuantityRow(w, id, T("Compra"), T("Vendi"),
+ n => new BuySharesCommand(new CompanyId(id), n, Money.Zero),
+ n => new SellSharesCommand(new CompanyId(id), n, Money.Zero),
+ $"{T("Spread")} {Fmt.Pct(sm.Spread, 0)}; {T("al massimo il")} {Fmt.Pct(sm.MaxDailyTradeShare, 0)} {T("del capitale per ordine.")}"));
+ }
+ else
+ {
+ _actions.AddChild(Wrapped(T("Non quotata: le sue azioni non sono sul mercato."), 13, Palette.TextSecondary));
+ }
+
+ if (target.ControlledBy == me)
+ {
+ _actions.AddChild(PanelKit.Separator());
+ _actions.AddChild(UiTheme.Text(T("Fusione"), 14, bold: true));
+ var info = UiTheme.Text("", 12, Palette.TextSecondary);
+ info.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ _actions.AddChild(info);
+ updates.Add(() =>
+ {
+ long days = _session.World.CompanyCards.GetValueOrDefault(id)?.ControlDays ?? 0;
+ info.Text = $"{T("La controlli da")} {Math.Max(0, days)} {T("giorni")}; {T("la fusione è possibile dopo")} {sm.MergeAfterDays} {T("giorni e liquida le minoranze al prezzo di mercato.")}";
+ });
+ var merge = UiTheme.Primary(T("Incorpora la controllata"));
+ merge.Pressed += () => _session.Command(new MergeCompanyCommand(new CompanyId(id)), Result);
+ _actions.AddChild(merge);
+ }
+ else if (target.Listed)
+ {
+ _actions.AddChild(PanelKit.Separator());
+ _actions.AddChild(UiTheme.Text(T("Offerta pubblica di acquisto"), 14, bold: true));
+ if (bidOpen)
+ {
+ _actions.AddChild(Wrapped(T("C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra."), 12, Palette.TextSecondary));
+ }
+ else
+ {
+ double pMin = sm.BidPremiumMin * 100, pMax = sm.BidPremiumMax * 100;
+ var premiumLabel = UiTheme.Text("", 13);
+ var premium = new HSlider { MinValue = pMin, MaxValue = pMax, Step = 1, Value = pMin, SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ _actions.AddChild(premiumLabel);
+ _actions.AddChild(premium);
+ var shareLabel = UiTheme.Text("", 13);
+ double minTarget = Math.Floor(sm.ControlShare * 100) + 1;
+ var share = new HSlider { MinValue = minTarget, MaxValue = 100, Step = 1, Value = minTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ _actions.AddChild(shareLabel);
+ _actions.AddChild(share);
+ var cost = UiTheme.Text("", 12, Palette.TextSecondary);
+ cost.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ _actions.AddChild(cost);
+ long Cents() => BidCents(PriceCents(_session.World, id), premium.Value / 100, sm.BidPremiumMin, sm.BidPremiumMax);
+ void Estimate()
+ {
+ var world = _session.World;
+ double market = PriceCents(world, id);
+ long cents = Cents();
+ string effective = market > 0 ? Fmt.Change(cents / market - 1) : "—";
+ premiumLabel.Text = $"{T("Premio")} {Fmt.Number(premium.Value, 0)}% · {Fmt.Price(cents)} {T("per azione")} ({effective} {T("sul mercato")}: {Fmt.PricePrecise(market)})";
+ shareLabel.Text = $"{T("Quota obiettivo")} {Fmt.Number(share.Value, 0)}%";
+ long outstanding = Outstanding(world, id);
+ long needed = Math.Max(0, (long)Math.Ceiling(share.Value / 100 * outstanding) - Mine(world, id));
+ cost.Text = $"{T("Impegno massimo")} {new Money(needed * cents)} {T("per")} {Fmt.Shares(needed)} {T("azioni")}; {T("durata")} {sm.BidDurationDays} {T("giorni")}.";
+ }
+ premium.ValueChanged += _ => Estimate();
+ share.ValueChanged += _ => Estimate();
+ updates.Add(Estimate);
+ var launch = UiTheme.Primary(T("Lancia l'offerta"));
+ launch.Pressed += () => _session.Command(new LaunchBidCommand(new CompanyId(id), new Money(Cents()), share.Value / 100), Result);
+ _actions.AddChild(launch);
+ if (Fmt.UnlockTier(w, u => u.HostileTakeover) is { } tier)
+ _actions.AddChild(Wrapped($"{T("Le scalate ostili si sbloccano al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
+ }
+ }
+ _updateEstimates = () => { foreach (var u in updates) u(); };
+ }
+
+ /// Offerta all'asta degli attivi di una compagnia fallita (offerta = prezzo per azione × azioni).
+ private void BuildAuction(ClientWorld w, CompanyInfo seller, CompanyCard card)
+ {
+ if (card.AuctionEndDay < 0)
+ {
+ _actions.AddChild(Wrapped(T("Compagnia fallita: nessuna asta in corso."), 13, Palette.TextSecondary));
+ return;
+ }
+ int id = seller.Id;
+ long total = Math.Max(1, card.TotalShares);
+ _actions.AddChild(UiTheme.Text(T("Asta degli attivi"), 14, bold: true));
+ var best = PanelKit.Value();
+ var closing = PanelKit.Value();
+ var minimum = PanelKit.Value();
+ _actions.AddChild(PanelKit.Pair(T("Base d'asta"), minimum));
+ _actions.AddChild(PanelKit.Pair(T("Miglior offerta"), best));
+ _actions.AddChild(PanelKit.Pair(T("Chiusura"), closing));
+ var row = PanelKit.Row(6);
+ // l'offerta si esprime in lire; il protocollo la trasmette come prezzo per azione intero in centesimi
+ double step = total / 100.0;
+ var offer = new SpinBox { MinValue = step, MaxValue = 1e12, Step = step, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ row.AddChild(offer);
+ var bid = UiTheme.Primary(T("Offri all'asta"));
+ bid.Pressed += () =>
+ {
+ long perShare = (long)Math.Ceiling(offer.Value * 100 / total - 1e-9);
+ _session.Command(new LaunchBidCommand(new CompanyId(id), new Money(perShare), 1), Result);
+ };
+ row.AddChild(bid);
+ _actions.AddChild(row);
+ _actions.AddChild(Wrapped(T("Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita."), 12, Palette.TextSecondary));
+ bool initialized = false;
+ _updateEstimates = () =>
+ {
+ var world = _session.World;
+ var c = world.CompanyCards.GetValueOrDefault(id);
+ if (c is null || c.AuctionEndDay < 0) return;
+ minimum.Text = c.AuctionMin.ToString();
+ best.Text = c.AuctionBestBidder >= 0 ? $"{c.AuctionBest} · {Fmt.Company(world, c.AuctionBestBidder)}" : T("nessuna");
+ closing.Text = $"{Fmt.Date(world, c.AuctionEndDay)} ({Math.Max(0, c.AuctionEndDay - Fmt.Today(world))} {T("giorni")})";
+ double floor = Math.Max(c.AuctionMin.Cents, c.AuctionBest.Cents + 1) / 100.0;
+ double next = Math.Ceiling(floor / step) * step;
+ if (!initialized || (offer.Value < next && !offer.GetLineEdit().HasFocus()))
+ {
+ initialized = true;
+ offer.SetValueNoSignal(next);
+ }
+ };
+ }
+
+ /// Riga quantità di azioni + pulsanti, con la stima del controvalore e delle azioni possedute.
+ private Action QuantityRow(ClientWorld w, int company, string first, string? second,
+ Func firstCommand, Func? secondCommand, string note)
+ {
+ var sm = w.Data.Balance.StockMarket;
+ long max = Math.Max(1, (long)(sm.Shares * sm.MaxDailyTradeShare));
+ var row = PanelKit.Row(6);
+ var qty = new SpinBox { MinValue = 1, MaxValue = max, Step = 1, CustomArrowStep = 1000, Rounded = true, Value = Math.Min(10_000, max), SizeFlagsHorizontal = SizeFlags.ExpandFill };
+ qty.TooltipText = T("Numero di azioni");
+ row.AddChild(qty);
+ var a = UiTheme.Primary(first);
+ a.Pressed += () => _session.Command(firstCommand((long)qty.Value), Result);
+ row.AddChild(a);
+ if (second is not null && secondCommand is not null)
+ {
+ var b = new Button { Text = second };
+ b.Pressed += () => _session.Command(secondCommand((long)qty.Value), Result);
+ row.AddChild(b);
+ }
+ _actions.AddChild(row);
+ var estimate = UiTheme.Text("", 12, Palette.TextSecondary);
+ estimate.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ _actions.AddChild(estimate);
+ _actions.AddChild(Wrapped(note, 12, Palette.TextSecondary));
+ void Estimate()
+ {
+ var world = _session.World;
+ long held = Mine(world, company);
+ long outstanding = Math.Max(1, Outstanding(world, company));
+ long free = Quote(world, company)?.FreeFloat ?? 0;
+ estimate.Text = $"{T("Controvalore")} ≈ {Money.FromCentsRounded(qty.Value * PriceCents(world, company))} · " +
+ $"{(company == Me(world) ? T("il fondatore ha") : T("possiedi"))} {Fmt.Shares(held)} {T("azioni")} ({Fmt.Pct((double)held / outstanding)}) · {T("sul mercato")} {Fmt.Shares(free)}";
+ }
+ qty.ValueChanged += _ => Estimate();
+ return Estimate;
+ }
+
+ ///
+ /// Prezzo intero (centesimi) dell'offerta per il premio scelto, tenuto dentro i limiti del premio
+ /// nonostante l'arrotondamento al centesimo.
+ ///
+ private static long BidCents(double market, double premium, double min, double max)
+ {
+ double basis = Math.Max(1e-6, market);
+ long cents = (long)Math.Round(basis * (1 + premium));
+ if (cents / basis - 1 < min) cents = (long)Math.Ceiling(basis * (1 + min) - 1e-9);
+ if (cents / basis - 1 > max) cents = (long)Math.Floor(basis * (1 + max) + 1e-9);
+ return Math.Max(1, cents);
+ }
+
+ // ------------------------------------------------------------------ mattoni
+
+ private static PanelContainer Tag(string text, Color color)
+ {
+ var p = new PanelContainer();
+ p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, color, 4, 6));
+ p.AddChild(UiTheme.Text(text, 12, color, bold: true));
+ return p;
+ }
+
+ private static Label Wrapped(string text, int size, Color? color, bool bold = false)
+ {
+ var l = UiTheme.Text(text, size, color, bold);
+ l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
+ return l;
+ }
+}
diff --git a/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs.uid b/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs.uid
new file mode 100644
index 0000000..75569a1
--- /dev/null
+++ b/client/ViaFerrea.Client/scripts/Panels/CompaniesPanel.cs.uid
@@ -0,0 +1 @@
+uid://bxbrrccdi8qun
diff --git a/client/ViaFerrea.Client/scripts/Panels/Fmt.cs b/client/ViaFerrea.Client/scripts/Panels/Fmt.cs
new file mode 100644
index 0000000..e815d0d
--- /dev/null
+++ b/client/ViaFerrea.Client/scripts/Panels/Fmt.cs
@@ -0,0 +1,86 @@
+using System.Globalization;
+using ViaFerrea.Core.Common;
+using ViaFerrea.Protocol.Client;
+using static ViaFerrea.Client.App.Localization;
+
+namespace ViaFerrea.Client.Panels;
+
+///
+/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
+/// decimali con la virgola, prezzi delle azioni in lire con i centesimi.
+///
+public static class Fmt
+{
+ /// Numero con i decimali indicati e la virgola («12,4»).
+ public static string Number(double value, int decimals = 1)
+ {
+ string text = value.ToString(decimals <= 0 ? "0" : "0." + new string('0', decimals), CultureInfo.InvariantCulture);
+ int dot = text.IndexOf('.');
+ string integer = dot < 0 ? text : text[..dot];
+ bool negative = integer.StartsWith('-');
+ if (negative) integer = integer[1..];
+ string grouped = ulong.TryParse(integer, NumberStyles.None, CultureInfo.InvariantCulture, out ulong n) ? Money.GroupThousands(n) : integer;
+ return (negative ? "−" : "") + grouped + (dot < 0 ? "" : "," + text[(dot + 1)..]);
+ }
+
+ /// Quota (0–1) in percentuale («12,4%»).
+ public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
+
+ /// Variazione con il segno («+1,2%», «−0,8%»).
+ public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
+
+ /// Prezzo per azione dai centesimi frazionari («₤ 0,25»).
+ public static string Price(double cents) => Money.FromCentsRounded(cents).ToString("it2");
+
+ /// Prezzo per azione con i decimali che servono a leggere le variazioni sotto il centesimo («₤ 0,2534»).
+ public static string PricePrecise(double cents) => cents >= 10_000 ? Price(cents) : "₤ " + Number(cents / 100, cents >= 100 ? 2 : 4);
+
+ /// Numero di azioni con il punto delle migliaia.
+ public static string Shares(long shares) => shares < 0 ? "−" + Money.GroupThousands((ulong)(-shares)) : Money.GroupThousands((ulong)shares);
+
+ /// Giorno corrente della partita (dal resoconto giornaliero o dal tick).
+ public static long Today(ClientWorld w) =>
+ w.LastDigest?.Day ?? (w.Calendar is { } c ? w.Tick / c.TicksPerDay : 0);
+
+ /// Data di calendario di un giorno della partita.
+ public static string Date(ClientWorld w, long day) =>
+ w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).ToString() : $"{T("giorno")} {day}";
+
+ /// Nome di una compagnia (o «—» se sconosciuta).
+ public static string Company(ClientWorld w, int id) =>
+ w.Companies.TryGetValue(id, out var c) ? c.Name : id >= 0 ? $"#{id}" : "—";
+
+ /// Nome del livello della compagnia nella lingua dell'interfaccia.
+ public static string Tier(ClientWorld w, int tier)
+ {
+ var tiers = w.Data.Tiers.Tiers;
+ var def = tiers[Math.Clamp(tier, 1, tiers.Count) - 1];
+ return Godot.TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
+ }
+
+ ///
+ /// Livello che sblocca una funzione, se la compagnia del giocatore non ce l'ha ancora (solo per
+ /// il suggerimento: è il server a decidere).
+ ///
+ public static int? UnlockTier(ClientWorld w, Func unlock)
+ {
+ int tier = w.Companies.TryGetValue(w.Summary?.CompanyId ?? 0, out var me) ? me.Tier : 1;
+ var tiers = w.Data.Tiers.Tiers;
+ if (unlock(tiers[Math.Clamp(tier, 1, tiers.Count) - 1].Unlocks)) return null;
+ return tiers.FirstOrDefault(t => unlock(t.Unlocks))?.Level;
+ }
+
+ /// Carattere di una compagnia IA (id di ai.json); vuoto per il giocatore.
+ public static string Personality(ClientWorld w, string id) => id switch
+ {
+ "" => "",
+ "expansive" => T("Espansiva"),
+ "prudent" => T("Prudente"),
+ "predatory" => T("Predatoria"),
+ _ => w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == id)?.NameIt ?? id,
+ };
+
+ /// Colore di una compagnia dalla stringa esadecimale, con l'ambra in mancanza.
+ public static Godot.Color CompanyColor(ClientWorld w, int id) =>
+ w.Companies.TryGetValue(id, out var c) && Godot.Color.HtmlIsValid(c.Color) ? new Godot.Color(c.Color) : App.Palette.Amber;
+}
diff --git a/client/ViaFerrea.Client/scripts/Panels/Fmt.cs.uid b/client/ViaFerrea.Client/scripts/Panels/Fmt.cs.uid
new file mode 100644
index 0000000..6d75444
--- /dev/null
+++ b/client/ViaFerrea.Client/scripts/Panels/Fmt.cs.uid
@@ -0,0 +1 @@
+uid://u5pgogq2sft1
diff --git a/client/ViaFerrea.Client/scripts/Panels/IndustryPanel.cs b/client/ViaFerrea.Client/scripts/Panels/IndustryPanel.cs
new file mode 100644
index 0000000..83225f9
--- /dev/null
+++ b/client/ViaFerrea.Client/scripts/Panels/IndustryPanel.cs
@@ -0,0 +1,367 @@
+using Godot;
+using ViaFerrea.Client.App;
+using ViaFerrea.Client.Net;
+using ViaFerrea.Core.Commands;
+using ViaFerrea.Core.Common;
+using ViaFerrea.Core.Economy;
+using ViaFerrea.Protocol.Client;
+using ViaFerrea.Protocol.Messages;
+using static ViaFerrea.Client.App.Localization;
+
+namespace ViaFerrea.Client.Panels;
+
+///
+/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
+/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
+/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
+/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
+/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
+///
+public partial class IndustryPanel : VBoxContainer
+{
+ private readonly GameSession _session;
+ private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
+ private readonly List _ids = [];
+ private readonly VBoxContainer _header = PanelKit.Column(8);
+ private readonly VBoxContainer _controls = PanelKit.Column(8);
+ private readonly VBoxContainer _details = PanelKit.Column(6);
+ private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
+ private readonly List