F5–F7: industrie, IA, borsa, economia completa e gioco infinito #2

Merged
Alby96 merged 2 commits from claude/funny-pasteur-jvtug9 into main 2026-10-19 11:58:34 +02:00
97 changed files with 8151 additions and 147 deletions

No files matched your search

@@ -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.
1 keys it en
2 Abitanti Population
3 Accetta Accept
4 Acquista Buy
5 Aderisci con le tue azioni Tender your shares
6 Aggiorna Refresh
7 Alto High
8 Ambra Amber
9 Amministrazione controllata Receivership
10 Ammoderna Upgrade
11 Ammodernamento Upgrade
12 Ammodernamento di livello Level upgrade
13 Ammodernamento programmato Upgrade scheduled
14 Ancora nessun fatto da raccontare. Nothing to tell yet.
15 Anno Year
16 Annulla Cancel
17 Anteprima non disponibile: Preview unavailable:
18 Appartiene a Belongs to
19 Assegna Assign
20 Asta degli attivi Asset auction
21 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
22 Attiva Active
23 Avvio del server locale… Starting the local server…
24 Azioni proprie (non votano) Treasury shares (no vote)
25 Base Base
26 Base d'asta Reserve price
27 Binari Track
28 Binari di stazione Platforms
29 Blu Blue
30 Budget di manutenzione Maintenance budget
31 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.
32 Cantiere Construction
33 Capitalizz. Market cap
34 Capitalizzazione Market cap
35 Carico Load
36 Cartella di manutenzione Maintenance record
37 Cartella in arrivo dal server… Record on its way from the server…
38 Cassa Cash
39 Cassa dell'industria Industry cash
40 Cavaliere bianco White knight
41 Celeste Light blue
42 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.
43 Chiedi il prestito Request loan
44 Chiudi Close
45 Chiusa Closed
46 Chiusura Closes
47 Classe Class
48 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.
49 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
50 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.
51 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.
52 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.
56 Collegamento non riuscito Connection failed
57 Collegati Connect
58 Collegati a un server Connect to a server
59 Colloca il Float
60 Come la linea o la flotta Same as line or fleet
61 Compagnia Company
62 Compagnia fallita: nessuna asta in corso. Bankrupt company: no auction running.
63 Compagnie Companies
64 Compagnie e borsa Companies and stock exchange
65 Componi Compose
66 Compra Buy
67 Compra veicoli Buy vehicles
68 Compravendita di azioni Share trading
69 Condizione Condition
70 Connessione persa Connection lost
71 Consuma Consumes
72 Continua come osservatore Continue as observer
73 Controllo Control
74 Controvalore Value
75 Convenzioni Agreements
76 Coperto dalla riserva Covered by reserve
77 Costi dell'anno Costs this year
78 Costo Cost
79 Costo dell'ammodernamento Upgrade cost
80 Costruisci Build
81 Crea linea Create line
82 Cronaca finale Final chronicle
83 Cronaca provvisoria Chronicle so far
84 Dati del gioco non trovati o non validi. Game data missing or invalid.
85 Dati insufficienti Not enough data
86 Debito Debt
87 Demolisci Demolish
88 Depositi e officine Depots and workshops
89 Deposito Depot
90 Deragliamento Derailment
91 Difese del bersaglio Target's defences
92 Disconnesso Disconnected
93 Dividendi (12 mesi) Dividends (12 months)
94 Dividendo Dividend
95 Dividendo per azione Dividend per share
96 Dividendo straordinario Extra dividend
97 Doppio binario Double track
98 Dove lavorano gli abitanti Where residents work
99 Efficienza Efficiency
100 Elettrificato Electrified
101 Esci Quit
102 Espansiva Expansive
103 Fallimento Bankruptcy
104 Fatti salienti Highlights
105 Fermo Shutdown
106 Fermo programmato Planned shutdown
107 Finanze Finance
108 Flotta, dal treno più usurato Fleet, most worn first
109 Fondatore (tu) Founder (you)
110 Fondatore privato Private founder
111 Fusione Merger
112 Galleria Tunnel
113 Gallerie Tunnels
114 Gestionale ferroviario dall'alto Top-down railway management
115 Gestisci l'industria Manage the industry
116 Grano Wheat
117 Guasti nell'anno Failures this year
118 Guasto Breakdown
119 Guasto grave Major failure
120 Guasto lieve Minor failure
121 Hai aderito con tutte le tue azioni. You tendered all your shares.
122 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.
123 Il server non risponde più. La partita continua sul server. The server is not responding. The game goes on on the server.
124 Impegno massimo Maximum commitment
125 Impianti Plant
126 Impieghi Jobs
127 In amministrazione controllata compri anche dal controllante, con il premio di riscatto. In receivership you also buy from the controller, at the ransom premium.
128 In attesa del listino del giorno… Waiting for today's share list…
129 In vendita For sale
130 Incidente grave Serious accident
131 Incorpora la controllata Merge the subsidiary
132 Indica l'indirizzo del server Enter the server address
133 Indietro Back
134 Indirizzo (host:porta) Address (host:port)
135 Indirizzo non valido Invalid address
136 Industrie Industries
137 Km di binari Track km
138 Km di servizio al giorno Service km per day
139 L'acquisto di industrie si sblocca al livello Buying industries unlocks at level
140 La compagnia è stata scalata The company was taken over
141 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://).
142 La controlli da You have controlled it for
143 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.
144 La quotazione si sblocca al livello Listing unlocks at level
145 La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio. Your company's story so far: charts, records, highlights and prestige.
146 La tua compagnia Your company
147 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
148 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.
149 Lancia l'offerta Launch the bid
150 Lavoratori Workers
151 Lavoratori e personale Workers and staff
152 Le azioni tornano al fondatore e alzano la tua quota. Shares return to the founder and raise your stake.
153 Le scalate ostili si sbloccano al livello Hostile takeovers unlock at level
154 Libro dei soci Shareholder register
155 Linea Line
156 Linee Lines
157 Linee della compagnia Company lines
158 Listino Share list
159 Listino del Share list of
160 Liv. Lvl
161 Livello Level
162 Lo storico si forma alla fine di ogni mese History builds up at the end of each month
163 Locomotiva Locomotive
164 Lunghezza Length
165 Macchinari Machinery
166 Manda al deposito Send to depot
167 Manutenzione Maintenance
168 Manutenzione al giorno Maintenance per day
169 Mappa di calore della condizione Condition heat map
170 Margine Margin
171 Mercato Market
172 Mercato (flottante) Market (free float)
173 Merci e passeggeri in attesa Waiting goods and passengers
174 Miglior offerta Best offer
175 Minimappa Minimap
176 Nel bacino In the catchment
177 Nessun anno concluso: lo storico si scrive a fine anno. No year closed yet: history is written at year end.
178 Nessun anno registrato No year recorded
179 Nessun fermo finora No shutdowns so far
180 Nessun posto di lavoro servito dai tuoi treni. No workplace served by your trains.
181 Nessun tracciato No route
182 Nessun treno in officina No trains in the workshop
183 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.
184 Nessuna linea No line
185 Nessuna offerta in corso. Un'offerta dura No open bids. A bid lasts
186 Nessuno None
187 Nome automatico Automatic name
188 Nome del treno Train name
189 Nome della linea Line name
190 Non quotata: le sue azioni non sono sul mercato. Not listed: its shares are not on the market.
191 Notizie News
192 Numero di azioni Number of shares
193 Nuova mappa con la difficoltà New map at difficulty
194 Nuova partita+ New game+
195 Nuova partita+ in preparazione Preparing New game+
196 Offerta pubblica di acquisto Takeover bid
197 Offerte pubbliche in corso Open takeover bids
198 Officine Workshops
199 Offri all'asta Bid at auction
200 Oggi il fondatore ha il The founder now holds
201 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.
202 Operazioni Actions
203 Ordina Order
204 Ordina ricambi Order parts
205 Paga dividendo Pay dividend
206 Partita conclusa Game over
207 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.
208 Partita locale Local game
209 Partita locale non avviata Local game not started
210 Patrimonio Net worth
211 Patrimonio netto Net worth
212 Patrimonio netto anno per anno Net worth year by year
213 Pausa Pause
214 Pendenza massima Max gradient
215 Personale Staff
218 Ponte Bridge
219 Ponti Bridges
220 Posti di lavoro Workplaces
221 Predatoria Predatory
222 Premio Premium
223 Prenotato Booked
224 Prestigio Prestige
225 Prestito Loan
226 Prezzi globali di oggi (la borsa arriva in seguito). Today's global prices (the stock market comes later).
227 Prezzo chiesto dai proprietari Asking price
228 Prezzo dell'azione a fine mese Month-end share price
229 Prezzo per azione Share price
230 Prezzo · var. Price · chg.
231 Primati Records
232 Produce Produces
233 Proprietari privati Private owners
234 Proprietà Owner
235 Prossimo intervento Next intervention
236 Prudente Prudent
237 Quota obiettivo Target stake
238 Quota rispetto al terreno Height above ground
239 Quotati in borsa Go public
240 Quotazione in borsa Stock market listing
241 Quote sulle Stakes of the
242 Raggio minimo Min radius
243 Rating Rating
244 Recupero Recovery
245 Recupero al giorno Recovery per day
246 Regione di Region of
247 Registro degli impieghi Employment register
248 Registro in arrivo dal server… Register on its way from the server…
249 Registro officina Workshop register
250 Resa impianti Plant output
251 Revisione Overhaul
252 Revisione programmata Overhaul scheduled
253 Riacquista Buy back
254 Riacquista almeno il Buy back at least
255 Riacquista azioni Buy back shares
256 Riacquisto Buyback
257 Riacquisto di azioni proprie Own share buyback
258 Ricambi Spare parts
259 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.
260 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.
261 Ricambi extra Extra parts
262 Ricambi già destinati Parts already allocated
263 Ricavi Revenue
264 Rifiuta Reject
265 Rilevato Embankment
266 Riscatto non riuscito in tempo Buyback not completed in time
267 Rischio di fermo in un anno Breakdown risk within a year
268 Ritira l'adesione Withdraw acceptance
269 Ritmo di lavoro (manca personale) Work rate (staff shortage)
270 Rosso coppo Tile red
271 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.
272 Scegli una compagnia nel listino Pick a company from the list
273 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.
274 Scheda del proprietario Owner's card
275 Scheda in arrivo dal server… Card on its way from the server…
276 Scorta desiderata Target stock
277 Scorte Stock
278 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.
279 Segnali Signals
280 Seleziona i veicoli da comporre Select the vehicles to compose
281 Seleziona un treno Select a train
282 Seleziona un treno e un deposito Select a train and a depot
283 Sentiment del mercato Market sentiment
284 Serve un deposito A depot is required
285 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.
286 Servizi Services
287 Servono almeno due fermate At least two stops are needed
288 Soddisfazione Satisfaction
289 Sopra il Above
290 Spesa di manutenzione nell'anno Maintenance spent this year
291 Spread Spread
292 Stalli Stalls
293 Stato Status
294 Stazione Station
295 Storico History
296 Storico annuale Yearly history
297 Storico dei fermi Shutdown history
298 Svuota Clear
299 Token Token
300 Token del server Server token
301 Torna al menu Back to menu
302 Torna alla partita Back to the game
303 Totale Total
304 Treni Trains
305 Treni della compagnia Company trains
306 Treno di riserva in deposito Reserve train in depot
307 Trincea Cutting
308 Tua quota Your stake
309 Usura al giorno Wear per day
310 Utile Profit
311 Utile annuo Annual profit
312 Veicoli Vehicles
313 Veicoli liberi nel deposito (selezione multipla, in ordine) Free vehicles in the depot (multiple selection, in order)
314 Velocità Speed
315 Vendi Sell
316 Verde Green
317 Via Ferrea Via Ferrea
318 a piedi on foot
319 abitanti inhabitants
320 agli azionisti; i dividendi alzano il sentiment del titolo. to shareholders; dividends raise the share's sentiment.
321 al 20% e si fermano più spesso. at 20% and stop more often.
322 al massimo il at most
323 al mese per month
324 altrimenti la partita finisce. Intanto versi il or the game ends. Meanwhile you pay
325 amministrazione controllata receivership
326 anni years
327 attende waiting for
328 attende i ricambi waiting for parts
329 attendi il pieno wait for full load
330 azioni shares
331 azioni in circolazione: oltre il outstanding shares: above
332 capacità delle carrozze insufficiente sulla not enough coach capacity on
333 capacità mancante da capacity short for
334 carica load
335 cavaliere bianco white knight
336 città senza servizi per il personale towns without services for staff
337 consumo use
338 controlla la compagnia controls the company
339 controllata da controlled by
340 copertura coverage
341 da from
342 degli utili come dividendo e non puoi chiedere prestiti. of profits as dividends and cannot take new loans.
343 dei ricavi of revenue
344 del capitale of the capital
345 del capitale per ordine. of the capital per order.
346 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
347 delle azioni entro il of the shares by
348 di of
349 dividendo straordinario extra dividend
350 durata duration
351 e il and
352 e personale sufficiente and enough staff
353 fallita bankrupt
354 fallita, attivi all'asta bankrupt, assets at auction
355 ferma stopped
356 ferma fino al stopped until
357 fermo in linea stranded on the line
358 fermo in salita stalled on grade
359 g d
360 giorni days
361 giorni di fermo days of shutdown
362 giorni e liquida le minoranze al prezzo di mercato. days and buys out the minorities at market price.
363 giorni e offre un premio tra il days and offers a premium between
364 giorno day
365 gli impianti rendono pieno; sotto calano fino a plants run at full output; below they drop to
366 guasto broken down
367 guasto lieve minor failure
368 hub mercato mondiale world market hub
369 il fondatore ha the founder holds
370 impegnato committed
371 in arrivo arriving
372 in attesa waiting
373 in attesa di via libera waiting for clearance
375 in deposito in depot
376 in marcia running
377 in officina in the workshop
378 in scorta in stock
379 in servizio in service
380 in stazione at station
381 incasso stimato estimated proceeds
382 intervento prenotato intervention booked
383 la fusione è possibile dopo the merger is possible after
384 la tua compagnia your company
385 large Grande Large
386 lavoratori workers
387 lavori jobs
388 le città raggiungibili non hanno lavoratori liberi reachable towns have no free workers
389 linea line
390 livello level
391 macchinari machinery
392 macchinari per il prossimo lavoro machinery for the next job
393 macchinari per livello machinery per level
394 medium Medio Medium
395 mesi months
396 mila km thousand km
397 nessuna none
398 nessuna città raggiungibile entro no town reachable within
399 nessuna stazione serve il posto di lavoro no station serves the workplace
400 non quotata not listed
401 non è in vendita. not for sale.
402 obiettivo target
403 ordinati in più extra ordered
404 ore hours
405 per for
406 per azione per share
407 personale staff
408 personale almeno al staff at least at
409 portafoglio azioni share portfolio
410 possiedi you hold
411 posti al giorno garantiti guaranteed seats a day
412 privati private
413 punti al giorno points per day
414 quotata listed
415 respinta dal consiglio rejected by the board
416 riacquisto buyback
417 ricambi parts
418 ricambi al mese per livello spare parts per month per level
419 rimorchiato towed
420 riporta la condizione a 100. restores condition to 100.
421 riserva reserve
422 scade il expires on
423 scaduta overdue
424 scaduto overdue
425 scarica unload
426 scorta della politica policy stock
427 senza linea no line
428 senza percorso no route
429 servono needs
430 si controlla la compagnia. you control the company.
431 small Piccolo Small
432 soccorso tra rescue in
433 stallo stall
434 sul mercato on the market
435 sul prezzo di mercato. over the market price.
436 tecnici staff
437 tra in
438 treni trains
439 tu you
440 tua yours
441 ultimi last
442 vincitore winner
443 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.
444 ⚠ 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.
@@ -14,7 +14,9 @@ namespace ViaFerrea.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): 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).
/// </summary>
public partial class AutoPilot : Node
{
@@ -73,6 +75,18 @@ public partial class AutoPilot : Node
return r.Created.Length > 0 ? r.Created[0] : -1;
}
/// <summary>Attende una condizione al massimo per il tempo indicato, senza fallire.</summary>
private async Task<bool> Wait(Func<bool> 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);
}
/// <summary>F5: scheda del proprietario di un'industria, borsa con il libro dei soci, Cronaca provvisoria.</summary>
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);
}
}
+34 -3
View File
@@ -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;
/// <summary>
/// Tema costruito da <see cref="Build"/>. Il tema della finestra non attraversa i nodi che non
/// sono Control (Main, CanvasLayer): ogni radice dell'interfaccia lo riceve con <see cref="Apply"/>.
/// </summary>
public static Theme? Current { get; private set; }
/// <summary>Assegna il tema a una radice dell'interfaccia (figlia di un nodo che non è un Control).</summary>
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;
}
+32 -8
View File
@@ -5,9 +5,12 @@ using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
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 }
/// <summary>Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.</summary>
/// <summary>
/// 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.
/// </summary>
public partial class Toolbar : PanelContainer
{
private readonly Dictionary<Tool, ToolButton> _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);
@@ -20,6 +20,9 @@ public sealed class GameSession : IAsyncDisposable
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
/// <summary>Preset di difficoltà della partita (dal Welcome; serve a «Nuova partita+»).</summary>
public string Difficulty { get; private set; } = "";
public LocalServerLauncher? LocalServer { get; set; }
/// <summary>Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.</summary>
@@ -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;
@@ -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;
/// <summary>
/// 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'è.
/// </summary>
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<int, CompanyRow> _rowById = [];
private readonly Dictionary<int, (Label Text, ProgressBar Bar)> _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);
}
/// <summary>Compagnia della scheda (−1 se nessuna).</summary>
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);
/// <summary>Prezzo per azione in centesimi: dal listino se c'è, altrimenti dalla scheda dell'entità.</summary>
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;
}
/// <summary>Azioni della compagnia del giocatore nella compagnia indicata (dal libro dei soci).</summary>
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);
}
/// <summary>Vero/falso se il libro dei soci è noto, null se la scheda non è ancora arrivata.</summary>
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<string>();
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);
}
}
/// <summary>Riga del listino: pulsante piatto con le colonne allineate.</summary>
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<string>();
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();
}
/// <summary>Operazioni sulla compagnia del giocatore: quotazione, dividendo, riacquisto.</summary>
private void BuildOwnActions(ClientWorld w, CompanyInfo me)
{
var sm = w.Data.Balance.StockMarket;
var updates = new List<Action>();
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(); };
}
/// <summary>Compravendita, offerta pubblica e fusione per le altre compagnie.</summary>
private void BuildTradeActions(ClientWorld w, CompanyInfo target, bool bidOpen)
{
var sm = w.Data.Balance.StockMarket;
int me = Me(w);
var updates = new List<Action>();
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(); };
}
/// <summary>Offerta all'asta degli attivi di una compagnia fallita (offerta = prezzo per azione × azioni).</summary>
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);
}
};
}
/// <summary>Riga quantità di azioni + pulsanti, con la stima del controvalore e delle azioni possedute.</summary>
private Action QuantityRow(ClientWorld w, int company, string first, string? second,
Func<long, GameCommand> firstCommand, Func<long, GameCommand>? 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;
}
/// <summary>
/// Prezzo intero (centesimi) dell'offerta per il premio scelto, tenuto dentro i limiti del premio
/// nonostante l'arrotondamento al centesimo.
/// </summary>
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;
}
}
@@ -0,0 +1 @@
uid://bxbrrccdi8qun
@@ -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;
/// <summary>
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
/// decimali con la virgola, prezzi delle azioni in lire con i centesimi.
/// </summary>
public static class Fmt
{
/// <summary>Numero con i decimali indicati e la virgola («12,4»).</summary>
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)..]);
}
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
/// <summary>Prezzo per azione dai centesimi frazionari («₤ 0,25»).</summary>
public static string Price(double cents) => Money.FromCentsRounded(cents).ToString("it2");
/// <summary>Prezzo per azione con i decimali che servono a leggere le variazioni sotto il centesimo («₤ 0,2534»).</summary>
public static string PricePrecise(double cents) => cents >= 10_000 ? Price(cents) : "₤ " + Number(cents / 100, cents >= 100 ? 2 : 4);
/// <summary>Numero di azioni con il punto delle migliaia.</summary>
public static string Shares(long shares) => shares < 0 ? "−" + Money.GroupThousands((ulong)(-shares)) : Money.GroupThousands((ulong)shares);
/// <summary>Giorno corrente della partita (dal resoconto giornaliero o dal tick).</summary>
public static long Today(ClientWorld w) =>
w.LastDigest?.Day ?? (w.Calendar is { } c ? w.Tick / c.TicksPerDay : 0);
/// <summary>Data di calendario di un giorno della partita.</summary>
public static string Date(ClientWorld w, long day) =>
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).ToString() : $"{T("giorno")} {day}";
/// <summary>Nome di una compagnia (o «—» se sconosciuta).</summary>
public static string Company(ClientWorld w, int id) =>
w.Companies.TryGetValue(id, out var c) ? c.Name : id >= 0 ? $"#{id}" : "—";
/// <summary>Nome del livello della compagnia nella lingua dell'interfaccia.</summary>
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;
}
/// <summary>
/// Livello che sblocca una funzione, se la compagnia del giocatore non ce l'ha ancora (solo per
/// il suggerimento: è il server a decidere).
/// </summary>
public static int? UnlockTier(ClientWorld w, Func<Core.Data.TierUnlocks, bool> 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;
}
/// <summary>Carattere di una compagnia IA (id di ai.json); vuoto per il giocatore.</summary>
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,
};
/// <summary>Colore di una compagnia dalla stringa esadecimale, con l'ambra in mancanza.</summary>
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;
}
@@ -0,0 +1 @@
uid://u5pgogq2sft1
@@ -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;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
/// </summary>
public partial class IndustryPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly List<int> _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<Button> _budgetButtons = [];
private SpinBox? _partsOrder;
private int _industry = -1;
private (int Industry, int Owner) _controlsKey = (-2, -2);
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
public IndustryPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_list);
AddChild(PanelKit.Separator());
AddChild(_header);
AddChild(_controls);
AddChild(_details);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_list.ItemSelected += i => Select(_ids[(int)i]);
RefreshList();
}
/// <summary>Industria mostrata (−1 se nessuna).</summary>
public int Industry => _industry;
public void Select(int id)
{
if (id == _industry) return;
_industry = id;
_status.Text = "";
SyncSelection();
Request();
Refresh();
}
private void Request()
{
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
}
public override void _Process(double delta)
{
// la scheda aperta si aggiorna una volta al secondo; il pannello al massimo quattro volte
_request += delta;
_sinceRefresh += delta;
if (_request >= 1)
{
_request = 0;
Request();
}
var w = _session.World;
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
Request();
}
private void Refresh()
{
var w = _session.World;
_sinceRefresh = 0;
if (w.EntityVersion != _entityVersion) RefreshList();
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
foreach (var c in _header.GetChildren()) c.QueueFree();
foreach (var c in _details.GetChildren()) c.QueueFree();
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
{
BuildControls(null);
return;
}
var card = w.IndustryCards.GetValueOrDefault(_industry);
BuildHeader(w, ind, card);
BuildControls(ind);
UpdateControls(ind, card);
BuildDetails(w, ind, card);
}
// ------------------------------------------------------------------ elenco
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
private void RefreshList()
{
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
long today = Fmt.Today(w);
var ordered = w.Industries.Values.Where(i => !i.Closed)
.OrderBy(i => i.Owner == me ? 0 : i.Owner < 0 ? 1 : 2).ThenBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Id).ToList();
bool same = ordered.Count == _ids.Count && ordered.Select(i => i.Id).SequenceEqual(_ids);
if (!same)
{
_ids.Clear();
_list.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
var ind = ordered[n];
string owner = ind.Owner == me ? T("tua") : ind.Owner < 0 ? T("privati") : Fmt.Company(w, ind.Owner);
string stop = ind.StoppedUntilDay >= today ? " · " + T("ferma") : "";
string text = $"{ind.Name} · {Fmt.Number(ind.Condition, 0)}% · {owner}{stop}";
if (!same)
{
_ids.Add(ind.Id);
_list.AddItem(text);
}
else if (_list.GetItemText(n) != text)
{
_list.SetItemText(n, text);
}
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
}
if (!same) SyncSelection();
}
private void SyncSelection()
{
int index = _ids.IndexOf(_industry);
if (index < 0)
{
_list.DeselectAll();
return;
}
if (!_list.IsSelected(index)) _list.Select(index);
_list.EnsureCurrentIsVisible();
}
// ------------------------------------------------------------------ scheda
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
int me = w.Summary?.CompanyId ?? 0;
var title = UiTheme.TitleLabel(ind.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_header.AddChild(title);
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
long today = Fmt.Today(w);
if (ind.StoppedUntilDay >= today)
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
else if (ind.PendingWork != 0)
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
if (ind.PartsShort)
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
var stats = PanelKit.Row(8);
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
_header.AddChild(stats);
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
_header.AddChild(bar);
var m = w.Data.Balance.IndustryMaintenance;
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
}
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
private void BuildControls(IndustryInfo? ind)
{
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
if (key == _controlsKey) return;
_controlsKey = key;
foreach (var c in _controls.GetChildren()) c.QueueFree();
_budgetButtons.Clear();
_partsOrder = null;
if (ind is null) return;
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
int id = ind.Id;
if (ind.Owner == me)
{
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
else if (ind.Owner < 0)
{
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
var price = PanelKit.Value("—");
price.Name = "Price";
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
var buy = UiTheme.Primary(T("Acquista"));
buy.Pressed += () =>
{
if (_session.World.IndustryCards.TryGetValue(id, out var c))
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
else
Request();
};
_controls.AddChild(buy);
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
}
}
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
{
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
}
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
if (card is null)
{
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = w.Summary?.CompanyId ?? 0;
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
if (ind.Owner == me)
{
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
}
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
{
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
_details.AddChild(l);
}
}
private static Control StockRow(string caption, int have, int target, Color color)
{
var row = PanelKit.Row(8);
var name = UiTheme.Text(caption, 13, Palette.TextSecondary);
name.CustomMinimumSize = new Vector2(96, 0);
row.AddChild(name);
var bar = new ProgressBar { MaxValue = Math.Max(1, Math.Max(have, target)), Value = have, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 3, 0));
row.AddChild(bar);
row.AddChild(UiTheme.Text($"{have} / {target}", 13, bold: true));
return row;
}
// ------------------------------------------------------------------ testi
public static string StopName(byte kind) => kind switch
{
1 => T("Guasto"),
2 => T("Incidente grave"),
3 => T("Revisione"),
4 => T("Ammodernamento"),
_ => T("Fermo"),
};
private static string WorkName(byte work) => work switch
{
1 => T("Revisione programmata"),
2 => T("Ammodernamento programmato"),
_ => "",
};
private static Label ColoredValue(string text, Color color)
{
var l = PanelKit.Value(text);
l.AddThemeColorOverride("font_color", color);
return l;
}
private static Label Wrapped(string text, int size, Color? color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://j8ci61w6roh6
@@ -18,6 +18,7 @@ public partial class InfoPanel : VBoxContainer
private double _refresh;
public event Action<int>? MaintenanceRequested;
public event Action<int>? IndustryRequested;
public InfoPanel(GameSession session)
{
@@ -141,6 +142,16 @@ public partial class InfoPanel : VBoxContainer
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
int me = w.Summary?.CompanyId ?? 0;
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
if (ind.StoppedUntilDay >= Fmt.Today(w))
AddChild(UiTheme.Notice($"{IndustryPanel.StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)}"));
int industryId = ind.Id;
var ownerButton = new Button { Text = ind.Owner == me ? T("Gestisci l'industria") : T("Scheda del proprietario") };
ownerButton.Pressed += () => IndustryRequested?.Invoke(industryId);
AddChild(ownerButton);
// dal Registro degli impieghi: presenze, posti scoperti e provenienza dei pendolari
if (w.Employment?.Rows.FirstOrDefault(r => r.Kind == 0 && r.Industry == ind.Id) is { } row)
{
@@ -0,0 +1,119 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// </summary>
public partial class SeriesChart : Control
{
public enum Style { Line, Bars }
private IReadOnlyList<double> _values = [];
private IReadOnlyList<string> _labels = [];
private Func<double, string> _format = v => Fmt.Number(v, 0);
private Style _style;
private Color _color = Palette.Amber;
private string _empty = "";
public SeriesChart(float height = 150)
{
CustomMinimumSize = new Vector2(0, height);
MouseFilter = MouseFilterEnum.Ignore;
}
/// <summary>Imposta la serie: valori, etichette dell'asse orizzontale (facoltative) e formato dei valori.</summary>
public void Show(IReadOnlyList<double> values, IReadOnlyList<string> labels, Func<double, string> format, Style style, Color color, string empty)
{
_values = values;
_labels = labels;
_format = format;
_style = style;
_color = color;
_empty = empty;
QueueRedraw();
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var font = UiTheme.Body;
const int fontSize = 11;
if (_values.Count == 0 || (_style == Style.Line && _values.Count < 2))
{
string text = _empty.Length > 0 ? _empty : T("Dati insufficienti");
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, Size.Y / 2 + 4), text, HorizontalAlignment.Left, -1, 13, Palette.TextSecondary);
return;
}
double min = _values.Min(), max = _values.Max();
if (_style == Style.Bars) min = Math.Min(0, min);
if (max - min < 1e-9)
{
max += Math.Max(1, Math.Abs(max) * 0.1);
if (_style == Style.Line) min -= Math.Max(1, Math.Abs(min) * 0.1);
}
string maxText = _format(max), minText = _format(min);
float left = 12 + Math.Max(font.GetStringSize(maxText, HorizontalAlignment.Left, -1, fontSize).X, font.GetStringSize(minText, HorizontalAlignment.Left, -1, fontSize).X) + 8;
bool hasLabels = _labels.Count == _values.Count;
var area = new Rect2(left, 12, Size.X - left - 14, Size.Y - (hasLabels ? 34 : 22));
float Y(double v) => area.End.Y - (float)((v - min) / (max - min)) * area.Size.Y;
// griglia: massimo, metà, minimo
foreach (double v in new[] { min, (min + max) / 2, max })
DrawLine(new Vector2(area.Position.X, Y(v)), new Vector2(area.End.X, Y(v)), Palette.WithAlpha(Palette.Border, 0.9f), 1);
DrawString(font, new Vector2(10, Y(max) + 4), maxText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
DrawString(font, new Vector2(10, Y(min) + 4), minText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
int n = _values.Count;
if (_style == Style.Bars)
{
float slot = area.Size.X / n;
float width = Math.Max(2, Math.Min(42, slot * 0.7f));
for (int i = 0; i < n; i++)
{
float x = area.Position.X + slot * (i + 0.5f);
float y0 = Y(Math.Max(min, 0)), y1 = Y(_values[i]);
var color = _values[i] < 0 ? Palette.Danger : i == n - 1 ? Palette.AmberLight : _color;
DrawRect(new Rect2(x - width / 2, Math.Min(y0, y1), width, Math.Max(1, Math.Abs(y1 - y0))), color);
}
DrawLabels(area, n, slot, font, fontSize, centered: true);
return;
}
float step = area.Size.X / (n - 1);
var points = new Vector2[n];
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
DrawPolyline(points, _color, 2.5f, true);
DrawCircle(points[^1], 4, Palette.AmberLight);
string last = _format(_values[^1]);
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
float lx = Math.Min(points[^1].X - lastDims.X / 2, Size.X - lastDims.X - 6);
float ly = points[^1].Y - 8 < area.Position.Y + 10 ? points[^1].Y + 18 : points[^1].Y - 8;
DrawString(UiTheme.BodyBold, new Vector2(lx, ly), last, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
DrawLabels(area, n, step, font, fontSize, centered: false);
}
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
{
if (_labels.Count != n) return;
float widest = _labels.Max(l => font.GetStringSize(l, HorizontalAlignment.Left, -1, fontSize).X) + 10;
int every = Math.Max(1, (int)Math.Ceiling(widest / Math.Max(1, step)));
for (int i = 0; i < n; i++)
{
// l'ultima etichetta si aggiunge solo se non tocca la precedente
bool show = i % every == 0 || (i == n - 1 && (n - 1) % every * step >= widest);
if (!show) continue;
var dims = font.GetStringSize(_labels[i], HorizontalAlignment.Left, -1, fontSize);
float x = area.Position.X + step * (centered ? i + 0.5f : i) - dims.X / 2;
x = Math.Clamp(x, area.Position.X - 4, Size.X - dims.X - 4);
DrawString(font, new Vector2(x, area.End.Y + 16), _labels[i], HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
}
}
}
@@ -0,0 +1 @@
uid://cvus3vxujok5q
@@ -34,7 +34,9 @@ public partial class TrackPanel : VBoxContainer
_world = world;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Binari"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary));
var help = UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
foreach (var cls in world.Data.Eras.TrackClasses)
{
_class.AddItem($"{cls.NameIt}", cls.Index);
@@ -0,0 +1,220 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Panels;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>
/// Cronaca finale (12.3), a tutto schermo sopra la partita: storia della compagnia anno per anno
/// (patrimonio netto), primati, fatti salienti e prestigio, con «Continua come osservatore» e
/// «Nuova partita+». A partita in corso la stessa schermata è la Cronaca provvisoria.
/// Mostra solo ciò che manda il server (messaggio Chronicle).
/// </summary>
public partial class ChronicleScreen : Control
{
private readonly ClientWorld _world;
private readonly Chronicle _chronicle;
private readonly string _nextDifficulty;
/// <summary>Chiusura: continua come osservatore (o torna alla partita, se provvisoria).</summary>
public event Action? Closed;
/// <summary>Nuova partita+ con la difficoltà successiva.</summary>
public event Action? NewGamePlus;
public ChronicleScreen(ClientWorld world, Chronicle chronicle, string nextDifficulty)
{
_world = world;
_chronicle = chronicle;
_nextDifficulty = nextDifficulty;
}
public bool Final => _chronicle.GameOver;
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
MouseFilter = MouseFilterEnum.Stop;
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var margin = new MarginContainer();
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (string side in new[] { "left", "right" }) margin.AddThemeConstantOverride("margin_" + side, 48);
foreach (string side in new[] { "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 28);
AddChild(margin);
var root = PanelKit.Column(16);
margin.AddChild(root);
var c = _chronicle;
var header = PanelKit.Row(24);
var titles = PanelKit.Column(2);
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
titles.AddChild(UiTheme.TitleLabel(c.GameOver ? T("Cronaca finale") : T("Cronaca provvisoria"), 60));
int lastYear = c.History.Count > 0 ? c.History[^1].Year : c.FoundedYear;
titles.AddChild(UiTheme.Text($"{c.Company} · {c.FoundedYear}–{lastYear} · {Fmt.Date(_world, c.Day)}", 20, Palette.TextSecondary, bold: true));
header.AddChild(titles);
var prestige = new PanelContainer { SizeFlagsVertical = SizeFlags.ShrinkCenter };
prestige.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 18));
var prestigeCol = PanelKit.Column(0);
prestigeCol.AddChild(UiTheme.Text(T("Prestigio"), 14, Palette.AmberLight));
prestigeCol.AddChild(UiTheme.TitleLabel(Fmt.Number(c.Prestige, 0), 48, Palette.AmberLight));
prestige.AddChild(prestigeCol);
header.AddChild(prestige);
root.AddChild(header);
if (c.GameOver)
{
var reason = new PanelContainer();
reason.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 16));
var col = PanelKit.Column(2);
col.AddChild(UiTheme.Text(ReasonTitle(c.Reason) + (c.Winner >= 0 ? $" · {T("vincitore")}: {Fmt.Company(_world, c.Winner)}" : ""), 17, Palette.AmberLight, bold: true));
if (c.Text.Length > 0) col.AddChild(Wrapped(c.Text, 14, Palette.Text));
col.AddChild(Wrapped(T("Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi."), 13, Palette.TextSecondary));
reason.AddChild(col);
root.AddChild(reason);
}
else
{
root.AddChild(UiTheme.Notice(T("La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena.")));
}
var body = PanelKit.Row(20);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
root.AddChild(body);
// sinistra: grafico e tabella anno per anno
var left = Frame(body, 1.7f);
left.AddChild(UiTheme.Text(T("Patrimonio netto anno per anno"), 16, bold: true));
var chart = new SeriesChart(240);
chart.Show(c.History.Select(y => (double)y.NetWorth.Cents).ToList(), c.History.Select(y => $"{y.Year}").ToList(),
v => Core.Common.Money.FromCentsRounded(v).ToString("short"), SeriesChart.Style.Bars, Palette.Amber, T("Nessun anno registrato"));
left.AddChild(chart);
left.AddChild(YearTable(c.History));
// destra: primati e fatti salienti
var right = Frame(body, 1f);
right.AddChild(UiTheme.Text(T("Primati"), 16, bold: true));
var records = new GridContainer { Columns = 2, SizeFlagsHorizontal = SizeFlags.ExpandFill };
records.AddThemeConstantOverride("h_separation", 8);
records.AddThemeConstantOverride("v_separation", 8);
foreach (var r in c.Records)
{
var value = PanelKit.Value(r.Value);
value.ClipText = true;
value.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
var stat = PanelKit.Stat($"{r.Title} ({r.Year})", value);
stat.TooltipText = $"{r.Title}: {r.Value} ({r.Year})";
records.AddChild(stat);
}
right.AddChild(records);
right.AddChild(PanelKit.Separator());
right.AddChild(UiTheme.Text(T("Fatti salienti"), 16, bold: true));
if (c.Highlights.Count == 0) right.AddChild(UiTheme.Text(T("Ancora nessun fatto da raccontare."), 13, Palette.TextSecondary));
foreach (string h in c.Highlights) right.AddChild(Wrapped("• " + h, 13, Palette.Text));
// pulsanti
var buttons = PanelKit.Row(12);
buttons.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
if (c.GameOver)
{
var hint = UiTheme.Text($"{T("Nuova mappa con la difficoltà")} «{_nextDifficulty}»", 14, Palette.TextSecondary);
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
buttons.AddChild(hint);
var observe = new Button { Text = T("Continua come osservatore"), CustomMinimumSize = new Vector2(0, 48) };
observe.Pressed += () => Closed?.Invoke();
buttons.AddChild(observe);
var again = UiTheme.Primary(T("Nuova partita+"));
again.CustomMinimumSize = new Vector2(200, 48);
again.Pressed += () => NewGamePlus?.Invoke();
buttons.AddChild(again);
}
else
{
var back = UiTheme.Primary(T("Torna alla partita"));
back.CustomMinimumSize = new Vector2(200, 48);
back.Pressed += () => Closed?.Invoke();
buttons.AddChild(back);
}
root.AddChild(buttons);
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
{
Closed?.Invoke();
GetViewport().SetInputAsHandled();
}
}
private static VBoxContainer Frame(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 18));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 12);
scroll.AddChild(margin);
var col = PanelKit.Column(10);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
private static Control YearTable(List<CompanyYearInfo> history)
{
var grid = new GridContainer { Columns = 7, SizeFlagsHorizontal = SizeFlags.ExpandFill };
grid.AddThemeConstantOverride("h_separation", 18);
grid.AddThemeConstantOverride("v_separation", 4);
string[] heads = [T("Anno"), T("Patrimonio"), T("Cassa"), T("Ricavi"), T("Utile"), T("Treni"), T("Km di binari")];
for (int i = 0; i < heads.Length; i++)
{
var l = UiTheme.Text(heads[i], 12, Palette.TextSecondary);
l.HorizontalAlignment = i == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
l.SizeFlagsHorizontal = i == 0 ? SizeFlags.Fill : SizeFlags.ExpandFill;
grid.AddChild(l);
}
foreach (var y in Enumerable.Reverse(history).Take(12))
{
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
foreach (var (text, color) in new[]
{
(y.NetWorth.ToString("short"), Palette.Text),
(y.Cash.ToString("short"), Palette.Text),
(y.Revenue.ToString("short"), Palette.Text),
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Ok),
($"{y.Trains}", Palette.Text),
(Fmt.Number(y.TrackKm, 1), Palette.Text),
})
{
var l = UiTheme.Text(text, 13, color);
l.HorizontalAlignment = HorizontalAlignment.Right;
grid.AddChild(l);
}
}
return grid;
}
private static string ReasonTitle(byte reason) => reason switch
{
1 => T("Fallimento"),
2 => T("La compagnia è stata scalata"),
3 => T("Riscatto non riuscito in tempo"),
_ => T("Partita conclusa"),
};
private static Label Wrapped(string text, int size, Color color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://ck3hivvfy7bdr
@@ -21,7 +21,9 @@ public partial class ConnectScreen : Control
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
@@ -6,6 +6,7 @@ using ViaFerrea.Client.Net;
using ViaFerrea.Client.Panels;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
@@ -38,6 +39,18 @@ public partial class GameScreen : Node
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private MaintenancePanel? _maintenance;
private IndustryPanel? _industryPanel;
private CompaniesPanel? _companies;
// pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
private Control? _mapArea;
private Control? _side;
// Cronaca finale (o provvisoria) sopra tutta la partita e avviso dell'osservatore
private readonly CanvasLayer _overlay = new() { Layer = 3 };
private readonly PanelContainer _observer = new() { Visible = false };
private ChronicleScreen? _chronicleScreen;
private Protocol.Messages.Chronicle? _seenChronicle;
private bool _wantChronicle, _finalShown;
private bool _heatMap;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
@@ -81,6 +94,29 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
_industryPanel?.Select(industry);
}
/// <summary>Apre «Compagnie e borsa» a tutto schermo sulla compagnia indicata.</summary>
public void OpenCompanies(int company)
{
if (_tool != Tool.Companies) _toolbar.Select(Tool.Companies);
_companies?.Select(company);
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
_wantChronicle = true;
_session.Send(new RequestDetail { Kind = DetailKind.Chronicle, Target = 0 });
}
public bool ChronicleVisible => _chronicleScreen is not null;
/// <summary>Mappa di calore della condizione dei treni.</summary>
public void SetHeatMap(bool on)
{
@@ -112,6 +148,7 @@ public partial class GameScreen : Node
var hud = new CanvasLayer { Layer = 2 };
AddChild(hud);
var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
UiTheme.Apply(root);
root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
root.AddThemeConstantOverride("separation", 0);
hud.AddChild(root);
@@ -122,6 +159,7 @@ public partial class GameScreen : Node
middle.AddChild(_toolbar);
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;
@@ -131,11 +169,19 @@ public partial class GameScreen : Node
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
middle.AddChild(side);
_side = side;
_full.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AppBackground, Palette.Border, 0, 20));
middle.AddChild(_full);
BuildObserverBanner(mapArea);
var sideCol = new VBoxContainer();
sideCol.AddThemeConstantOverride("separation", 12);
side.AddChild(sideCol);
sideCol.AddChild(_scroll);
_scroll.AddChild(_content);
// margine destro: la barra di scorrimento non copre i valori allineati a destra
var contentMargin = new MarginContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
contentMargin.AddThemeConstantOverride("margin_right", 12);
_scroll.AddChild(contentMargin);
contentMargin.AddChild(_content);
var miniHeader = new HBoxContainer();
var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary);
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
@@ -146,6 +192,7 @@ public partial class GameScreen : Node
root.AddChild(_ticker);
BuildDisconnectedOverlay(hud);
AddChild(_overlay);
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
@@ -165,9 +212,37 @@ public partial class GameScreen : Node
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
/// <summary>Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata.</summary>
private void BuildObserverBanner(Control mapArea)
{
_observer.SetAnchorsPreset(Control.LayoutPreset.BottomWide);
_observer.OffsetLeft = 16;
_observer.OffsetRight = -16;
_observer.OffsetTop = -70;
_observer.OffsetBottom = -16;
_observer.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 8, 14));
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 14);
var text = UiTheme.Text(T("Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare."), 14, Palette.AmberLight, bold: true);
text.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
text.SizeFlagsVertical = Control.SizeFlags.ShrinkCenter;
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
row.AddChild(text);
var open = UiTheme.Primary(T("Cronaca finale"));
open.Pressed += () =>
{
if (_session.World.Chronicle is { } c) ShowChronicle(c);
else OpenChronicle();
};
row.AddChild(open);
_observer.AddChild(row);
mapArea.AddChild(_observer);
}
private void BuildDisconnectedOverlay(CanvasLayer hud)
{
_disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect);
UiTheme.Apply(_disconnected);
_disconnected.Visible = false;
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) };
shade.SetAnchorsPreset(Control.LayoutPreset.FullRect);
@@ -202,7 +277,12 @@ public partial class GameScreen : Node
// nuova partita o caricamento: si ricomincia dalla copia locale vuota
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
CloseChronicle();
_seenChronicle = null;
_wantChronicle = _finalShown = false;
_toolbar.Select(Tool.None);
SendViewport(force: true);
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
break;
case DailyDigest d:
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
@@ -214,6 +294,7 @@ public partial class GameScreen : Node
{
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
UpdateChronicle();
SendViewport(force: false);
_sincePreview += delta;
if (_previewDirty && _sincePreview > 0.12)
@@ -282,6 +363,13 @@ public partial class GameScreen : Node
_linesPanel = null;
_info = null;
_maintenance = null;
_industryPanel = null;
_companies = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool == Tool.Companies;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
Control panel;
switch (tool)
{
@@ -331,6 +419,16 @@ public partial class GameScreen : Node
case Tool.Employment:
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
_companies.CloseRequested += () => _toolbar.Select(Tool.None);
_companies.ChronicleRequested += OpenChronicle;
_full.AddChild(_companies);
panel = NewInfoPanel();
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
@@ -338,14 +436,21 @@ public partial class GameScreen : Node
panel = new FinancePanel(_session);
break;
default:
panel = _info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
panel = NewInfoPanel();
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_content.AddChild(panel);
}
private InfoPanel NewInfoPanel()
{
_info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
_info.IndustryRequested += OpenIndustry;
return _info;
}
private void OnMapHovered(Vector2 world)
{
_mouse = world;
@@ -394,6 +499,9 @@ public partial class GameScreen : Node
case Tool.Lines when _linesPanel is not null:
if (NearestStation(world) is { } station) _linesPanel.AddStop(station);
break;
case Tool.Industries when _industryPanel is not null:
if (IndustryAt(world) is { } industry) _industryPanel.Select(industry);
break;
default:
SelectAt(world);
break;
@@ -568,13 +676,10 @@ public partial class GameScreen : Node
_map.Entities.SelectedStation = -1;
_map.Entities.QueueRedraw();
double cs = w.Summary?.CellSizeM ?? 100;
foreach (var ind in w.Industries.Values)
if (IndustryAt(world) is { } industry)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6))
{
_info.Select(InfoPanel.Kind.Industry, ind.Id);
return;
}
_info.Select(InfoPanel.Kind.Industry, industry);
return;
}
foreach (var town in w.Towns.Values)
{
@@ -587,6 +692,72 @@ public partial class GameScreen : Node
_info.Select(InfoPanel.Kind.None, -1);
}
private int? IndustryAt(Vector2 world)
{
double cs = _session.World.Summary?.CellSizeM ?? 100;
foreach (var ind in _session.World.Industries.Values)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6)) return ind.Id;
}
return null;
}
// ------------------------------------------------------------------ Cronaca finale e osservatore
/// <summary>Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore.</summary>
private void UpdateChronicle()
{
var chronicle = _session.World.Chronicle;
if (!ReferenceEquals(chronicle, _seenChronicle))
{
_seenChronicle = chronicle;
if (chronicle is not null && ((chronicle.GameOver && !_finalShown) || _wantChronicle))
{
_wantChronicle = false;
if (chronicle.GameOver) _finalShown = true;
ShowChronicle(chronicle);
}
}
_observer.Visible = chronicle?.GameOver == true && _chronicleScreen is null;
}
private void ShowChronicle(Protocol.Messages.Chronicle chronicle)
{
CloseChronicle();
var next = NextDifficulty();
string name = TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt;
var screen = new ChronicleScreen(_session.World, chronicle, name);
screen.Closed += CloseChronicle;
screen.NewGamePlus += StartNewGamePlus;
_overlay.AddChild(screen);
_chronicleScreen = screen;
}
private void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
}
/// <summary>Difficoltà successiva a quella della partita (l'ultima resta l'ultima).</summary>
private DifficultyDef NextDifficulty()
{
var file = _session.World.Data.Difficulty;
int i = file.Presets.FindIndex(p => p.Id == _session.Difficulty);
if (i < 0) i = file.Presets.FindIndex(p => p.Id == file.Default);
return file.Presets[Math.Clamp(i + 1, 0, file.Presets.Count - 1)];
}
/// <summary>Nuova partita+: mappa nuova (seme successivo, stessa dimensione) con la difficoltà superiore.</summary>
private void StartNewGamePlus()
{
var summary = _session.World.Summary;
var next = NextDifficulty();
_session.Send(new NewGame { Seed = (summary?.Seed ?? 0) + 1, SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = next.Id });
CloseChronicle();
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private void Toast(string text, bool error = false)
{
@@ -14,7 +14,9 @@ public partial class MenuScreen : Control
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
+45 -3
View File
@@ -7,13 +7,55 @@
"maxProjectsPerMonth": 2,
"candidateMaxDistanceKm": 40,
"candidateMinDistanceKm": 4,
"pathSlopePenalty": 40,
"pathSlopePenalty": 120,
"pathWaterPenalty": 8,
"trainsPerLine": 2,
"steepPenalty": 25,
"steepGradeFactor": 1.6,
"pathMarginRetryKm": 20,
"trainsPerLine": 1,
"wagonsPerTrain": 5,
"cashReserveMonths": 3,
"revenueHorizonYears": 10,
"maxRejectedShare": 0.05
"maxRejectedShare": 0.05,
"maxConcurrentProjects": 2,
"evaluateTop": 6,
"pathMarginKm": 8,
"simplifyToleranceM": 120,
"stationOffsetsM": [ 300, 550, 850, 1250 ],
"depotOffsetM": 450,
"platforms": 3,
"hubPlatforms": 6,
"assumedEfficiency": 0.6,
"speedFactor": 0.55,
"dwellMinutes": 6,
"maintenanceCostShare": 0.2,
"trackUpkeepPerKmPerYear": 30000,
"maxTrainsPerLine": 2,
"addTrainWaitingTrips": 2.0,
"minCommuters": 20,
"commuterCoverage": 0.6,
"hubShare": 0.25,
"noPartsFactor": 0.5,
"townBonus": 1.8,
"townRoiFactor": 0.5,
"repayCashMonths": 12,
"planningDaySpacing": 7,
"failedMemory": 64
},
"market": {
"founderAcceptPremium": 0.4,
"holderAcceptPremium": 0.15,
"predatoryStakeTarget": 0.3,
"sharesCashShare": 0.1,
"bidMinStake": 0.25,
"bidPremium": 0.3,
"bidCashMultiple": 1.2,
"buybackCashShare": 0.5,
"knightCashMultiple": 2.0,
"issueFloatMax": 0.5,
"issueShare": 0.1,
"industryMaxCashShare": 0.25,
"industryMinMargin": 0.1
},
"personalities": [
{ "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
+31 -4
View File
@@ -117,11 +117,11 @@
"border": { "name_it": "Valico", "monthlyCapacity": 1500, "duty": 0.12, "footprint": "small" }
},
"tariffs": {
"freightBaseRate": 150,
"freightBaseRate": 360,
"freightFixedWeight": 0.6,
"freightPriceWeight": 0.4,
"freightKmExponent": 0.9,
"paxBaseFare": 45,
"paxBaseFare": 75,
"paxKmExponent": 0.85,
"classMultipliers": { "worker": 1.0, "staff": 3.0 },
"lateThreshold": 1.5,
@@ -152,7 +152,27 @@
"bidPremiumMax": 0.5,
"bidDurationDays": 90,
"ransomShare": 0.51,
"receivershipDividend": 0.5
"receivershipDividend": 0.5,
"sentimentEarningsWeight": 0.4,
"sentimentCycleWeight": 1.0,
"sentimentDividendWeight": 4.0,
"sentimentSmoothingDays": 30,
"extraDividendSentimentBoost": 0.15,
"extraDividendDecayDays": 120,
"aiFloatAtStart": 0.3,
"tenderDailyShare": 0.04,
"extraDividendCashShare": 0.25,
"whiteKnightPremium": 0.05,
"ransomPremium": 0.25,
"maxDailyTradeShare": 0.05,
"secondaryMaxFloat": 0.6,
"priceHistoryMonths": 120,
"auctionDays": 30,
"auctionMinBookShare": 0.4,
"concentrationThreshold": 0.6,
"newCompetitorCooldownYears": 3,
"maxCompanies": 8,
"historyYears": 300
},
"industryMaintenance": {
"wearPerDay": 0.06,
@@ -181,6 +201,13 @@
"npcUpgradeMargin": 0.15,
"npcUpgradeYears": 2,
"npcHighMargin": 0.15,
"npcOverhaulBelow": 35
"npcOverhaulBelow": 35,
"partsTargetMonths": 3,
"initialPartsMonths": 6,
"maxOrderedParts": 200,
"townEffectRadiusKm": 12,
"stopHistoryLength": 12,
"ownerCashReserve": 2000000,
"purchase": { "assetShare": 0.6, "earningsMultiple": 5, "conditionWeight": 0.5 }
}
}
+5 -5
View File
@@ -23,7 +23,7 @@
],
"curveSpeedFactor": 0.65,
"costs": {
"basePerMeter": 1200,
"basePerMeter": 700,
"natural": 1.0,
"embankmentPerM": 0.25,
"cuttingPerM": 0.35,
@@ -34,9 +34,9 @@
"land": { "basePerCell": 20000, "nearTownKm": 2.0, "nearTownMultiplier": 3.0, "fieldMultiplier": 2.0 },
"doubleTrackMultiplier": 1.8,
"electrificationExtra": 0.35,
"stationBase": 4000000,
"stationPerPlatform": 1500000,
"depotBySize": { "small": 6000000, "medium": 12000000, "large": 24000000 },
"stationBase": 1200000,
"stationPerPlatform": 400000,
"depotBySize": { "small": 2000000, "medium": 4000000, "large": 8000000 },
"demolitionRefund": 0.1
},
"crews": {
@@ -56,7 +56,7 @@
"gradientWeight": 8,
"speedWeight": 0.4,
"maintenanceDriftPerDay": 0.02,
"maintenanceCostPerKmPerDay": 400,
"maintenanceCostPerKmPerDay": 60,
"limitBelow60": 0.6,
"limitBelow30": 0.3,
"failureChanceBelow30": 0.002,
+7 -7
View File
@@ -50,12 +50,12 @@
"comfortMax": 1.05
},
"interventions": [
{ "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.005, "spareParts": 0, "effect": "inspection" },
{ "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.03, "spareParts": 1, "effect": "service" },
{ "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.25, "spareParts": 5, "effect": "overhaul" },
{ "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.05, "spareParts": 1, "effect": "repair", "restoreTo": 80 },
{ "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.15, "spareParts": 3, "effect": "repair", "restoreTo": 90 },
{ "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.40, "spareParts": 8, "effect": "replace" }
{ "id": "inspection", "name_it": "Ispezione", "days": 1, "costShare": 0.001, "spareParts": 0, "effect": "inspection" },
{ "id": "service", "name_it": "Tagliando", "days": 3, "costShare": 0.012, "spareParts": 1, "effect": "service" },
{ "id": "overhaul", "name_it": "Revisione generale", "days": 20, "costShare": 0.12, "spareParts": 5, "effect": "overhaul" },
{ "id": "repair_minor", "name_it": "Riparazione dopo guasto lieve", "days": 2, "costShare": 0.03, "spareParts": 1, "effect": "repair", "restoreTo": 80 },
{ "id": "repair_major", "name_it": "Riparazione dopo guasto grave", "days": 7, "costShare": 0.08, "spareParts": 3, "effect": "repair", "restoreTo": 90 },
{ "id": "repair_catastrophic", "name_it": "Ricostruzione dopo deragliamento", "days": 30, "costShare": 0.3, "spareParts": 8, "effect": "replace" }
],
"inspection": { "brakesTo": 100, "othersPlus": 10, "hazardFactor": 0.5, "hazardDays": 30 },
"service": { "plus": 40 },
@@ -64,7 +64,7 @@
"stallsBySize": { "small": 2, "medium": 4, "large": 8 },
"staffPerStall": 4,
"slowdownAtHalfStaff": 2.0,
"initialSpareParts": 10,
"initialSpareParts": 25,
"jobsWorkersPerStall": 6,
"targetSpareParts": 40,
"maxSpareParts": 400
+12 -1
View File
@@ -90,6 +90,16 @@
"pattern": "^#[0-9a-fA-F]{6}$"
},
"minItems": 1
},
"market": {
"type": "object",
"additionalProperties": {
"type": [
"number",
"integer",
"boolean"
]
}
}
},
"required": [
@@ -97,7 +107,8 @@
"planning",
"personalities",
"companyNames",
"colors"
"colors",
"market"
],
"additionalProperties": false
}
+4 -4
View File
@@ -7,16 +7,16 @@
"requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" },
"unlocks": { "maxLoanFactor": 1.0, "crews": 2, "trading": false, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } },
{ "level": 2, "name_it": "Compagnia regionale", "name_en": "Regional company",
"requirements": { "netWorth": 100000000, "connectedTownsOver": { "count": 3, "population": 1000 }, "creditRating": "BB" },
"requirements": { "netWorth": 40000000, "connectedTownsOver": { "count": 2, "population": 800 }, "creditRating": "BB" },
"unlocks": { "maxLoanFactor": 2.0, "crews": 4, "trading": true, "buyIndustry": false, "ipo": false, "hostileTakeover": false, "concessions": false } },
{ "level": 3, "name_it": "Compagnia nazionale", "name_en": "National company",
"requirements": { "netWorth": 500000000, "connectedTownsOver": { "count": 8, "population": 2000 }, "creditRating": "BBB" },
"requirements": { "netWorth": 100000000, "connectedTownsOver": { "count": 3, "population": 1000 }, "creditRating": "BBB" },
"unlocks": { "maxLoanFactor": 4.0, "crews": 8, "trading": true, "buyIndustry": true, "ipo": false, "hostileTakeover": false, "concessions": true } },
{ "level": 4, "name_it": "Grande compagnia", "name_en": "Major company",
"requirements": { "netWorth": 2000000000, "connectedTownsOver": { "count": 15, "population": 3000 }, "creditRating": "A" },
"requirements": { "netWorth": 400000000, "connectedTownsOver": { "count": 6, "population": 2000 }, "creditRating": "A" },
"unlocks": { "maxLoanFactor": 8.0, "crews": 12, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": false, "concessions": true } },
{ "level": 5, "name_it": "Impero ferroviario", "name_en": "Railway empire",
"requirements": { "netWorth": 8000000000, "connectedTownsOver": { "count": 25, "population": 5000 }, "creditRating": "AA" },
"requirements": { "netWorth": 1500000000, "connectedTownsOver": { "count": 10, "population": 3500 }, "creditRating": "AA" },
"unlocks": { "maxLoanFactor": 16.0, "crews": 20, "trading": true, "buyIndustry": true, "ipo": true, "hostileTakeover": true, "concessions": true } }
]
}
+9 -5
View File
@@ -30,7 +30,7 @@ Regole:
| `ViaFerrea.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. |
| `ViaFerrea.Core.Rail` | `TrackGeometry` (raccordi), `TrackPlanner` (profilo a 25 m, opere, costi, tempi, vincoli per era), `RailNetwork` (nodi, archi campionati, stazioni, depositi, cantieri, indice spaziale), `Pathfinder` (A* sugli archi orientati), veicoli, treni, linee, pacchetti, `LineGraph` con maschere dei carichi (ADR 0007, 0008). |
| `ViaFerrea.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. |
| `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor`, eventi in uscita. |
| `ViaFerrea.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita. |
| `ViaFerrea.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. |
## 3. Il tick
@@ -43,7 +43,7 @@ Clock → Commands → Construction → Trains → Signals → Stations → Main
→ Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero)
```
Sistemi implementati (F1–F4), nella loro posizione:
Sistemi implementati (F1–F5), nella loro posizione:
| Sistema | Frequenza | Cosa fa |
|---|---|---|
@@ -56,16 +56,19 @@ Sistemi implementati (F1–F4), nella loro posizione:
| `FleetMaintenanceSystem` | giorno | usura per componente in km di servizio, rischio e guasti (lieve, grave con soccorso, deragliamento), pianificatore predittivo e prenotazioni, officine con stalli, ricambi e personale, riserve, avvisi (posto di «Maintenance», ADR 0010); formule senza stato in `Fleet` |
| `DemandSystem` | giorno | domanda delle città (con elasticità) e input richiesti dalle industrie |
| `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi e su rotaia per industrie e depositi (`IWorkplace`, abbinamento mensile sul `LineGraph`), motivi dei posti scoperti, convenzioni, pacchetti giornalieri dei pendolari, presenze e coperture (posto di «Commuting», ADR 0008 e 0010) |
| `IndustrySystem` | giorno/trimestre/anno | produzione, esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite |
| `IndustrySystem` | giorno/trimestre/anno | produzione (nulla durante i fermi), esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite |
| `IndustryMaintenanceSystem` | giorno/mese | condizione degli impianti (usura con l'utilizzo, recupero del budget), consumo di ricambi, fermi e incidenti, revisioni e ammodernamenti in attesa di macchinari, scelte dei proprietari privati, conguaglio con il proprietario (ADR 0011) |
| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato |
| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta |
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, chiusura dei conti |
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
| `StockMarketSystem` | giorno/mese/anno | prezzi e sentiment, valore delle partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate, amministrazione controllata del giocatore, fallimenti e aste, storico annuale, nuovi concorrenti (ADR 0012) |
| `AiSystem` | giorno/mese | agenti delle compagnie IA: progetti, stalli, offerte; una volta al mese (giorno diverso per IA) finanza, treni aggiuntivi, borsa, industrie, linee dei ricambi e nuovi progetti, tutto con i comandi (ADR 0013) |
| `HashSystem` | giorno | hash dello stato dinamico |
- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`.
- `SystemPipeline.Profile` misura tempo e allocazioni per sistema (usato da `bench`).
- `WorldContext` espone il mondo, i dati e il calendario; gli eventi in uscita (notifiche, notizie) vanno in `World.Events`, che il server svuota.
- I comandi arrivano in una coda; il server la riempie dai socket, le IA dal proprio sistema; il sistema `Commands` la drena a inizio tick. Per il replay si registrano `(tick, comando)` in `World.CommandLog`.
- I comandi arrivano in una coda; il server la riempie dai socket e il sistema `Commands` la drena a inizio tick. Le IA eseguono i loro comandi direttamente con `CommandProcessor` dal sistema `AiAgents` (stesse validazioni, esito immediato, numeri di sequenza ≥ 0x80000000, non registrati per il replay: le IA si rigiocano da sole). Per il replay si registrano `(tick, comando)` in `World.CommandLog`.
- I flussi pseudo-casuali dei sottosistemi si ottengono con `World.Stream(nome)` (derivati dalla radice con `Rng.Fork`, salvati per nome).
## 4. Determinismo
@@ -98,6 +101,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
- Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero.
- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006.
- Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010).
- Corpo versione 3 (F5): `CorporateSerializer` aggiunge manutenzione e proprietà delle industrie, libro dei soci, prezzi, controllo e storico delle compagnie, offerte, aste, fine partita e stato degli agenti IA (progetti, candidati scartati); i salvataggi precedenti si migrano (ADR 0012).
## 8. Server
+22 -10
View File
@@ -77,7 +77,7 @@ costMultiplier: f64 }`
| 7 | Save | `name: string` |
| 8 | Load | `saveId: string` |
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi), `target: i32` (id del treno o del deposito; ignorato per 3). Aggiunto in F4 |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3 e 6). Aggiunto in F4 |
### Comandi (`Command.type`, payload in ordine)
@@ -100,7 +100,7 @@ costMultiplier: f64 }`
| 15 | SetReserve | `train: i32`, `reserve: bool` |
| 16 | SetMaintenancePolicy | `scope: u8` (0 compagnia, 1 linea, 2 treno), `target: i32`, `policy: string` |
| 17 | ScheduleService | `train: i32`, `intervention: string` |
| 18 | OrderParts | `depot: i32`, `quantity: i32` |
| 18 | OrderParts | `depot: i32`, `quantity: i32`; blocco 1 (F5): `industry: i32` (ricambi ordinati per un'industria posseduta, oltre la scorta della politica) |
| 19 | TakeLoan | `amount: Money` |
| 20 | RepayLoan | `loan: i32`, `amount: Money` |
| 21 | AcceptAgreement | `agreement: i32` |
@@ -116,18 +116,20 @@ costMultiplier: f64 }`
| 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` |
| 32 | PayDividend | `perShare: Money` |
| 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` |
| 34 | RespondBid | `bid: i32`, `accept: bool` |
| 34 | RespondBid | `bid: i32`, `accept: bool`; blocco 1 (F5): `defense: u8` (0 nessuna, 1 riacquisto, 2 dividendo straordinario, 3 cavaliere bianco), `knight: i32` |
| 35 | BuyConcession | `region: i32` |
| 36 | AcceptContract | `contract: i32` |
| 37 | FundResearch | `project: string`, `amount: Money` |
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
| 39 | MergeCompany | `subsidiary: i32` — fusione di una controllata dopo 360 giorni di controllo (aggiunto in F5) |
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi
(`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o
treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata
del deposito). Fino alla loro fase i comandi 23–38 (tranne 26) rispondono `NotImplemented`. Il server
imposta l'emittente in base alla sessione.
del deposito). Dalla F5 sono attivi anche 25–34 e 39 (industrie, borsa, offerte, fusioni; `LaunchBid` su
una compagnia fallita è un'offerta all'asta degli attivi: prezzo per azione × azioni). Fino alla loro fase i
comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
## 5. Messaggi Server → Client
@@ -147,6 +149,9 @@ imposta l'emittente in base alla sessione.
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
| 124 | MaintenanceCard | `train, day: i64, condition: f32, status: u8, policy: u8, policyOverride: u8, reserve, failure: u8, failedVehicle, failedComponent: string, rescueHours: f32, nextIntervention: string, nextDueDays: f32, plannedIntervention: string, maintenanceDepot, serviceKmPerDay: f32, costThisYear: Money, costLastYear: Money, failuresThisYear, failuresTotal, coveredBy, covering, vehicles: [VehicleCard], history: [MaintenanceRecordInfo]` (su richiesta, F4) |
| 125 | WorkshopRegister | `depot, day: i64, stalls, jobsStaff, staffPresent: f32, workRate: f32, spareParts, partsTarget, partsReserved, jobs: [WorkshopJobInfo], booked: [WorkshopJobInfo]` (su richiesta, F4) |
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
| 131 | Notification | `EventInfo` |
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
@@ -155,9 +160,11 @@ imposta l'emittente in base alla sessione.
Record (ognuno chiude con `flags`):
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata)
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata);
blocco 2 (F5): `personality: string, listed, sharePriceCents: f64, sentiment: f32, founderShare: f32, controlledBy: i32, merged, receivership, receivershipUntilDay: i64, annualProfit: Money`
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`;
blocco 1 (F5): `budget: u8 (0 nessuno, 1 base, 2 alto), spareParts, machinery, stoppedUntilDay: i64, stopKind: u8 (1 guasto, 2 incidente, 3 revisione, 4 ammodernamento), pendingWork: u8 (1 revisione, 2 ammodernamento), partsShort: bool`
- `HubInfo { id, kind: string, name, position }`
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
@@ -178,7 +185,10 @@ Record (ognuno chiude con `flags`):
- `VehicleCard { vehicle, type: string, odometerKm: f32, ageYears: f32, ageFactor: f32, components: [ComponentCard { component: string, condition: f32, wearPerDay: f32 }] }`
- `MaintenanceRecordInfo { day: i64, intervention: string, cost: Money, depot, parts }`
- `WorkshopJobInfo { train, intervention: string, inStall, started, progress: f32, days: f32, parts, queuedDay: i64 }`
- `SharePrice { company, price: Money, change: f32, listed }`, `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`
- `SharePrice { company, price: Money, change: f32, listed }`; blocco 1 (F5): `priceCents: f64, outstanding: i64, freeFloat: i64, founderShare: f32, controlledBy: i32`
- `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`; blocco 1 (F5): `state: u8, committedShare: f64, defenses: u8 (bit per difesa usata), knight: i32, accepted: bool` (la compagnia della sessione ha aderito)
- `HoldingInfo { holder: i32 (−1 fondatore, −2 mercato, altrimenti compagnia), shares: i64 }`, `CompanyYearInfo { year, netWorth, cash, revenue, profit: Money, tier: u8, trains, trackKm: f32, sharePrice: Money }`
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
## 6. Flusso e interest management
@@ -190,13 +200,15 @@ Record (ognuno chiude con `flags`):
- `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
- `DailyDigest` a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
- `DailyDigest` e `MarketTape` (listino delle compagnie attive e offerte in corso) a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
informativi della compagnia della sessione; `MaintenanceAlert` quando un treno scende sotto le soglie
d'avviso (40) o critica (30) e quando un'officina resta senza ricambi.
- Dettagli su richiesta (F4): `MaintenanceCard`, `WorkshopRegister` ed `EmploymentReport` rispondono a
`RequestDetail` per entità della compagnia della sessione (le richieste per entità altrui o
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità.
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. Dalla F5 anche
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce.
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
sessione si chiude (il client può riprenderla).
- Obiettivo di banda in regime: < 100 KB/s per client.
+22 -4
View File
@@ -68,13 +68,27 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- Accettazione F4 (rete di Valdoria con officina a Valdoria e due treni per linea): senza la linea dei ricambi la flotta scende sotto 40 al giorno 697 con 12 guasti (19,5 per milione di km di servizio); con la linea dal Porto di Levante resta sopra 73 con 3 guasti (3,2 per milione di km).
- 102 test.
### F5 — Industrie, IA, borsa e scalate
- Manutenzione degli impianti (sezione 11, ADR 0011): usura giornaliera con efficienza, intensità e difficoltà, recupero dal budget (dimezzato senza ricambi), fermi sotto 40 con storico e insoddisfazione della città vicina, incidenti gravi sotto 10 per trasformazione e manifattura, revisione e ammodernamento programmabili; ricambi e macchinari come domanda esplicita dell'industria (in treno, dal trasporto locale e per trasbordo nel bacino di una stazione servita); politica dei privati.
- Industrie possedute: `BuyIndustry` dal livello 3 con prezzo chiesto (attivi, condizione, utile, cassa), cassa di riserva, surplus e perdite al proprietario (voce «Industrie»), `SetIndustryPolicy`, `OverhaulIndustry`, `UpgradeIndustry` e `OrderParts` per l'industria.
- Livelli (`Tiers`): patrimonio netto, città collegate sopra una soglia di abitanti e rating, soglie ritarate in `tiers.json`; ritaratura economica di costi di costruzione, manutenzione e tariffe misurata con le IA (ADR 0011 §7).
- Borsa e società (sezione 12.2–12.3, ADR 0012): libro dei soci, prezzo da patrimonio e utili con sentiment ciclico, ordini con spread e limite, quotazione dal livello 4, aumento di capitale, riacquisto, dividendi ordinari e straordinari, controllo oltre il 50 % con quota dell'utile al controllante, fusione (`MergeCompany`, comando 39), offerte pubbliche condizionate con adesione del flottante, risposte delle compagnie azioniste e tre difese, esiti per difficoltà (amministrazione controllata, fine partita), aste degli attivi delle IA fallite, nuovi concorrenti quando una compagnia domina i ricavi, `GameOver` con osservatore e Cronaca finale con prestigio.
- Agenti IA (sezione 12.1, ADR 0013): pianificazione mensile con candidati (merci e pendolari), regioni collegabili, Dijkstra a 8 direzioni con pendenze, fiumi e ostacoli, semplificazione che non taglia ostacoli, `TrackPreview`, ROI con soglia della personalità; esecuzione con gli stessi comandi del giocatore (stazioni, binario, deposito, linea, treni), treni aggiuntivi, linee dei ricambi, rimedio agli stalli di capacità, liquidità, rimborso dei prestiti, borsa (partecipazioni, offerte, adesioni, difese, fusioni); tre personalità (Espansiva, Prudente, Predatoria). `viaferrea-tools simulate --trace-ai` con riepilogo per compagnia.
- Salvataggio: corpo versione 3 con sezione societaria (libro dei soci, storici, offerte, aste, stato degli agenti, fine partita) nell'hash; migrazione dei salvataggi F4.
- Protocollo: prezzi e offerte nei record (blocco 1), `CompanyCard` (126), `IndustryCard` (127), `Chronicle` (128), `RequestDetail` per compagnia, industria e cronaca, `MergeCompany` e campi nuovi di `OrderParts` e `RespondBid` (blocco 1 dei comandi).
- Server: listino quotidiano, schede di compagnia e industria su richiesta, Cronaca una volta per sessione a fine partita.
- Client: pannelli «Borsa» (listino, offerte, schede delle compagnie con soci e storico, comandi di compravendita, quotazione, offerte e difese) e scheda del proprietario dell'industria (condizione, fermi, budget, revisione, ammodernamento, acquisto), Cronaca finale; schermate in `docs/screenshots/f5-*.jpg`.
- Test di 14.5: manutenzione delle industrie (usura, fermi, ricambi, revisione, acquisto), borsa (prezzo, quotazione, controllo e fusione, scalata riuscita, esiti per difficoltà, asta dell'IA fallita, salvataggio dello stato societario), IA (comandi rifiutati ≤ 5 %, IA con capitale ×2 sopra il giocatore passivo in 10 anni, determinismo con le IA anche passando da un salvataggio).
- Accettazione F5 (`OnMagnateAnAiReachesTierThreeIn15Years`, seme 7, 128 km, «Magnate», giocatore passivo): la Società Ferroviaria Adriatica arriva al livello 3 nel 1863 (13 anni) con ₤ 2,7 milioni di patrimonio, rating BBB e 3 città sopra 1.000 abitanti collegate.
- 120 test.
## In corso
- Nessun lavoro a metà: F4 chiusa.
- Nessun lavoro a metà: F5 chiusa.
## Prossimo passo
- F5: manutenzione delle industrie (sezione 11: condizione degli impianti, fermi, ammodernamenti, acquisto delle industrie con il pannello del proprietario), poi agenti IA, borsa, quotazione e scalate (sezione 12) con i test di 14.5 e il determinismo con le IA.
- F6: hub e commercio (`BuyGoods`/`SellGoods`), eventi, storico dei prezzi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 06–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`, esportazione Windows con il server.
## Limiti noti
@@ -86,10 +100,12 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
- Comandi ancora `NotImplemented`: commercio, industrie, borsa, concessioni, contratti, ricerca, regioni (fasi F5–F7).
- Comandi ancora `NotImplemented`: commercio, concessioni, contratti, ricerca, regioni (fasi F6–F7).
- Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata.
- Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza.
- La manutenzione degli impianti (sezione 11) arriva in F5: fino ad allora la condizione delle industrie resta 100.
- IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3 e non usano il commercio (F6).
- Borsa (ADR 0012): per le compagnie piccole il prezzo per azione è di pochi centesimi e il premio di un'offerta ha la granularità di un centesimo; antitrust e finanziamenti statali arrivano in F7.
- Prezzi, soglie dei livelli e taratura economica restano provvisori fino al bilanciamento della F6.
## Misure di prestazione
@@ -112,3 +128,5 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
| Accettazione F4 (due corse di 3 anni, 6–7 treni) | 3,7 s | F4 |
| Suite di test (102, parallela su 4 core) | ~15 s | F4 |
| Pilota automatico del client con i pannelli F4 | ~90 s, 12 schermate | F4 |
| Suite di test (120, parallela su 4 core, con i test lenti delle IA) | ~137 s (accettazione F5 70 s) | F5 |
| `simulate --years 15` su 128 km «Magnate» con 3 IA | ~60 s | F5 |
@@ -0,0 +1,62 @@
# ADR 0011 — Manutenzione delle industrie, industrie possedute, livelli e ritaratura economica (F5)
Stato: accettato (F5).
## Contesto
La sezione 11 fissa usura, moltiplicatore di efficienza, rischio di fermo, budget, revisione e
ammodernamento, ma non dice come i ricambi e i macchinari arrivano alle industrie, come si paga
un'industria, come si riparte la cassa tra industria e proprietario, quando un livello della
compagnia si raggiunge né quali sono le soglie. Inoltre, con i costi di F1–F2, una linea nuova non
ripagava il capitale: le IA della F5 (che usano gli stessi comandi del giocatore) fallivano tutte.
## Decisione
1. **Usura e recupero** (`IndustryMaintenanceSystem`, dopo `Industries`): ogni giorno
`c −= 0,06 × efficienza × wearIntensity × usura della difficoltà` e `c += recupero del budget`
(dimezzato se l'ultimo consumo mensile di ricambi non era coperto). L'efficienza del giorno è
l'utilizzo. Il costo del budget è la quota dei ricavi medi giornalieri (EMA a 90 giorni) e
entra nei costi dell'industria (margine).
2. **Fermi**: sotto 40 il rischio giornaliero è `0,001·exp((40 − c)/8)`; il fermo dura 5–20 giorni,
è annotato nello storico (ultimi 12) e toglie 2 punti di soddisfazione a ogni categoria della città
più vicina entro 12 km. Sotto 10, per le industrie di trasformazione e manifattura (non primarie),
è un incidente grave: 60 giorni e −0,2 % di abitanti alla città vicina. Durante un fermo l'industria
non produce né consuma e non si usura; i salari si pagano comunque.
3. **Ricambi e macchinari** sono una domanda esplicita dell'industria: scorta desiderata = consumo
mensile della politica × 3 mesi + quanto ordinato con «Ordina ricambi» (`OrderParts` con il campo
`Industry`, blocco 1 del protocollo); macchinari = quelli richiesti dal lavoro programmato. Arrivano:
in treno (le industrie sono consumatori di questi beni come gli input), dal trasporto locale di
produttori e hub vicini (3 km) e, novità, per **trasbordo nel bacino**: una stazione servita da una
linea passa ricambi e macchinari dai produttori e dagli hub del suo bacino alle officine e alle
industrie dello stesso bacino, senza treno. Le industrie partono con 6 mesi di ricambi.
4. **Revisione e ammodernamento** si programmano (comando o privati) e partono quando ci sono i
macchinari (e, per la revisione, il personale ≥ 0,8); l'ammodernamento si paga all'inizio
(`upgradeCost × livello`, dal proprietario). I privati: budget dal margine (> 15 % Alto, < 0 nessuno),
revisione sotto 35 se la cassa paga i macchinari, ammodernamento dopo due anni di margine > 15 % con
ricambi in scorta.
5. **Acquisto** (`BuyIndustry`, dal livello 3): il prezzo chiesto è
`upgradeCost × livello × 0,6 × (0,5 + 0,5·c/100) + 5 × utile annuo positivo + cassa dell'impresa`;
un'offerta più bassa è rifiutata. L'industria tiene una cassa di riserva (20.000 lire): ogni mese il
surplus va al proprietario e le perdite sono coperte da lui (voce «Industrie» del conto economico,
che entra nell'utile operativo).
6. **Livelli** (`Tiers`, ogni mese dopo il rating): si sale quando patrimonio netto, città collegate
sopra una popolazione (nel bacino di una stazione fermata di una linea con treni) e rating
raggiungono il livello successivo; non si scende. Soglie in `tiers.json` ritarate perché una
compagnia competente arrivi al livello 3 in 10–15 anni: 400.000, 1.000.000, 4.000.000 e 15.000.000
lire; 2, 3, 6 e 10 città sopra 800, 1.000, 2.000 e 3.500 abitanti; BB, BBB, A, AA. Misura con le IA in
«Magnate» su mappe da 128 km: la migliore arriva a 1–2,7 milioni in 15 anni collegando 2–3 città.
7. **Ritaratura economica** (misurata con le IA su `simulate`, rifinitura in F6): binario 7 lire al metro
(era 12), stazione 12.000 + 4.000 lire per binario (era 40.000 + 15.000), depositi 20/40/80 mila lire;
manutenzione ordinaria del binario 0,6 lire al km al giorno (era 4); tariffa merci base 2,8 (era 1,5) e
passeggeri 0,6 (era 0,45) centesimi; costi degli interventi di manutenzione dei treni ridotti
(ispezione 0,1 %, tagliando 1,2 %, revisione 12 % del prezzo); ricambi a 150 lire la cassa (erano 300);
scorta iniziale dei depositi 25 casse.
## Conseguenze
- Chi trasporta ricambi e macchinari tiene in vita il territorio: un'industria lontana da produttori e
hub e non servita decade lentamente; le reti vicine a un porto o a una fabbrica di macchinari partono
avvantaggiate.
- L'accettazione F4 resta valida con la nuova taratura (senza linea dei ricambi la flotta scende sotto 40
entro 3 anni, con la linea resta sopra 60).
- I prezzi e le soglie restano provvisori fino al bilanciamento della F6.
@@ -0,0 +1,64 @@
# ADR 0012 — Borsa, controllo, scalate, amministrazione controllata e Cronaca finale (F5)
Stato: accettato (F5).
## Contesto
La sezione 12.2–12.3 fissa azioni, formula del prezzo, quotazione, dividendi, controllo, fusione,
offerte con le difese ed esiti per difficoltà, ma non dice chi possiede le azioni di una compagnia
privata, come aderisce il mercato a un'offerta, come si riscatta il 51 %, chi compra un'IA fallita né
come la fusione e la fine partita toccano il resto del mondo.
## Decisione
1. **Libro dei soci** (`ShareRegister`): 1.000.000 di azioni divise tra fondatore (il giocatore o il
proprietario privato di un'IA), mercato (flottante), azioni proprie (non votano) e altre compagnie.
Il giocatore parte con il 100 % (il 60 % in «Ferro e sangue», quotato); le IA sono quotate dall'inizio
con il 30 % di flottante.
2. **Prezzo**: `max(patrimonio netto, 8 × utile dei 12 mesi chiusi) / azioni in circolazione × sentiment`;
il sentiment (0,8–1,3) segue con media a 30 giorni `1 + 0,4·crescita degli utili + 1·ciclo mondiale
(A·sin(2πt/T)) + 4·rendimento dei dividendi + spinta del dividendo straordinario`. Le partecipazioni
in altre compagnie entrano nel patrimonio netto al prezzo di mercato. Si scambia al prezzo ± metà
dello spread (1 %), al massimo il 5 % del capitale per ordine.
3. **Quotazione** (livello 4): il fondatore colloca fino al 40 % e il ricavato entra in cassa; chi è già
quotato può collocare altro capitale fino a un flottante del 60 % (le IA lo fanno quando la cassa
scarseggia). **Riacquisto** = comprare le proprie azioni (per conto del fondatore).
4. **Controllo**: chi supera il 50 % delle azioni in circolazione controlla; ogni mese la controllata
versa la quota dell'utile del mese al controllante (voce «Controllate», un dividendo per la
controllata); dopo 360 giorni il controllante può fonderla con `MergeCompany` (comando 39, aggiunto
in F5): liquida le minoranze al prezzo di mercato e assorbe rete, treni, linee, industrie, debiti e
cassa; la fusa resta nel mondo come compagnia cessata.
5. **Offerte pubbliche** (`LaunchBid`, livello 5 per il giocatore; le IA con cassa): premio 20–50 % sul
prezzo, durata 90 giorni, quota obiettivo. Ogni giorno aderisce una quota del flottante libero
proporzionale al premio (4 % al giorno con il premio minimo, fino all'8 %); le compagnie azioniste
aderiscono con `RespondBid` e il fondatore privato di un'IA solo con premi sopra il 40 %. L'offerta si
chiude quando le adesioni raggiungono la quota o alla scadenza: senza la quota fallisce e nessuno
vende (offerta condizionata). Difese del bersaglio (`RespondBid` con il campo `Defense`): riacquisto
del flottante con la cassa, dividendo straordinario del 25 % della cassa (rende il titolo più caro),
cavaliere bianco (un'altra compagnia compra il flottante al prezzo dell'offerta + 5 %).
6. **Il giocatore comprato** (borsa o insolvenza): «Apprendista» mai (nessuna IA supera il 50 % e le
offerte sul giocatore sono rifiutate); «Imprenditore» e «Magnate» amministrazione controllata per 3 o
1 anno: dividendo obbligatorio del 50 % dell'utile trimestrale, niente prestiti; si esce riportando il
fondatore al 51 % (riacquisto dal mercato e poi dal controllante con un premio del 25 %); alla scadenza
la partita finisce. «Ferro e sangue»: fine immediata. Insolvenza: i creditori vendono la compagnia
all'IA più ricca che ne salda i debiti (poi gli stessi esiti); senza compratori la partita finisce.
7. **IA fallite**: gli attivi vanno all'asta per 30 giorni con base al 40 % del valore di libro; si offre
con `LaunchBid` sul fallito (prezzo per azione × 1.000.000). Il vincitore paga i creditori e assorbe
gli attivi; senza offerte i treni si rottamano, le linee chiudono e binari e stazioni restano
abbandonati.
8. **Nuovi concorrenti** (12.1): a inizio anno, se una compagnia ha più del 60 % dei ricavi dei vettori,
entra una nuova IA (al massimo una ogni 3 anni, fino a 8 compagnie attive). La F7 aggiunge antitrust e
finanziamenti statali.
9. **Fine partita e Cronaca**: `World.GameOver` registra motivo, testo e vincitore; da quel momento i
comandi del giocatore sono rifiutati e il mondo prosegue (osservatore). La Cronaca finale (messaggio
128, anche su richiesta come cronaca provvisoria) riporta la storia annuale, i primati, i fatti
salienti e un prestigio semplice (100 per livello massimo + 1 per 10.000 lire di patrimonio massimo
+ 5 per anno di attività), che la F7 estende.
## Conseguenze
- Prezzi in centesimi frazionari: per una compagnia piccola un'azione vale pochi centesimi e il premio
di un'offerta ha la granularità di un centesimo (le IA non offrono quando l'arrotondamento esce dai
limiti del premio).
- Il salvataggio passa alla versione 3 (sezione societaria in coda allo stato dinamico, nell'hash); i
salvataggi precedenti ricevono un libro dei soci come in una partita nuova.
+72
View File
@@ -0,0 +1,72 @@
# ADR 0013 — Agenti IA delle compagnie concorrenti (F5)
Stato: accettato (F5).
## Contesto
La sezione 12.1 chiede agenti che usino solo i comandi del protocollo, pianifichino ogni mese con
candidati, percorso di Dijkstra sulle celle, `TrackPlanner` e ROI, con personalità diverse e vincoli
identici al giocatore. Restano aperti: come l'IA riceve gli esiti dei comandi, quali informazioni legge,
come sceglie stazioni e depositi, come tiene in vita la rete (ricambi, stalli) e come si evita che più IA
facciano la stessa linea.
## Decisione
1. **Comandi**: l'agente costruisce i record di `Commands` e li esegue con `CommandProcessor.Execute`
dal sistema `AiAgents`, con le stesse validazioni e gli stessi costi dei giocatori, ricevendo subito
l'esito (gli id creati). Nessun comando in volo tra un tick e l'altro, quindi niente da salvare oltre
allo stato dell'agente; i comandi delle IA non vanno nel registro del replay (si rigiocano da soli).
Conta emessi e rifiutati: il test di 14.5 chiede rifiutati ≤ 5 %, in pratica sono quasi zero perché
l'agente verifica prima siti e tracciati con le stesse funzioni (`TrackPreview` del comando).
2. **Informazioni**: solo ciò che vede anche il giocatore (terreno, industrie, città, hub, prezzi, rete e
treni di tutti), con gli stimatori di `Estimators` (ricavo per unità e per passeggero, durata del giro,
costi) che serviranno anche ai tooltip «perché».
3. **Pianificazione mensile** (giorno del mese diverso per IA): finanza (rimborso dei prestiti più cari
quando la cassa supera 12 mesi di costi, aumento di capitale in borsa quando scarseggia), un treno in più
sulle linee con la merce in attesa (fino a 2 per linea e nei limiti dei binari di stazione), borsa,
industrie (dal livello 3, una all'anno tra quelle servite e in utile), linea dei ricambi se un deposito
non ne riceve, altrimenti al più un nuovo progetto.
4. **Candidati**: merci da un produttore a un consumatore (industria, città con domanda, hub
d'esportazione) tra 4 e 40 km in linea d'aria, non già serviti da altre compagnie (anche con stazioni
in costruzione; la Predatoria punta invece ai produttori serviti dal giocatore); pendolari da città con
lavoratori liberi verso industrie che la compagnia serve già con le merci, entro il tempo massimo di
viaggio. Punteggio di massima = ricavo annuo stimato / costo in linea d'aria, ritoccato: ×1,3 se un capo
è una stazione propria, ×0,5 se una rete nuova non ha fonti di ricambi vicine, ×1,8 per le città quando
il livello successivo ne chiede di più. Si valutano i 6 migliori.
5. **Valutazione**: siti delle stazioni (stazione propria con il bacino giusto e binari liberi, altrimenti
punti liberi a 300–1.250 m verso l'altro capo, lontani dai binari altrui); percorso con Dijkstra a 8
direzioni in un riquadro attorno ai capi (costo = modificatore di costo del terreno, ponte per i fiumi
attraversabili con i ponti dell'epoca, penalità di pendenza e di celle troppo ripide; città, industrie,
mare, fiumi troppo larghi e binari propri esclusi), semplificazione di Douglas–Peucker che non taglia
ostacoli e rimozione dei vertici i cui raccordi non stanno al raggio minimo; piano con
`TrackPreview` (se non valido si riprova con tolleranza dimezzata). Prima della ricerca si controlla
che i capi siano nella stessa regione collegabile (componenti connesse ricalcolate quando cambiano i
ponti dell'epoca). Ricavi: merci = min(produzione, domanda) × ricavo per unità, entro la capacità dei
treni; pendolari = posti al giorno dei treni × copertura attesa (0,6). Costi annui: treni con
manutenzione, binari di stazione, deposito, manutenzione del binario. ROI = (ricavi − costi) / capitale
(come nella guida: gli interessi sono una scelta di finanziamento), confrontato con la soglia della
personalità; per i progetti che collegano città, quando il livello successivo ne chiede di più, la
soglia si dimezza.
6. **Esecuzione**: stazioni (la stazione del deposito ha 6 binari: diventa il nodo della rete), binario,
deposito piccolo con raccordo (dalla parte della fonte di ricambi), poi, a cantieri finiti, linea, treni
(locomotiva non elettrica più recente, carri adatti al bene o carrozze della classe) e assegnazione.
Prestiti entro la quota del fido della personalità (tutto il fido per comprare il primo treno di una
linea già costruita).
7. **Tenere in vita la rete**: una rete nuova lontana da hub e fabbriche di macchinari mette in conto la
linea dei ricambi (se nessuna è possibile, il candidato si scarta); ogni deposito con treni in servizio
riceve una linea dei ricambi dalla fonte più vicina; una stazione condivisa regge al massimo binari − 1
treni (stallo di capacità); se almeno due treni aspettano via libera da più dei giorni d'avviso e
nessuno è guasto in linea, quello fermo da più tempo diventa riserva (una volta ogni 60 giorni).
8. **Personalità** da `ai.json`: Espansiva (ROI 8 %, prestiti fino all'80 % del fido), Prudente (15 %,
30 %), Predatoria (10 %, 60 %, compra quote dei concorrenti quotati e in utile fino al 30 %, poi lancia
un'offerta al 30 % di premio). Tutte rispondono alle offerte sulle azioni che possiedono (aderiscono con
un premio ≥ 15 %) e si difendono da bersaglio (riacquisto, cavaliere bianco non predatorio, dividendo
straordinario), fondono le controllate dopo un anno.
## Conseguenze
- Il comportamento è riproducibile: stesso seme e stessi comandi del giocatore danno lo stesso hash anche
con le IA (test di determinismo di 14.5), e lo stato dell'agente entra nel salvataggio.
- Nel 1850 i grandi fiumi (oltre la campata dei ponti in legno) dividono la mappa in regioni: le IA
crescono nella propria regione finché i ponti in ferro (1870) aprono nuovi collegamenti.
- La qualità delle IA dipende dal bilanciamento economico: la F6 lo rifinisce con bot su `simulate`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

@@ -46,6 +46,7 @@ public enum CommandType : ushort
AcceptContract = 36,
FundResearch = 37,
DelegateRegion = 38,
MergeCompany = 39,
}
/// <summary>Codici di errore stabili degli esiti dei comandi.</summary>
+25 -2
View File
@@ -26,10 +26,17 @@ public sealed record ScheduleServiceCommand(TrainId Train, string Intervention)
public override CommandType Type => CommandType.ScheduleService;
}
/// <summary>Ordina ricambi per un deposito (domanda esplicita sul grafo delle linee).</summary>
/// <summary>
/// Ordina ricambi (domanda esplicita sul grafo delle linee): per un deposito fissa la scorta
/// desiderata; con <see cref="Industry"/> valido ordina la quantità indicata oltre la scorta della
/// politica di un'industria posseduta (sezione 11).
/// </summary>
public sealed record OrderPartsCommand(DepotId Depot, int Quantity) : GameCommand
{
public override CommandType Type => CommandType.OrderParts;
/// <summary>Industria destinataria (blocco 1 del protocollo); None per i depositi.</summary>
public IndustryId Industry { get; init; } = IndustryId.None;
}
/// <summary>Accetta una convenzione di pendolarismo proposta da un'industria.</summary>
@@ -104,10 +111,26 @@ public sealed record LaunchBidCommand(CompanyId Target, Money PricePerShare, dou
public override CommandType Type => CommandType.LaunchBid;
}
/// <summary>Risposta a un'offerta pubblica (azionisti del bersaglio).</summary>
/// <summary>
/// Risposta a un'offerta pubblica: un'azionista aderisce (Accept) con tutte le sue azioni; il
/// bersaglio può difendersi (blocco 1 del protocollo) con riacquisto, dividendo straordinario o
/// cavaliere bianco (12.2).
/// </summary>
public sealed record RespondBidCommand(BidId Bid, bool Accept) : GameCommand
{
public override CommandType Type => CommandType.RespondBid;
/// <summary>Difesa del bersaglio (None per l'adesione degli azionisti).</summary>
public Economy.BidDefense Defense { get; init; }
/// <summary>Compagnia alleata chiamata come cavaliere bianco.</summary>
public CompanyId Knight { get; init; } = CompanyId.None;
}
/// <summary>Fusione di una controllata posseduta da almeno un anno (12.2); id 39, aggiunto in F5.</summary>
public sealed record MergeCompanyCommand(CompanyId Subsidiary) : GameCommand
{
public override CommandType Type => CommandType.MergeCompany;
}
/// <summary>Acquisto della concessione di una regione.</summary>
+73
View File
@@ -9,6 +9,7 @@ public sealed class AiFile
[JsonPropertyName("$schema")] public string? Schema { get; init; }
public required int Version { get; init; }
public required AiPlanningParams Planning { get; init; }
public required AiMarketParams Market { get; init; }
public required List<AiPersonalityDef> Personalities { get; init; }
public required List<string> CompanyNames { get; init; }
public required List<string> Colors { get; init; }
@@ -23,11 +24,83 @@ public sealed class AiPlanningParams
public required double CandidateMinDistanceKm { get; init; }
public required double PathSlopePenalty { get; init; }
public required double PathWaterPenalty { get; init; }
/// <summary>Costo aggiunto per cella con pendenza del terreno oltre SteepGradeFactor × pendenza massima.</summary>
public required double SteepPenalty { get; init; }
public required double SteepGradeFactor { get; init; }
/// <summary>Margine più ampio per un secondo tentativo di ricerca del percorso.</summary>
public required double PathMarginRetryKm { get; init; }
public required int TrainsPerLine { get; init; }
public required int WagonsPerTrain { get; init; }
public required double CashReserveMonths { get; init; }
public required double RevenueHorizonYears { get; init; }
public required double MaxRejectedShare { get; init; }
/// <summary>Progetti in costruzione contemporaneamente.</summary>
public required int MaxConcurrentProjects { get; init; }
/// <summary>Candidati migliori (stima in linea d'aria) valutati con percorso e piano dei binari.</summary>
public required int EvaluateTop { get; init; }
/// <summary>Margine attorno ai due estremi per la ricerca del percorso sulle celle.</summary>
public required double PathMarginKm { get; init; }
public required double SimplifyToleranceM { get; init; }
/// <summary>Distanze provate per la stazione dal centro dell'industria o dal bordo della città.</summary>
public required double[] StationOffsetsM { get; init; }
public required double DepotOffsetM { get; init; }
public required int Platforms { get; init; }
/// <summary>Binari della stazione del deposito, nodo della rete per le linee successive.</summary>
public required int HubPlatforms { get; init; }
/// <summary>Efficienza attesa delle industrie servite (stima dei volumi).</summary>
public required double AssumedEfficiency { get; init; }
/// <summary>Velocità media come quota della massima (salite, curve, frenate).</summary>
public required double SpeedFactor { get; init; }
public required double DwellMinutes { get; init; }
/// <summary>Manutenzione della flotta stimata in quota del costo d'esercizio.</summary>
public required double MaintenanceCostShare { get; init; }
public required long TrackUpkeepPerKmPerYear { get; init; }
public required int MaxTrainsPerLine { get; init; }
/// <summary>Si aggiunge un treno quando in stazione aspetta più di questi carichi pieni.</summary>
public required double AddTrainWaitingTrips { get; init; }
public required int MinCommuters { get; init; }
/// <summary>Copertura attesa dei pendolari (treni in officina, attese, scioglimenti).</summary>
public required double CommuterCoverage { get; init; }
/// <summary>Quota della capacità di un hub che una linea d'esportazione può aspettarsi.</summary>
public required double HubShare { get; init; }
/// <summary>Peso di una rete nuova senza fonti di ricambi vicine (servirà una linea apposta).</summary>
public required double NoPartsFactor { get; init; }
/// <summary>Peso delle linee che collegano una città quando il prossimo livello ne chiede.</summary>
public required double TownBonus { get; init; }
/// <summary>Riduzione della soglia di ROI per le linee che collegano città quando servono al livello.</summary>
public required double TownRoiFactor { get; init; }
/// <summary>Si rimborsano prestiti quando la cassa supera questi mesi di costi.</summary>
public required double RepayCashMonths { get; init; }
/// <summary>Distanza in giorni tra i giorni di pianificazione delle diverse IA.</summary>
public required int PlanningDaySpacing { get; init; }
/// <summary>Candidati falliti ricordati per non riprovarli.</summary>
public required int FailedMemory { get; init; }
}
/// <summary>Comportamento in borsa delle IA (12.1–12.2).</summary>
public sealed class AiMarketParams
{
/// <summary>Premio oltre il quale il proprietario privato di un'IA cede le sue azioni a un'offerta.</summary>
public required double FounderAcceptPremium { get; init; }
/// <summary>Premio oltre il quale un'IA azionista aderisce a un'offerta.</summary>
public required double HolderAcceptPremium { get; init; }
/// <summary>Quota che una Predatoria accumula nei concorrenti prima di lanciare un'offerta.</summary>
public required double PredatoryStakeTarget { get; init; }
/// <summary>Quota della cassa libera destinata ogni mese agli acquisti di azioni.</summary>
public required double SharesCashShare { get; init; }
public required double BidMinStake { get; init; }
public required double BidPremium { get; init; }
/// <summary>Cassa richiesta (multiplo del costo) per lanciare un'offerta.</summary>
public required double BidCashMultiple { get; init; }
public required double BuybackCashShare { get; init; }
/// <summary>Cassa (multiplo del costo) con cui un'IA accetta di fare da cavaliere bianco.</summary>
public required double KnightCashMultiple { get; init; }
/// <summary>Flottante massimo che un'IA raggiunge con gli aumenti di capitale.</summary>
public required double IssueFloatMax { get; init; }
/// <summary>Quota del capitale collocata a ogni aumento.</summary>
public required double IssueShare { get; init; }
public required double IndustryMaxCashShare { get; init; }
public required double IndustryMinMargin { get; init; }
}
public sealed class AiPersonalityDef
+65
View File
@@ -377,6 +377,41 @@ public sealed class StockMarketBalance
public required int BidDurationDays { get; init; }
public required double RansomShare { get; init; }
public required double ReceivershipDividend { get; init; }
/// <summary>Peso della crescita degli utili sul sentiment (crescita relativa, limitata a ±1).</summary>
public required double SentimentEarningsWeight { get; init; }
/// <summary>Peso del ciclo di mercato mondiale (A·sin(2πt/T)) sul sentiment.</summary>
public required double SentimentCycleWeight { get; init; }
/// <summary>Peso del rendimento dei dividendi degli ultimi 12 mesi sul sentiment.</summary>
public required double SentimentDividendWeight { get; init; }
public required int SentimentSmoothingDays { get; init; }
/// <summary>Spinta temporanea del dividendo straordinario (difesa), che decade linearmente.</summary>
public required double ExtraDividendSentimentBoost { get; init; }
public required int ExtraDividendDecayDays { get; init; }
/// <summary>Flottante delle compagnie IA all'inizio (quotate dall'inizio).</summary>
public required double AiFloatAtStart { get; init; }
/// <summary>Quota del flottante residuo che aderisce ogni giorno a un'offerta con il premio minimo.</summary>
public required double TenderDailyShare { get; init; }
/// <summary>Quota della cassa pagata come dividendo straordinario nella difesa.</summary>
public required double ExtraDividendCashShare { get; init; }
/// <summary>Premio del cavaliere bianco sul prezzo dell'offerta ostile.</summary>
public required double WhiteKnightPremium { get; init; }
/// <summary>Premio sul prezzo di mercato per riscattare azioni dal controllante in amministrazione controllata.</summary>
public required double RansomPremium { get; init; }
/// <summary>Massimo di azioni scambiabili al giorno da una compagnia, in quota del capitale.</summary>
public required double MaxDailyTradeShare { get; init; }
/// <summary>Flottante massimo raggiungibile con gli aumenti di capitale di chi è già quotato.</summary>
public required double SecondaryMaxFloat { get; init; }
public required int PriceHistoryMonths { get; init; }
/// <summary>Durata dell'asta degli attivi di una compagnia fallita.</summary>
public required int AuctionDays { get; init; }
/// <summary>Prezzo minimo dell'asta in quota del valore di libro degli attivi.</summary>
public required double AuctionMinBookShare { get; init; }
/// <summary>Quota di mercato oltre la quale entra un nuovo concorrente (12.1).</summary>
public required double ConcentrationThreshold { get; init; }
public required int NewCompetitorCooldownYears { get; init; }
public required int MaxCompanies { get; init; }
/// <summary>Anni di storico per compagnia conservati (Cronaca finale).</summary>
public required int HistoryYears { get; init; }
}
public sealed class IndustryMaintenanceBalance
@@ -404,6 +439,36 @@ public sealed class IndustryMaintenanceBalance
public required int NpcUpgradeYears { get; init; }
public required double NpcHighMargin { get; init; }
public required double NpcOverhaulBelow { get; init; }
/// <summary>Scorta di ricambi desiderata in mesi di consumo della politica.</summary>
public required double PartsTargetMonths { get; init; }
/// <summary>Scorta iniziale di ricambi in mesi di consumo (politica Base).</summary>
public required double InitialPartsMonths { get; init; }
/// <summary>Massimo di ricambi ordinabili oltre la scorta desiderata («Ordina ricambi»).</summary>
public required int MaxOrderedParts { get; init; }
/// <summary>Raggio entro cui un fermo o un incidente colpisce la città più vicina.</summary>
public required double TownEffectRadiusKm { get; init; }
public required int StopHistoryLength { get; init; }
/// <summary>Cassa che un'industria di una compagnia trattiene; ogni mese il resto va al proprietario (o lo chiede).</summary>
public required long OwnerCashReserve { get; init; }
public required IndustryPurchaseParams Purchase { get; init; }
public IndustryBudgetParams For(Economy.IndustryBudget budget) => Budgets[budget switch
{
Economy.IndustryBudget.None => "none",
Economy.IndustryBudget.High => "high",
_ => "base",
}];
}
/// <summary>Valutazione di un'industria in vendita (BuyIndustry).</summary>
public sealed class IndustryPurchaseParams
{
/// <summary>Quota del costo di ammodernamento cumulato riconosciuta come valore degli impianti.</summary>
public required double AssetShare { get; init; }
/// <summary>Multiplo dell'utile annuo stimato.</summary>
public required double EarningsMultiple { get; init; }
/// <summary>Peso della condizione sul valore degli impianti: valore × (1 − peso + peso·c/100).</summary>
public required double ConditionWeight { get; init; }
}
public sealed class IndustryBudgetParams
+82 -5
View File
@@ -25,6 +25,10 @@ public enum LedgerEntry : byte
Contracts = 16,
Penalties = 17,
Other = 18,
/// <summary>Conguaglio mensile con le industrie possedute (utili versati o perdite coperte).</summary>
Industries = 19,
/// <summary>Utili versati dalle compagnie controllate.</summary>
Subsidiaries = 20,
}
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
@@ -41,7 +45,7 @@ public sealed class Loan
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
public sealed class Company
{
public const int EntryCount = 19;
public const int EntryCount = 21;
public required CompanyId Id { get; init; }
public required string Name { get; set; }
@@ -86,14 +90,86 @@ public sealed class Company
}
}
/// <summary>Patrimonio netto = cassa + attivi a valore di libro − debiti.</summary>
public Money NetWorth => Cash + AssetBookValue - Debt;
/// <summary>Valore di mercato delle azioni di altre compagnie possedute (aggiornato ogni giorno dalla borsa).</summary>
public Money PortfolioValue { get; set; }
/// <summary>Patrimonio netto = cassa + attivi a valore di libro + partecipazioni − debiti.</summary>
public Money NetWorth => Cash + AssetBookValue + PortfolioValue - Debt;
// ------------------------------------------------------------------ borsa e controllo (12.2)
/// <summary>Libro dei soci.</summary>
public ShareRegister Shares { get; } = new();
/// <summary>Quotata in borsa (le azioni del flottante si scambiano).</summary>
public bool Listed { get; set; }
/// <summary>Prezzo per azione (centesimi, frazionario) e sentiment corrente.</summary>
public double SharePrice { get; set; }
public double Sentiment { get; set; } = 1;
/// <summary>Spinta del dividendo straordinario, che decade ogni giorno.</summary>
public double ExtraSentiment { get; set; }
/// <summary>Utile operativo degli ultimi 12 mesi chiusi (anello mensile) e indice del prossimo mese.</summary>
public long[] ProfitRing { get; } = new long[12];
public int ProfitRingIndex { get; set; }
/// <summary>Dividendi pagati negli ultimi 12 mesi (anello mensile, centesimi).</summary>
public long[] DividendRing { get; } = new long[12];
/// <summary>Utile dei 12 mesi alla chiusura dell'anno precedente (per la crescita).</summary>
public long LastAnnualProfit { get; set; }
/// <summary>Compagnia che controlla questa (oltre la soglia di controllo) e da quando.</summary>
public CompanyId ControlledBy { get; set; } = CompanyId.None;
public long ControlSinceDay { get; set; } = -1;
/// <summary>Fusa in un'altra compagnia: non esiste più come impresa autonoma.</summary>
public bool Merged { get; set; }
public CompanyId MergedInto { get; set; } = CompanyId.None;
/// <summary>Amministrazione controllata del giocatore (12.3): fino a quando e sotto chi.</summary>
public bool Receivership { get; set; }
public long ReceivershipUntilDay { get; set; } = -1;
public CompanyId ReceivershipBy { get; set; } = CompanyId.None;
/// <summary>Giorno della bancarotta (−1 se attiva) e attivi già liquidati.</summary>
public long BankruptDay { get; set; } = -1;
public bool Liquidated { get; set; }
/// <summary>Storico dei prezzi dell'azione, un valore al mese (centesimi).</summary>
public List<double> PriceHistory { get; } = [];
/// <summary>Fotografie annuali per la Cronaca finale.</summary>
public List<CompanyYear> History { get; } = [];
/// <summary>Fatti salienti (livelli, quotazione, scalate, fusioni) per la Cronaca finale.</summary>
public List<CompanyMilestone> Milestones { get; } = [];
/// <summary>Compagnia fuori gioco: fallita o fusa.</summary>
public bool Defunct => Bankrupt || Merged;
/// <summary>Utile operativo degli ultimi 12 mesi chiusi.</summary>
public long AnnualProfit
{
get
{
long sum = 0;
foreach (long p in ProfitRing) sum += p;
return sum;
}
}
/// <summary>Capitalizzazione di borsa (centesimi).</summary>
public double MarketCap => SharePrice * Shares.Outstanding;
/// <summary>Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti).</summary>
public static long OperatingProfit(long[] entries)
{
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts];
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]
+ entries[(int)LedgerEntry.Industries] + entries[(int)LedgerEntry.Subsidiaries];
long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
@@ -102,5 +178,6 @@ public sealed class Company
public static long Revenue(long[] entries) =>
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts]);
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts])
+ Math.Max(0, entries[(int)LedgerEntry.Industries]) + Math.Max(0, entries[(int)LedgerEntry.Subsidiaries]);
}
+1 -1
View File
@@ -96,7 +96,7 @@ public sealed class CommuteAgreement
{
public required AgreementId Id { get; init; }
public required IndustryId Industry { get; init; }
public required CompanyId Carrier { get; init; }
public required CompanyId Carrier { get; set; }
public required int SeatsPerDay { get; init; }
public required Money MonthlyFee { get; init; }
public required long ProposedDay { get; init; }
+41
View File
@@ -6,6 +6,15 @@ namespace ViaFerrea.Core.Economy;
/// <summary>Budget di manutenzione degli impianti scelto dal proprietario (guida, sezione 11).</summary>
public enum IndustryBudget : byte { None = 0, Base = 1, High = 2 }
/// <summary>Motivo di un fermo dell'industria (sezione 11).</summary>
public enum IndustryStop : byte { None = 0, Breakdown = 1, Accident = 2, Overhaul = 3, Upgrade = 4 }
/// <summary>Lavoro programmato in attesa di macchinari (e personale, per la revisione).</summary>
public enum IndustryWork : byte { None = 0, Overhaul = 1, Upgrade = 2 }
/// <summary>Fermo concluso o in corso, per lo storico del pannello del proprietario.</summary>
public readonly record struct IndustryStopRecord(long Day, int Days, IndustryStop Kind);
/// <summary>
/// Industria: produce secondo la ricetta del suo tipo, con efficienza
/// e = min(copertura input, lavoratori, personale) × fattore di profitto × condizione impianti.
@@ -39,6 +48,38 @@ public sealed class Industry : IWorkplace
public IndustryBudget Budget { get; set; } = IndustryBudget.Base;
/// <summary>Scorta di ricambi e macchinari per la manutenzione degli impianti (sezione 11).</summary>
public int SpareParts { get; set; }
public int Machinery { get; set; }
/// <summary>Ricambi ordinati dal proprietario oltre la scorta desiderata («Ordina ricambi»).</summary>
public int PartsOrdered { get; set; }
/// <summary>Ultimo consumo mensile di ricambi non coperto: il recupero è dimezzato.</summary>
public bool PartsShort { get; set; }
/// <summary>Fermo in corso fino al giorno indicato (escluso); −1 se l'industria lavora.</summary>
public long StoppedUntilDay { get; set; } = -1;
public IndustryStop StopKind { get; set; }
/// <summary>Lavoro programmato che aspetta macchinari o personale per iniziare.</summary>
public IndustryWork PendingWork { get; set; }
/// <summary>Ultimi fermi (il più recente in coda).</summary>
public List<IndustryStopRecord> StopHistory { get; } = [];
/// <summary>Mesi consecutivi con margine sopra la soglia di ammodernamento dei privati.</summary>
public int MonthsHighMargin { get; set; }
/// <summary>Spesa di manutenzione degli impianti dell'anno corrente (centesimi).</summary>
public long MaintenanceSpentYear { get; set; }
/// <summary>Giorno d'acquisto da parte della compagnia proprietaria (−1 se privata).</summary>
public long AcquiredDay { get; set; } = -1;
/// <summary>Fermo in corso nel giorno dato.</summary>
public bool IsStopped(long day) => StoppedUntilDay > day;
/// <summary>Scorte degli input, allineate a Def.Recipe.Inputs.</summary>
public int[] InputStock { get; init; } = [];
+120
View File
@@ -0,0 +1,120 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Economy;
/// <summary>
/// Libro dei soci di una compagnia (12.2): fondatore (il giocatore o il proprietario privato
/// dell'IA), flottante sul mercato, azioni proprie riacquistate (non votano) e quote delle altre
/// compagnie. Il totale resta sempre il numero di azioni della compagnia.
/// </summary>
public sealed class ShareRegister
{
public long Total { get; set; }
public long Founder { get; set; }
public long Public { get; set; }
public long Treasury { get; set; }
/// <summary>Quote delle compagnie, indicizzate per id (cresce con le compagnie).</summary>
public long[] ByCompany { get; set; } = [];
/// <summary>Azioni in circolazione (escluse le proprie): base del controllo e del prezzo per azione.</summary>
public long Outstanding => Total - Treasury;
public long Of(CompanyId holder) => holder.IsValid && holder.Value < ByCompany.Length ? ByCompany[holder.Value] : 0;
public void Add(CompanyId holder, long shares)
{
if (holder.Value >= ByCompany.Length)
{
var grown = new long[holder.Value + 1];
Array.Copy(ByCompany, grown, ByCompany.Length);
ByCompany = grown;
}
ByCompany[holder.Value] += shares;
}
/// <summary>Quota di voto del titolare sulle azioni in circolazione.</summary>
public double FractionOf(CompanyId holder) => Outstanding > 0 ? (double)Of(holder) / Outstanding : 0;
public double FounderFraction => Outstanding > 0 ? (double)Founder / Outstanding : 0;
/// <summary>Somma dei titolari (verifica d'invarianza: deve valere Total).</summary>
public long Sum()
{
long sum = Founder + Public + Treasury;
foreach (long s in ByCompany) sum += s;
return sum;
}
}
/// <summary>Stato di un'offerta pubblica di acquisto (12.2).</summary>
public enum BidState : byte { Open = 0, Succeeded = 1, Failed = 2, Withdrawn = 3 }
/// <summary>Difese del bersaglio (RespondBid dal bersaglio).</summary>
public enum BidDefense : byte { None = 0, Buyback = 1, ExtraDividend = 2, WhiteKnight = 3 }
/// <summary>
/// Offerta pubblica di acquisto: premio sul prezzo di mercato, durata, adesioni del flottante e
/// delle compagnie azioniste; si conclude quando le adesioni bastano o alla scadenza.
/// </summary>
public sealed class TakeoverBid
{
public required BidId Id { get; init; }
public required CompanyId Bidder { get; init; }
public required CompanyId Target { get; init; }
/// <summary>Prezzo offerto per azione (centesimi).</summary>
public required long PricePerShare { get; init; }
/// <summary>Quota del capitale in circolazione che l'offerente vuole raggiungere.</summary>
public required double TargetShare { get; init; }
public required long StartDay { get; init; }
public required long EndDay { get; init; }
public BidState State { get; set; }
/// <summary>Azioni del flottante che hanno aderito (vincolate fino all'esito).</summary>
public long TenderedPublic { get; set; }
/// <summary>Azioni del fondatore che hanno aderito (solo se il fondatore è un privato che accetta).</summary>
public long TenderedFounder { get; set; }
/// <summary>Compagnie azioniste che hanno aderito con tutte le loro azioni.</summary>
public List<CompanyId> Accepted { get; } = [];
/// <summary>Difese usate dal bersaglio (bit di <see cref="BidDefense"/>).</summary>
public byte Defenses { get; set; }
/// <summary>Cavaliere bianco intervenuto, se c'è.</summary>
public CompanyId Knight { get; set; } = CompanyId.None;
public long ClosedDay { get; set; } = -1;
}
/// <summary>Asta degli attivi di una compagnia fallita (12.1): vince l'offerta più alta alla scadenza.</summary>
public sealed class Auction
{
public required CompanyId Seller { get; init; }
public required long StartDay { get; init; }
public required long EndDay { get; init; }
public required long MinPriceCents { get; init; }
public CompanyId BestBidder { get; set; } = CompanyId.None;
public long BestPriceCents { get; set; }
public bool Closed { get; set; }
}
/// <summary>Fotografia annuale di una compagnia per la Cronaca finale e i grafici.</summary>
public readonly record struct CompanyYear(int Year, long NetWorthCents, long CashCents, long RevenueCents, long ProfitCents,
int Tier, int Trains, double TrackKm, long SharePriceCents);
/// <summary>Fatto saliente della storia di una compagnia.</summary>
public readonly record struct CompanyMilestone(long Day, string Text);
/// <summary>Esito della partita del giocatore (12.3).</summary>
public enum GameOverReason : byte { None = 0, Bankruptcy = 1, Takeover = 2, ReceivershipExpired = 3 }
/// <summary>Fine della partita: il mondo prosegue in modalità osservatore.</summary>
public sealed class GameOverState
{
public required long Day { get; init; }
public required GameOverReason Reason { get; init; }
public required string Text { get; init; }
public CompanyId Winner { get; init; } = CompanyId.None;
}
@@ -0,0 +1,352 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Ai;
namespace ViaFerrea.Core.Persistence;
/// <summary>
/// Stato della fase F5 (corpo del salvataggio dalla versione 3): manutenzione e proprietà delle
/// industrie, borsa, controllo e storico delle compagnie, offerte pubbliche, aste, fine partita e
/// agenti IA. I salvataggi precedenti si migrano con valori iniziali coerenti (ADR 0012).
/// </summary>
public static class CorporateSerializer
{
public static void Write(World w, SaveWriter s)
{
s.Write(w.Industries.Count);
foreach (var ind in w.Industries)
{
s.Write(ind.SpareParts);
s.Write(ind.Machinery);
s.Write(ind.PartsOrdered);
s.Write(ind.PartsShort);
s.Write(ind.StoppedUntilDay);
s.Write((byte)ind.StopKind);
s.Write((byte)ind.PendingWork);
s.Write(ind.MonthsHighMargin);
s.Write(ind.MaintenanceSpentYear);
s.Write(ind.AcquiredDay);
s.Write(ind.StopHistory.Count);
foreach (var h in ind.StopHistory)
{
s.Write(h.Day);
s.Write(h.Days);
s.Write((byte)h.Kind);
}
}
s.Write(w.Companies.Count);
foreach (var c in w.Companies)
{
var sh = c.Shares;
s.Write(sh.Total);
s.Write(sh.Founder);
s.Write(sh.Public);
s.Write(sh.Treasury);
s.Write(sh.ByCompany);
s.Write(c.Listed);
s.Write(c.SharePrice);
s.Write(c.Sentiment);
s.Write(c.ExtraSentiment);
s.Write(c.ProfitRing);
s.Write(c.ProfitRingIndex);
s.Write(c.DividendRing);
s.Write(c.LastAnnualProfit);
s.Write(c.PortfolioValue.Cents);
s.Write(c.ControlledBy.Value);
s.Write(c.ControlSinceDay);
s.Write(c.Merged);
s.Write(c.MergedInto.Value);
s.Write(c.Receivership);
s.Write(c.ReceivershipUntilDay);
s.Write(c.ReceivershipBy.Value);
s.Write(c.BankruptDay);
s.Write(c.Liquidated);
s.Write(c.PriceHistory.ToArray());
s.Write(c.History.Count);
foreach (var y in c.History)
{
s.Write(y.Year);
s.Write(y.NetWorthCents);
s.Write(y.CashCents);
s.Write(y.RevenueCents);
s.Write(y.ProfitCents);
s.Write(y.Tier);
s.Write(y.Trains);
s.Write(y.TrackKm);
s.Write(y.SharePriceCents);
}
s.Write(c.Milestones.Count);
foreach (var m in c.Milestones)
{
s.Write(m.Day);
s.Write(m.Text);
}
}
s.Write(w.Bids.Count);
foreach (var b in w.Bids)
{
s.Write(b.Id.Value);
s.Write(b.Bidder.Value);
s.Write(b.Target.Value);
s.Write(b.PricePerShare);
s.Write(b.TargetShare);
s.Write(b.StartDay);
s.Write(b.EndDay);
s.Write((byte)b.State);
s.Write(b.TenderedPublic);
s.Write(b.TenderedFounder);
s.Write(b.Accepted.Select(a => a.Value).ToArray());
s.Write(b.Defenses);
s.Write(b.Knight.Value);
s.Write(b.ClosedDay);
}
s.Write(w.Auctions.Count);
foreach (var a in w.Auctions)
{
s.Write(a.Seller.Value);
s.Write(a.StartDay);
s.Write(a.EndDay);
s.Write(a.MinPriceCents);
s.Write(a.BestBidder.Value);
s.Write(a.BestPriceCents);
s.Write(a.Closed);
}
s.Write(w.GameOver is not null);
if (w.GameOver is { } g)
{
s.Write(g.Day);
s.Write((byte)g.Reason);
s.Write(g.Text);
s.Write(g.Winner.Value);
}
s.Write(w.LastCompetitorYear);
s.Write(w.AiPaused);
s.Write(w.AiStates.Count);
foreach (var a in w.AiStates)
{
s.Write(a.Company.Value);
s.Write(a.PlanDay);
s.Write(a.Issued);
s.Write(a.Rejected);
s.Write(a.PolicySet);
s.Write(a.NextProjectId);
s.Write(a.LastIndustryYear);
s.Write(a.LastGridlockDay);
s.Write(a.Failed.ToArray());
s.Write(a.Responded.ToArray());
s.Write(a.Projects.Count);
foreach (var p in a.Projects)
{
s.Write(p.Id);
s.Write((byte)p.Kind);
s.Write(p.Good);
s.Write(p.PaxClass);
s.Write(p.Key);
s.Write(p.StationA.Value);
s.Write(p.StationB.Value);
s.Write(p.Depot.Value);
s.Write(p.Edges.Select(e => e.Value).ToArray());
s.Write(p.Line.Value);
s.Write(p.Trains.Select(t => t.Value).ToArray());
s.Write((byte)p.Stage);
s.Write(p.StartDay);
s.Write(p.CapitalCents);
s.Write(p.RevenuePerYearCents);
s.Write(p.TrainsPlanned);
s.Write(p.Loco);
s.Write(p.Car);
s.Write(p.CarsPerTrain);
s.Write(p.GrowAfterDay);
s.Write(p.SupplyFor.Value);
}
}
}
public static void Read(World w, SaveReader r)
{
int industries = r.ReadInt32();
for (int i = 0; i < industries; i++)
{
var ind = w.Industries[i];
ind.SpareParts = r.ReadInt32();
ind.Machinery = r.ReadInt32();
ind.PartsOrdered = r.ReadInt32();
ind.PartsShort = r.ReadBool();
ind.StoppedUntilDay = r.ReadInt64();
ind.StopKind = (IndustryStop)r.ReadByte();
ind.PendingWork = (IndustryWork)r.ReadByte();
ind.MonthsHighMargin = r.ReadInt32();
ind.MaintenanceSpentYear = r.ReadInt64();
ind.AcquiredDay = r.ReadInt64();
int history = r.ReadInt32();
for (int h = 0; h < history; h++) ind.StopHistory.Add(new IndustryStopRecord(r.ReadInt64(), r.ReadInt32(), (IndustryStop)r.ReadByte()));
}
int companies = r.ReadInt32();
for (int i = 0; i < companies; i++)
{
var c = w.Companies[i];
var sh = c.Shares;
sh.Total = r.ReadInt64();
sh.Founder = r.ReadInt64();
sh.Public = r.ReadInt64();
sh.Treasury = r.ReadInt64();
sh.ByCompany = r.ReadInt64Array();
c.Listed = r.ReadBool();
c.SharePrice = r.ReadDouble();
c.Sentiment = r.ReadDouble();
c.ExtraSentiment = r.ReadDouble();
CopyInto(r.ReadInt64Array(), c.ProfitRing);
c.ProfitRingIndex = r.ReadInt32();
CopyInto(r.ReadInt64Array(), c.DividendRing);
c.LastAnnualProfit = r.ReadInt64();
c.PortfolioValue = new Money(r.ReadInt64());
c.ControlledBy = new CompanyId(r.ReadInt32());
c.ControlSinceDay = r.ReadInt64();
c.Merged = r.ReadBool();
c.MergedInto = new CompanyId(r.ReadInt32());
c.Receivership = r.ReadBool();
c.ReceivershipUntilDay = r.ReadInt64();
c.ReceivershipBy = new CompanyId(r.ReadInt32());
c.BankruptDay = r.ReadInt64();
c.Liquidated = r.ReadBool();
c.PriceHistory.AddRange(r.ReadDoubleArray());
int years = r.ReadInt32();
for (int y = 0; y < years; y++)
{
c.History.Add(new CompanyYear(r.ReadInt32(), r.ReadInt64(), r.ReadInt64(), r.ReadInt64(), r.ReadInt64(),
r.ReadInt32(), r.ReadInt32(), r.ReadDouble(), r.ReadInt64()));
}
int milestones = r.ReadInt32();
for (int m = 0; m < milestones; m++) c.Milestones.Add(new CompanyMilestone(r.ReadInt64(), r.ReadRequiredString()));
}
int bids = r.ReadInt32();
for (int i = 0; i < bids; i++)
{
var b = new TakeoverBid
{
Id = new BidId(r.ReadInt32()),
Bidder = new CompanyId(r.ReadInt32()),
Target = new CompanyId(r.ReadInt32()),
PricePerShare = r.ReadInt64(),
TargetShare = r.ReadDouble(),
StartDay = r.ReadInt64(),
EndDay = r.ReadInt64(),
};
b.State = (BidState)r.ReadByte();
b.TenderedPublic = r.ReadInt64();
b.TenderedFounder = r.ReadInt64();
foreach (int a in r.ReadInt32Array()) b.Accepted.Add(new CompanyId(a));
b.Defenses = r.ReadByte();
b.Knight = new CompanyId(r.ReadInt32());
b.ClosedDay = r.ReadInt64();
w.Bids.Add(b);
}
int auctions = r.ReadInt32();
for (int i = 0; i < auctions; i++)
{
var a = new Auction
{
Seller = new CompanyId(r.ReadInt32()),
StartDay = r.ReadInt64(),
EndDay = r.ReadInt64(),
MinPriceCents = r.ReadInt64(),
};
a.BestBidder = new CompanyId(r.ReadInt32());
a.BestPriceCents = r.ReadInt64();
a.Closed = r.ReadBool();
w.Auctions.Add(a);
}
if (r.ReadBool())
{
w.GameOver = new GameOverState
{
Day = r.ReadInt64(),
Reason = (GameOverReason)r.ReadByte(),
Text = r.ReadRequiredString(),
Winner = new CompanyId(r.ReadInt32()),
};
}
w.LastCompetitorYear = r.ReadInt32();
w.AiPaused = r.ReadBool();
int states = r.ReadInt32();
for (int i = 0; i < states; i++)
{
var a = new AiState { Company = new CompanyId(r.ReadInt32()), PlanDay = r.ReadInt32() };
a.Issued = r.ReadInt64();
a.Rejected = r.ReadInt64();
a.PolicySet = r.ReadBool();
a.NextProjectId = r.ReadInt32();
a.LastIndustryYear = r.ReadInt32();
a.LastGridlockDay = r.ReadInt64();
a.Failed.AddRange(r.ReadInt64Array());
a.Responded.AddRange(r.ReadInt32Array());
int projects = r.ReadInt32();
for (int p = 0; p < projects; p++)
{
int id = r.ReadInt32();
var kind = (AiProjectKind)r.ReadByte();
int good = r.ReadInt32(), paxClass = r.ReadInt32();
long key = r.ReadInt64();
var stationA = new StationId(r.ReadInt32());
var stationB = new StationId(r.ReadInt32());
var depot = new DepotId(r.ReadInt32());
int[] edges = r.ReadInt32Array();
var line = new LineId(r.ReadInt32());
int[] trains = r.ReadInt32Array();
var stage = (AiProjectStage)r.ReadByte();
var project = new AiProject
{
Id = id, Kind = kind, Good = good, PaxClass = paxClass, Key = key,
StationA = stationA, StationB = stationB, Depot = depot, Line = line, Stage = stage,
StartDay = r.ReadInt64(),
CapitalCents = r.ReadInt64(),
RevenuePerYearCents = r.ReadInt64(),
TrainsPlanned = r.ReadInt32(),
Loco = r.ReadRequiredString(),
Car = r.ReadRequiredString(),
CarsPerTrain = r.ReadInt32(),
GrowAfterDay = r.ReadInt64(),
SupplyFor = new DepotId(r.ReadInt32()),
};
foreach (int e in edges) project.Edges.Add(new EdgeId(e));
foreach (int t in trains) project.Trains.Add(new TrainId(t));
a.Projects.Add(project);
}
w.AiStates.Add(a);
}
}
/// <summary>
/// Migrazione dei salvataggi precedenti a F5: ricambi iniziali delle industrie, libro dei soci
/// come in una partita nuova, prezzi delle azioni, agenti IA senza progetti.
/// </summary>
public static void Migrate(World w)
{
var im = w.Data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries)
{
ind.SpareParts = (int)Math.Round(Simulation.Systems.IndustryMath.MonthlyPartsUse(ind, im) * im.InitialPartsMonths);
w.Goods.Produced[w.Data.SparePartsGood] += ind.SpareParts;
}
var d = w.Difficulty;
foreach (var c in w.Companies)
{
if (c.IsPlayer) Corporate.InitShares(w, c, d.PublicFromStart, d.PublicFromStart ? d.PlayerShareAtStart : 1.0);
else Corporate.InitShares(w, c, listed: true, 1 - w.Data.Balance.StockMarket.AiFloatAtStart);
}
AiSystem.EnsureStates(w);
}
private static void CopyInto(long[] source, long[] target) => Array.Copy(source, target, Math.Min(source.Length, target.Length));
}
@@ -14,7 +14,7 @@ namespace ViaFerrea.Core.Persistence;
public static class WorldSerializer
{
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
public const int BodyVersion = 2;
public const int BodyVersion = 3;
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
public static void Write(World w, SaveWriter s)
@@ -235,6 +235,7 @@ public static class WorldSerializer
RailSerializer.Write(w, s);
MaintenanceSerializer.Write(w, s);
CorporateSerializer.Write(w, s);
}
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
@@ -673,6 +674,9 @@ public static class WorldSerializer
// versione 2 (F4): manutenzione, officine, convenzioni; la versione 1 si migra
if (version >= 2) MaintenanceSerializer.Read(w, r);
else MaintenanceSerializer.Migrate(w);
// versione 3 (F5): industrie, borsa, offerte, aste, fine partita, agenti IA
if (version >= 3) CorporateSerializer.Read(w, r);
else CorporateSerializer.Migrate(w);
}
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
+4 -4
View File
@@ -48,7 +48,7 @@ public sealed class TrackEdge
public required EdgeId Id { get; init; }
public required NodeId A { get; set; }
public required NodeId B { get; set; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required int TrackClass { get; set; }
public required bool DoubleTrack { get; set; }
public required bool Electrified { get; set; }
@@ -196,7 +196,7 @@ public sealed class TrackEdge
public sealed class Station
{
public required StationId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required NodeId Node { get; init; }
public required Vec2 Position { get; init; }
@@ -258,7 +258,7 @@ public sealed class WorkshopJob
public sealed class Depot : IWorkplace
{
public required DepotId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required NodeId Node { get; init; }
public required Vec2 Position { get; init; }
@@ -305,7 +305,7 @@ public enum ProjectKind : byte { NewTrack = 0, Renewal = 1, Upgrade = 2 }
public sealed class ConstructionProject
{
public required int Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required ProjectKind Kind { get; init; }
public required List<EdgeId> Edges { get; init; }
public required double TotalDays { get; init; }
+5 -2
View File
@@ -207,8 +207,11 @@ public static class TrackPlanner
string reason = !req.AllowTunnels
? "servirebbe una galleria o un altro tracciato"
: "abbassa o alza il tracciato o cambia percorso";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded,
$"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}", geo[i].S));
// se la stima locale non supera il massimo, il conflitto nasce dall'insieme dei vincoli di quota
string text = needed > gMax + 1e-9
? $"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}"
: $"I vincoli di quota (ponti, attraversamenti, estremità) non si raccordano entro la pendenza massima del {gMax * 100:F1}%: {reason}";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded, text, geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
}
+3 -3
View File
@@ -8,7 +8,7 @@ public sealed class Vehicle
{
public required VehicleId Id { get; init; }
public required VehicleDef Def { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required long BoughtDay { get; set; }
public TrainId Train { get; set; } = TrainId.None;
public DepotId Depot { get; set; } = DepotId.None;
@@ -97,7 +97,7 @@ public struct HeldResource
public sealed class Train
{
public required TrainId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public List<VehicleId> Vehicles { get; } = [];
public DepotId HomeDepot { get; set; } = DepotId.None;
@@ -216,7 +216,7 @@ public sealed record LineStop(StationId Station, bool Load = true, bool Unload =
public sealed class Line
{
public required LineId Id { get; init; }
public required CompanyId Owner { get; init; }
public required CompanyId Owner { get; set; }
public required string Name { get; set; }
public required string Color { get; set; }
public List<LineStop> Stops { get; } = [];
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,63 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>Tipo di progetto di un'IA: merci da un produttore a un consumatore o pendolari da una città.</summary>
public enum AiProjectKind : byte { Freight = 0, Commuter = 1 }
/// <summary>Fase di un progetto: cantieri, acquisto dei treni, esercizio o abbandono.</summary>
public enum AiProjectStage : byte { Construction = 0, Equip = 1, Running = 2, Abandoned = 3 }
/// <summary>Linea costruita (o in costruzione) da un'IA e ciò che serve a seguirla.</summary>
public sealed class AiProject
{
public required int Id { get; init; }
public required AiProjectKind Kind { get; init; }
/// <summary>Bene trasportato (merci) o −1.</summary>
public int Good { get; init; } = -1;
/// <summary>Classe dei pendolari (0 operai, 1 tecnici) per i progetti di pendolarismo.</summary>
public int PaxClass { get; init; }
public required long Key { get; init; }
public StationId StationA { get; set; } = StationId.None;
public StationId StationB { get; set; } = StationId.None;
public DepotId Depot { get; set; } = DepotId.None;
public List<EdgeId> Edges { get; } = [];
public LineId Line { get; set; } = LineId.None;
public List<TrainId> Trains { get; } = [];
public AiProjectStage Stage { get; set; }
public long StartDay { get; init; }
public long CapitalCents { get; init; }
public long RevenuePerYearCents { get; init; }
public int TrainsPlanned { get; set; }
public required string Loco { get; init; }
public required string Car { get; init; }
public int CarsPerTrain { get; init; }
/// <summary>Giorno prima del quale non si aggiungono treni (dopo uno stallo risolto).</summary>
public long GrowAfterDay { get; set; }
/// <summary>Deposito rifornito di ricambi da questa linea (progetti di supporto), o None.</summary>
public DepotId SupplyFor { get; init; } = DepotId.None;
}
/// <summary>Stato persistente dell'agente IA di una compagnia (12.1).</summary>
public sealed class AiState
{
public required CompanyId Company { get; init; }
/// <summary>Giorno del mese (0-based) in cui l'IA pianifica.</summary>
public int PlanDay { get; init; }
public long Issued { get; set; }
public long Rejected { get; set; }
public bool PolicySet { get; set; }
public int NextProjectId { get; set; }
public List<AiProject> Projects { get; } = [];
/// <summary>Chiavi dei candidati scartati (percorso o piano non validi), i più recenti in coda.</summary>
public List<long> Failed { get; } = [];
/// <summary>Offerte pubbliche a cui l'IA ha già risposto come bersaglio.</summary>
public List<int> Responded { get; } = [];
public int LastIndustryYear { get; set; } = int.MinValue;
/// <summary>Ultimo giorno in cui l'IA ha sciolto uno stallo (uno ogni tanto, non a cascata).</summary>
public long LastGridlockDay { get; set; } = -1_000_000;
/// <summary>Quota dei comandi rifiutati sul totale emesso.</summary>
public double RejectedShare => Issued == 0 ? 0 : (double)Rejected / Issued;
}
@@ -0,0 +1,49 @@
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>
/// Agenti delle compagnie IA (12.1), dopo la borsa: ogni giorno seguono progetti e offerte, una
/// volta al mese (in giorni diversi per ciascuna IA) pianificano. Le IA agiscono solo con i comandi.
/// </summary>
public sealed class AiSystem : ISimSystem
{
public string Name => "AiAgents";
/// <summary>Diagnostica facoltativa (strumenti): non influisce sulla simulazione.</summary>
public static Action<string>? Trace { get; set; }
private readonly GridPath _path = new();
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
if (w.AiPaused) return;
EnsureStates(w);
int dpm = w.Calendar.DaysPerMonth;
foreach (var s in w.AiStates)
{
var c = w.Company(s.Company);
if (c.Defunct) continue;
var agent = new AiAgent(w, ctx, s, _path);
agent.Daily();
if (ctx.Day % dpm == s.PlanDay) agent.Monthly();
}
}
/// <summary>Uno stato per ogni compagnia IA (anche per i nuovi concorrenti), in ordine di id.</summary>
public static void EnsureStates(World w)
{
if (w.AiStates.Count == w.Companies.Count(c => !c.IsPlayer)) return;
int dpm = w.Calendar.DaysPerMonth;
foreach (var c in w.Companies)
{
if (c.IsPlayer || w.AiStates.Any(s => s.Company == c.Id)) continue;
int index = w.AiStates.Count;
w.AiStates.Add(new AiState
{
Company = c.Id,
PlanDay = (1 + index * w.Data.Ai.Planning.PlanningDaySpacing) % dpm,
});
}
}
}
@@ -0,0 +1,381 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
namespace ViaFerrea.Core.Simulation.Ai;
/// <summary>
/// Percorso di un nuovo binario per le IA (12.1): Dijkstra sulla griglia delle celle in un
/// riquadro attorno ai due estremi, con costo = costo di costruzione della cella (modificatori del
/// terreno, acqua da superare con un ponte) + penalità di pendenza; città, industrie e mare non si
/// attraversano. Il percorso si semplifica in una polilinea (Douglas–Peucker).
/// </summary>
public sealed class GridPath
{
private double[] _dist = [];
private int[] _prev = [];
private readonly PriorityQueue<int, double> _queue = new();
// regioni collegabili (componenti connesse delle celle attraversabili) per la campata dell'epoca
private int[] _region = [];
private double _regionSpan = -1;
private int _regionCells = -1;
// celle con binari della compagnia (non si incrociano a raso), ricalcolate quando cambia la rete
private bool[] _ownTrack = [];
private int _ownTrackCompany = -1;
private int _ownTrackEdges = -1;
private long _ownTrackVersion = -1;
private static double MaxSpan(World w)
{
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
return maxSpan;
}
private static bool Passable(World w, int x, int y, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
switch (t.TypeAt(x, y))
{
case CellType.Sea:
case CellType.Town:
case CellType.Industry:
return false;
case CellType.Water:
int cls = t.RiverWidth[y * t.Width + x];
return cls > 0 && riverWidths[Math.Min(cls, riverWidths.Length) - 1] <= maxSpan;
default:
return true;
}
}
/// <summary>
/// Vero se i due punti stanno nella stessa regione collegabile con i ponti dell'epoca
/// (verifica rapida prima della ricerca del percorso).
/// </summary>
public bool SameRegion(World w, Vec2 a, Vec2 b)
{
var t = w.Terrain;
double span = MaxSpan(w);
if (span != _regionSpan || _regionCells != t.Width * t.Height) BuildRegions(w, span);
int ra = RegionNear(w, a), rb = RegionNear(w, b);
return ra >= 0 && ra == rb;
}
private int RegionNear(World w, Vec2 p)
{
var t = w.Terrain;
var (cx, cy) = t.CellAt(p);
for (int r = 0; r <= 2; r++)
{
for (int dy = -r; dy <= r; dy++)
{
for (int dx = -r; dx <= r; dx++)
{
int x = cx + dx, y = cy + dy;
if (!t.InBounds(x, y)) continue;
int label = _region[y * t.Width + x];
if (label >= 0) return label;
}
}
}
return -1;
}
private void BuildRegions(World w, double span)
{
var t = w.Terrain;
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
int n = t.Width * t.Height;
_region = new int[n];
Array.Fill(_region, -1);
var stack = new Stack<int>();
int next = 0;
for (int i = 0; i < n; i++)
{
if (_region[i] >= 0 || !Passable(w, i % t.Width, i / t.Width, span, riverWidths)) continue;
_region[i] = next;
stack.Push(i);
while (stack.Count > 0)
{
int c = stack.Pop();
int cx = c % t.Width, cy = c / t.Width;
for (int k = 0; k < 4; k++)
{
int nx = cx + (k == 0 ? 1 : k == 1 ? -1 : 0), ny = cy + (k == 2 ? 1 : k == 3 ? -1 : 0);
if (!t.InBounds(nx, ny)) continue;
int ni = ny * t.Width + nx;
if (_region[ni] >= 0 || !Passable(w, nx, ny, span, riverWidths)) continue;
_region[ni] = next;
stack.Push(ni);
}
}
next++;
}
_regionSpan = span;
_regionCells = n;
}
private void BuildOwnTrack(World w, CompanyId company)
{
var t = w.Terrain;
int n = t.Width * t.Height;
if (_ownTrack.Length != n) _ownTrack = new bool[n];
else Array.Clear(_ownTrack);
foreach (var e in w.Network.Edges)
{
if (e.Owner != company || e.State == Rail.EdgeState.Demolished) continue;
for (int i = 0; i < e.X.Length; i++)
{
var (cx, cy) = t.CellAt(new Vec2(e.X[i], e.Y[i]));
_ownTrack[cy * t.Width + cx] = true;
}
}
_ownTrackCompany = company.Value;
_ownTrackEdges = w.Network.Edges.Count;
_ownTrackVersion = w.Network.Version;
}
/// <summary>Polilinea in metri da <paramref name="from"/> a <paramref name="to"/>, o null se irraggiungibile.</summary>
public List<Vec2>? Find(World w, CompanyId company, Vec2 from, Vec2 to, double marginKm, double toleranceM, double minRadiusM)
{
var t = w.Terrain;
if (!SameRegion(w, from, to)) return null;
if (_ownTrackCompany != company.Value || _ownTrackEdges != w.Network.Edges.Count || _ownTrackVersion != w.Network.Version)
BuildOwnTrack(w, company);
var plan = w.Data.Ai.Planning;
var costs = w.Data.Construction.Costs;
var (ax, ay) = t.CellAt(from);
var (bx, by) = t.CellAt(to);
int margin = (int)Math.Ceiling(marginKm * 1000 / t.CellSizeM);
int x0 = Math.Max(0, Math.Min(ax, bx) - margin), x1 = Math.Min(t.Width - 1, Math.Max(ax, bx) + margin);
int y0 = Math.Max(0, Math.Min(ay, by) - margin), y1 = Math.Min(t.Height - 1, Math.Max(ay, by) + margin);
int bw = x1 - x0 + 1, bh = y1 - y0 + 1, n = bw * bh;
if (_dist.Length < n)
{
_dist = new double[n];
_prev = new int[n];
}
Array.Fill(_dist, double.PositiveInfinity, 0, n);
Array.Fill(_prev, -1, 0, n);
_queue.Clear();
// fiumi attraversabili con i ponti dell'epoca (larghezza dell'alveo della classe ≤ campata massima)
double maxSpan = 0;
foreach (var b in w.Data.Eras.BridgeTypes)
{
if (b.From <= w.Clock.Year) maxSpan = Math.Max(maxSpan, b.MaxSpanM);
}
var riverWidths = w.Data.Construction.Profile.RiverWidthMByClass;
// pendenza massima della trazione più permissiva disponibile: le celle più ripide costano molto
// (il pianificatore compensa solo piccoli dislivelli con trincee e rilevati)
var g = w.Data.Construction.MaxGradientByTraction;
double gMax = g.Steam;
if (w.Clock.Year >= w.Data.Eras.Eras.First(e => e.Id == "diesel").From) gMax = Math.Max(gMax, g.Diesel);
int start = (ay - y0) * bw + (ax - x0), goal = (by - y0) * bw + (bx - x0);
_dist[start] = 0;
_queue.Enqueue(start, 0);
double cs = t.CellSizeM;
ReadOnlySpan<int> dxs = [1, -1, 0, 0, 1, 1, -1, -1];
ReadOnlySpan<int> dys = [0, 0, 1, -1, 1, -1, 1, -1];
while (_queue.TryDequeue(out int cur, out double d))
{
if (d > _dist[cur]) continue;
if (cur == goal) break;
int cx = cur % bw + x0, cy = cur / bw + y0;
double hc = t.Heights[cy * t.Width + cx] / 10.0;
for (int k = 0; k < 8; k++)
{
int nx = cx + dxs[k], ny = cy + dys[k];
if (nx < x0 || nx > x1 || ny < y0 || ny > y1) continue;
int ni = (ny - y0) * bw + (nx - x0);
bool endpoint = ni == goal;
var type = t.TypeAt(nx, ny);
if (type == CellType.Water)
{
int cls = t.RiverWidth[ny * t.Width + nx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) continue;
}
double cellCost = CellCost(type, costs, plan, endpoint);
if (double.IsPositiveInfinity(cellCost)) continue;
// i propri binari non si incrociano a raso: ci si aggancia solo vicino agli estremi
if (_ownTrack[ny * t.Width + nx] && Vec2.Distance(t.CellCenter(nx, ny), from) > 300 && Vec2.Distance(t.CellCenter(nx, ny), to) > 300) continue;
double step = k < 4 ? 1.0 : 1.41421356237;
double hn = t.Heights[ny * t.Width + nx] / 10.0;
double grade = Math.Abs(hn - hc) / (step * cs);
double steep = grade > gMax * plan.SteepGradeFactor ? plan.SteepPenalty : 0;
double nd = d + step * (cellCost + steep) + plan.PathSlopePenalty * grade * step;
if (nd >= _dist[ni]) continue;
_dist[ni] = nd;
_prev[ni] = cur;
_queue.Enqueue(ni, nd);
}
}
if (double.IsPositiveInfinity(_dist[goal]))
{
int reached = 0;
for (int i = 0; i < n; i++) if (!double.IsPositiveInfinity(_dist[i])) reached++;
AiSystem.Trace?.Invoke($" percorso: obiettivo non raggiunto, celle raggiunte {reached} su {n}, partenza {t.TypeAt(ax, ay)} arrivo {t.TypeAt(bx, by)} binari propri vicino all'arrivo {_ownTrack[by * t.Width + bx]}");
return null;
}
var cells = new List<Vec2>();
for (int c = goal; c >= 0; c = _prev[c]) cells.Add(t.CellCenter(c % bw + x0, c / bw + y0));
cells.Reverse();
cells[0] = from;
cells[^1] = to;
bool Clear(Vec2 a, Vec2 b) => SegmentClear(w, a, b, from, to, maxSpan, riverWidths);
return EnforceRadius(Simplify(cells, toleranceM, Clear), minRadiusM * 1.05, Clear);
}
/// <summary>
/// Il segmento non attraversa città, industrie, mare o fiumi troppo larghi per i ponti dell'epoca
/// (a parte i primi e gli ultimi 200 m, dove stanno le stazioni).
/// </summary>
private static bool SegmentClear(World w, Vec2 a, Vec2 b, Vec2 from, Vec2 to, double maxSpan, double[] riverWidths)
{
var t = w.Terrain;
double len = Vec2.Distance(a, b);
int steps = Math.Max(1, (int)Math.Ceiling(len / 25));
for (int i = 0; i <= steps; i++)
{
var p = Vec2.Lerp(a, b, (double)i / steps);
if (Vec2.Distance(p, from) < 200 || Vec2.Distance(p, to) < 200) continue;
var (cx, cy) = t.CellAt(p);
switch (t.TypeAt(cx, cy))
{
case CellType.Town:
case CellType.Industry:
case CellType.Sea:
return false;
case CellType.Water:
int cls = t.RiverWidth[cy * t.Width + cx];
if (cls <= 0 || riverWidths[Math.Min(cls, riverWidths.Length) - 1] > maxSpan) return false;
break;
}
}
return true;
}
/// <summary>
/// Toglie i vertici i cui raccordi al raggio minimo non entrano nei segmenti adiacenti
/// (tangente R·tan(θ/2) a ciascun estremo), finché la polilinea li ammette tutti.
/// </summary>
public static List<Vec2> EnforceRadius(List<Vec2> points, double radius, Func<Vec2, Vec2, bool>? clear = null)
{
var pts = new List<Vec2>(points);
while (pts.Count > 2)
{
int n = pts.Count;
var tangent = new double[n];
for (int i = 1; i < n - 1; i++)
{
var d1 = (pts[i] - pts[i - 1]).Normalized();
var d2 = (pts[i + 1] - pts[i]).Normalized();
double theta = Math.Abs(DMath.Atan2(Vec2.Cross(d1, d2), Math.Clamp(Vec2.Dot(d1, d2), -1, 1)));
tangent[i] = radius * DMath.Tan(theta / 2);
}
int worst = -1;
double worstExcess = 0;
for (int j = 0; j < n - 1; j++)
{
double excess = tangent[j] + tangent[j + 1] - Vec2.Distance(pts[j], pts[j + 1]);
if (excess <= worstExcess) continue;
// si toglie il vertice con il raccordo più lungo, se il segmento che resta è libero
int first = j == 0 ? 1 : j + 1 == n - 1 ? j : tangent[j] >= tangent[j + 1] ? j : j + 1;
int second = first == j ? j + 1 : j;
foreach (int k in new[] { first, second })
{
if (k <= 0 || k >= n - 1) continue;
if (clear is not null && !clear(pts[k - 1], pts[k + 1])) continue;
worstExcess = excess;
worst = k;
break;
}
}
if (worst < 0) break;
pts.RemoveAt(worst);
}
return pts;
}
/// <summary>Costo relativo di costruzione per cella (∞ = non attraversabile).</summary>
private static double CellCost(CellType type, ConstructionCosts costs, AiPlanningParams plan, bool endpoint)
{
switch (type)
{
case CellType.Sea:
return double.PositiveInfinity;
case CellType.Town:
case CellType.Industry:
return endpoint ? 1.0 : double.PositiveInfinity;
case CellType.Water:
return plan.PathWaterPenalty;
case CellType.Rock:
return costs.TerrainModifiers.GetValueOrDefault("rock", 1.0);
case CellType.Marsh:
return costs.TerrainModifiers.GetValueOrDefault("marsh", 1.0);
case CellType.Mountain:
return costs.TerrainModifiers.GetValueOrDefault("mountain", 1.0);
case CellType.Forest:
return costs.TerrainModifiers.GetValueOrDefault("forest", 1.0);
default:
return 1.0;
}
}
/// <summary>
/// Semplificazione di Douglas–Peucker (estremi conservati): un tratto si divide anche quando il
/// segmento semplificato attraverserebbe un ostacolo.
/// </summary>
public static List<Vec2> Simplify(List<Vec2> points, double tolerance, Func<Vec2, Vec2, bool>? clear = null)
{
if (points.Count <= 2) return [.. points];
var keep = new bool[points.Count];
keep[0] = keep[^1] = true;
var stack = new Stack<(int, int)>();
stack.Push((0, points.Count - 1));
while (stack.Count > 0)
{
var (a, b) = stack.Pop();
double best = -1;
int index = -1;
for (int i = a + 1; i < b; i++)
{
double d = SegmentDistance(points[i], points[a], points[b]);
if (d > best)
{
best = d;
index = i;
}
}
if (index >= 0 && (best > tolerance || (clear is not null && !clear(points[a], points[b]))))
{
keep[index] = true;
stack.Push((a, index));
stack.Push((index, b));
}
}
var result = new List<Vec2>();
for (int i = 0; i < points.Count; i++)
{
if (keep[i]) result.Add(points[i]);
}
return result;
}
private static double SegmentDistance(Vec2 p, Vec2 a, Vec2 b)
{
var ab = b - a;
double len2 = ab.LengthSquared;
if (len2 <= 0) return Vec2.Distance(p, a);
double u = Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1);
return Vec2.Distance(p, a + ab * u);
}
}
@@ -0,0 +1,46 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation;
/// <summary>Primato della Cronaca finale.</summary>
public readonly record struct ChronicleRecord(string Title, string Value, int Year);
/// <summary>
/// Cronaca finale della compagnia del giocatore (12.3): storia anno per anno (con l'anno in
/// corso), primati, fatti salienti e prestigio. Il prestigio di F5 è un punteggio semplice
/// (livelli, patrimonio massimo, anni di attività) che la F7 estende (ADR 0012).
/// </summary>
public sealed class ChronicleReport
{
public List<CompanyYear> History { get; } = [];
public List<ChronicleRecord> Records { get; } = [];
public List<string> Highlights { get; } = [];
public long Prestige { get; private set; }
public static ChronicleReport Build(World w)
{
var c = w.Player;
var report = new ChronicleReport();
report.History.AddRange(c.History);
var current = Corporate.Snapshot(w, c, w.Clock.Year, c.YearEntries);
if (report.History.Count == 0 || report.History[^1].Year != current.Year) report.History.Add(current);
var richest = report.History.MaxBy(y => y.NetWorthCents);
var best = report.History.MaxBy(y => y.ProfitCents);
var fleet = report.History.MaxBy(y => y.Trains);
var track = report.History.MaxBy(y => y.TrackKm);
report.Records.Add(new ChronicleRecord("Patrimonio netto massimo", new Money(richest.NetWorthCents).ToString(), richest.Year));
report.Records.Add(new ChronicleRecord("Anno più redditizio", new Money(best.ProfitCents).ToString(), best.Year));
report.Records.Add(new ChronicleRecord("Flotta più grande", $"{fleet.Trains} treni", fleet.Year));
report.Records.Add(new ChronicleRecord("Rete più estesa", $"{track.TrackKm:0.0} km", track.Year));
int maxTier = report.History.Max(y => y.Tier);
var tierYear = report.History.First(y => y.Tier == maxTier);
report.Records.Add(new ChronicleRecord("Livello più alto", w.Data.Tiers.Tiers[Math.Clamp(maxTier, 1, w.Data.Tiers.Tiers.Count) - 1].NameIt, tierYear.Year));
foreach (var m in c.Milestones) report.Highlights.Add($"{w.Calendar.DateOfDay(m.Day)}: {m.Text}");
int years = Math.Max(0, w.Clock.Year - w.Calendar.StartYear);
report.Prestige = 100L * maxTier + richest.NetWorthCents / 1_000_000 + 5L * years;
return report;
}
}
@@ -17,14 +17,28 @@ public static class CommandProcessor
if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count)
return Result(CommandError.UnknownCompany, "Compagnia sconosciuta");
var company = w.Companies[command.Issuer.Value];
if (company.Merged)
return Result(CommandError.NotAllowed, "La compagnia è stata incorporata");
if (company.Bankrupt)
return Result(CommandError.Bankrupt, "La compagnia è in bancarotta");
if (company.IsPlayer && w.GameOver is not null)
return Result(CommandError.NotAllowed, "Partita conclusa: si osserva il mondo senza poter dare comandi");
return command switch
{
TakeLoanCommand c => TakeLoan(w, company, c, Result),
RepayLoanCommand c => RepayLoan(w, company, c, Result),
SetIndustryPolicyCommand c => SetIndustryPolicy(w, company, c, Result),
SetIndustryPolicyCommand c => IndustryCommandHandlers.SetPolicy(w, company, c, Reply),
BuyIndustryCommand c => IndustryCommandHandlers.BuyIndustry(w, company, c, Reply),
OverhaulIndustryCommand c => IndustryCommandHandlers.Overhaul(w, company, c, Reply),
UpgradeIndustryCommand c => IndustryCommandHandlers.Upgrade(w, company, c, Reply),
IpoCommand c => CorporateCommandHandlers.Ipo(w, company, c, Reply),
BuySharesCommand c => CorporateCommandHandlers.BuyShares(w, company, c, Reply),
SellSharesCommand c => CorporateCommandHandlers.SellShares(w, company, c, Reply),
PayDividendCommand c => CorporateCommandHandlers.PayDividend(w, company, c, Reply),
LaunchBidCommand c => CorporateCommandHandlers.LaunchBid(w, company, c, Reply),
RespondBidCommand c => CorporateCommandHandlers.RespondBid(w, company, c, Reply),
MergeCompanyCommand c => CorporateCommandHandlers.MergeCompany(w, company, c, ctx, Reply),
BuildTrackCommand c => RailCommandHandlers.BuildTrack(w, company, c, Reply),
BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply),
BuildDepotCommand c => RailCommandHandlers.BuildDepot(w, company, c, Reply),
@@ -52,6 +66,7 @@ public static class CommandProcessor
private static CommandResult TakeLoan(World w, Company company, TakeLoanCommand c, Func<CommandError, string, CommandResult> result)
{
if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido");
if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti");
var max = FinanceSystem.MaxLoan(w, company);
if (company.Debt + c.Amount > max)
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}");
@@ -82,13 +97,4 @@ public static class CommandProcessor
if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
return result(CommandError.None, $"Rimborsati {amount}");
}
private static CommandResult SetIndustryPolicy(World w, Company company, SetIndustryPolicyCommand c, Func<CommandError, string, CommandResult> result)
{
if (!c.Industry.IsValid || c.Industry.Value >= w.Industries.Count) return result(CommandError.NotFound, "Industria inesistente");
var ind = w.Industries[c.Industry.Value];
if (ind.Owner != company.Id) return result(CommandError.NotAllowed, "L'industria non appartiene alla compagnia");
ind.Budget = c.Budget;
return result(CommandError.None, $"Budget di manutenzione di {ind.Name}: {c.Budget}");
}
}
+284
View File
@@ -0,0 +1,284 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Operazioni societarie (12.2–12.3): prezzo delle azioni, controllo, fusioni, liquidazioni,
/// amministrazione controllata e fine partita del giocatore (ADR 0012).
/// </summary>
public static class Corporate
{
/// <summary>Libro dei soci iniziale: il fondatore tiene la quota indicata, il resto è flottante.</summary>
public static void InitShares(World w, Company c, bool listed, double founderShare)
{
long total = w.Data.Balance.StockMarket.Shares;
c.Shares.Total = total;
c.Shares.Founder = (long)Math.Round(total * Math.Clamp(founderShare, 0, 1));
c.Shares.Public = total - c.Shares.Founder;
c.Shares.Treasury = 0;
c.Listed = listed;
c.SharePrice = FundamentalPrice(w, c);
}
/// <summary>Valore fondamentale per azione: max(patrimonio netto, multiplo × utile annuo) / azioni in circolazione.</summary>
public static double FundamentalPrice(World w, Company c)
{
var sm = w.Data.Balance.StockMarket;
double value = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit);
long outstanding = Math.Max(1, c.Shares.Outstanding);
return Math.Max(MinPrice, value / outstanding);
}
/// <summary>Prezzo minimo per azione (centesimi): un titolo non vale mai zero.</summary>
public const double MinPrice = 0.01;
/// <summary>Prezzo d'acquisto (lettera) e di vendita (denaro) con lo spread.</summary>
public static double Ask(World w, Company c) => c.SharePrice * (1 + w.Data.Balance.StockMarket.Spread / 2);
public static double BidPrice(World w, Company c) => c.SharePrice * (1 - w.Data.Balance.StockMarket.Spread / 2);
/// <summary>Titolare che controlla la compagnia (oltre la soglia), o None (fondatore o nessuno).</summary>
public static CompanyId Controller(World w, Company c)
{
double control = w.Data.Balance.StockMarket.ControlShare;
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (i != c.Id.Value && c.Shares.FractionOf(new CompanyId(i)) > control) return new CompanyId(i);
}
return CompanyId.None;
}
/// <summary>Azioni del flottante non vincolate da offerte in corso.</summary>
public static long FreeFloat(World w, Company c)
{
long tendered = 0;
foreach (var b in w.Bids)
{
if (b.State == BidState.Open && b.Target == c.Id) tendered += b.TenderedPublic;
}
return Math.Max(0, c.Shares.Public - tendered);
}
/// <summary>
/// Fusione (12.2): il controllante liquida le minoranze al prezzo di mercato e assorbe attivi,
/// debiti e cassa della controllata, che cessa di esistere come impresa autonoma.
/// </summary>
public static void Merge(WorldContext ctx, Company parent, Company sub)
{
var w = ctx.World;
double price = sub.SharePrice;
// liquidazione delle minoranze: flottante e fondatore al mercato (conto Esterno), altre compagnie a sé
long external = sub.Shares.Public + sub.Shares.Founder;
PayFromParent(w, parent, Account.External, external * price);
for (int i = 0; i < sub.Shares.ByCompany.Length; i++)
{
long held = sub.Shares.ByCompany[i];
if (held == 0 || i == parent.Id.Value || i == sub.Id.Value) continue;
PayFromParent(w, parent, Account.Of(new CompanyId(i)), held * price);
sub.Shares.ByCompany[i] = 0;
}
TransferAssets(w, sub, parent);
sub.Merged = true;
sub.MergedInto = parent.Id;
sub.ControlledBy = CompanyId.None;
sub.Listed = false;
sub.Shares.Public = 0;
sub.Shares.Founder = 0;
sub.Shares.Treasury = 0;
Array.Clear(sub.Shares.ByCompany);
sub.Shares.Add(parent.Id, 0);
sub.Shares.ByCompany[parent.Id.Value] = sub.Shares.Total;
CloseBidsOn(w, sub.Id);
Milestone(w, parent, $"incorpora {sub.Name}");
Milestone(w, sub, $"incorporata da {parent.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"{parent.Name} incorpora {sub.Name}: rete, treni e debiti passano alla capogruppo", EntityKind.Company, sub.Id.Value, parent.Id));
}
private static void PayFromParent(World w, Company parent, Account to, double cents)
{
var amount = Money.FromCentsRounded(cents);
if (amount.Cents > 0) w.Money.Transfer(Account.Of(parent.Id), to, amount, LedgerEntry.Shares);
}
/// <summary>Passa a un'altra compagnia tutto ciò che appartiene a <paramref name="from"/>.</summary>
public static void TransferAssets(World w, Company from, Company to)
{
var net = w.Network;
foreach (var n in net.Nodes) if (n.Owner == from.Id) n.Owner = to.Id;
foreach (var e in net.Edges) if (e.Owner == from.Id) e.Owner = to.Id;
foreach (var s in net.Stations) if (s.Owner == from.Id) s.Owner = to.Id;
foreach (var d in net.Depots) if (d.Owner == from.Id) d.Owner = to.Id;
foreach (var p in net.Projects) if (p.Owner == from.Id) p.Owner = to.Id;
foreach (var v in w.Vehicles) if (v.Owner == from.Id) v.Owner = to.Id;
foreach (var t in w.Trains) if (t.Owner == from.Id) t.Owner = to.Id;
foreach (var l in w.Lines) if (l.Owner == from.Id) l.Owner = to.Id;
foreach (var i in w.Industries) if (i.Owner == from.Id) i.Owner = to.Id;
foreach (var c in w.Commutes) if (c.Carrier == from.Id) c.Carrier = to.Id;
foreach (var a in w.Agreements) if (a.Carrier == from.Id) a.Carrier = to.Id;
to.Loans.AddRange(from.Loans);
from.Loans.Clear();
// partecipazioni in altre compagnie
foreach (var other in w.Companies)
{
long held = other.Shares.Of(from.Id);
if (held == 0 || other.Id == from.Id) continue;
other.Shares.ByCompany[from.Id.Value] = 0;
if (other.Id == to.Id) other.Shares.Treasury += held; // azioni proprie riacquistate
else other.Shares.Add(to.Id, held);
}
if (from.Cash.Cents != 0) w.Money.Transfer(Account.Of(from.Id), Account.Of(to.Id), from.Cash, LedgerEntry.Other);
w.LineGraphs.Touch();
FinanceSystem.UpdateBookValues(w);
}
/// <summary>
/// Liquidazione senza compratori: i treni si fermano e si rottamano, le linee chiudono, i
/// pendolari perdono il vettore; binari e stazioni restano come rete abbandonata.
/// </summary>
public static void Liquidate(WorldContext ctx, Company c)
{
var w = ctx.World;
foreach (var t in w.Trains)
{
if (t.Owner != c.Id || t.Removed) continue;
TrainSystem.ReleaseAll(w.Network, t);
foreach (var p in t.Cargo)
{
if (p.Kind == PacketKind.Freight) w.Goods.Decayed[p.Good] += p.Units;
}
t.Cargo.Clear();
t.Removed = true;
t.Line = LineId.None;
}
foreach (var v in w.Vehicles)
{
if (v.Owner != c.Id || v.Sold) continue;
v.Sold = true;
}
foreach (var l in w.Lines)
{
if (l.Owner == c.Id) l.Removed = true;
}
foreach (var d in w.Network.Depots)
{
if (d.Owner != c.Id) continue;
d.Jobs.Clear();
}
foreach (var s in w.Network.Stations)
{
if (s.Owner != c.Id) continue;
foreach (var p in s.Waiting)
{
if (p.Kind == PacketKind.Freight) w.Goods.Decayed[p.Good] += p.Units;
}
s.Waiting.Clear();
Array.Clear(s.Incoming);
}
foreach (var com in w.Commutes)
{
if (com.Carrier == c.Id) com.Carrier = CompanyId.None;
}
foreach (var a in w.Agreements)
{
if (a.Carrier == c.Id && a.State <= AgreementState.Active) a.State = AgreementState.Broken;
}
c.Liquidated = true;
c.Listed = false;
w.LineGraphs.Touch();
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"{c.Name}: nessun compratore all'asta, treni rottamati e linee chiuse", EntityKind.Company, c.Id.Value, c.Id));
}
/// <summary>Chiude come fallite le offerte in corso che coinvolgono la compagnia.</summary>
public static void CloseBidsOn(World w, CompanyId company)
{
foreach (var b in w.Bids)
{
if (b.State != BidState.Open || (b.Target != company && b.Bidder != company)) continue;
b.State = BidState.Failed;
b.ClosedDay = w.Clock.Day;
}
}
/// <summary>Fine della partita del giocatore: la compagnia resta nel mondo, il giocatore diventa osservatore.</summary>
public static void EndGame(WorldContext ctx, GameOverReason reason, string text, CompanyId winner)
{
var w = ctx.World;
if (w.GameOver is not null) return;
w.GameOver = new GameOverState { Day = ctx.Day, Reason = reason, Text = text, Winner = winner };
Milestone(w, w.Player, $"fine della partita: {text}");
RecordYear(w, w.Player);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical, $"Fine della partita: {text}",
EntityKind.Company, w.Player.Id.Value, w.Player.Id));
}
/// <summary>
/// Il giocatore è passato sotto il controllo di un'IA (borsa o insolvenza): esito secondo la
/// difficoltà (12.3). Con «Apprendista» non succede mai.
/// </summary>
public static void PlayerTakenOver(WorldContext ctx, Company controller)
{
var w = ctx.World;
var player = w.Player;
var d = w.Difficulty;
switch (d.PlayerTakeover)
{
case TakeoverRule.Disabled:
return;
case TakeoverRule.Immediate:
EndGame(ctx, GameOverReason.Takeover, $"{controller.Name} ha preso il controllo di {player.Name}", controller.Id);
return;
default:
if (player.Receivership) return;
player.Receivership = true;
player.ReceivershipBy = controller.Id;
player.ReceivershipUntilDay = ctx.Day + (long)d.TakeoverRansomYears * w.Calendar.DaysPerYear;
Milestone(w, player, $"in amministrazione controllata da {controller.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{player.Name} in amministrazione controllata da {controller.Name}: dividendo obbligatorio del " +
$"{w.Data.Balance.StockMarket.ReceivershipDividend * 100:0} %, niente nuovi prestiti; {d.TakeoverRansomYears} anni per riacquistare il " +
$"{w.Data.Balance.StockMarket.RansomShare * 100:0} %", EntityKind.Company, player.Id.Value, player.Id));
return;
}
}
/// <summary>Annota la fotografia dell'anno in corso della compagnia (Cronaca finale).</summary>
public static void RecordYear(World w, Company c) => AddYear(w, c, Snapshot(w, c, w.Clock.Year, c.YearEntries));
/// <summary>Aggiunge (o sostituisce, se è lo stesso anno) una fotografia annuale nello storico.</summary>
public static void AddYear(World w, Company c, CompanyYear snapshot)
{
if (c.History.Count > 0 && c.History[^1].Year == snapshot.Year) c.History[^1] = snapshot;
else c.History.Add(snapshot);
int max = w.Data.Balance.StockMarket.HistoryYears;
while (c.History.Count > max) c.History.RemoveAt(0);
}
/// <summary>Fotografia di una compagnia con le voci del conto economico indicate.</summary>
public static CompanyYear Snapshot(World w, Company c, int year, long[] entries)
{
double km = 0;
foreach (var e in w.Network.Edges)
{
if (e.Owner == c.Id && e.State != EdgeState.Demolished) km += e.Length / 1000;
}
int trains = 0;
foreach (var t in w.Trains)
{
if (t.Owner == c.Id && !t.Removed) trains++;
}
return new CompanyYear(year, c.NetWorth.Cents, c.Cash.Cents, Company.Revenue(entries), Company.OperatingProfit(entries),
c.Tier, trains, km, (long)Math.Round(c.SharePrice));
}
/// <summary>Annota un fatto saliente nella storia della compagnia (al massimo 60, i più recenti).</summary>
public static void Milestone(World w, Company c, string text)
{
c.Milestones.Add(new CompanyMilestone(w.Clock.Day, text));
while (c.Milestones.Count > 60) c.Milestones.RemoveAt(0);
}
}
@@ -0,0 +1,280 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Comandi di borsa (12.2): quotazione, compravendita di azioni, dividendi, offerte pubbliche con le
/// difese del bersaglio, aste delle compagnie fallite e fusione delle controllate (ADR 0012).
/// </summary>
public static class CorporateCommandHandlers
{
public static CommandResult Ipo(World w, Company company, IpoCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (company.IsPlayer && !company.Listed && !Tiers.Unlocks(w, company).Ipo)
return reply(CommandError.TierLocked, "La quotazione si sblocca al livello «Grande compagnia»");
// prima quotazione fino a ipoMaxShare; per chi è già quotato un aumento di capitale fino al flottante massimo
double limit = company.Listed ? sm.SecondaryMaxFloat - (double)company.Shares.Public / company.Shares.Total : sm.IpoMaxShare;
if (!(c.FloatShare > 0) || c.FloatShare > limit + 1e-9)
return reply(CommandError.InvalidArgument, company.Listed
? $"Il flottante non può superare il {sm.SecondaryMaxFloat * 100:0} % del capitale"
: $"Si può offrire fino al {sm.IpoMaxShare * 100:0} % del capitale");
long shares = (long)Math.Round(company.Shares.Total * c.FloatShare);
shares = Math.Min(shares, company.Shares.Founder);
if (shares <= 0) return reply(CommandError.InvalidArgument, "Nessuna azione da offrire");
// il collocamento avviene al prezzo di denaro: il ricavato entra in cassa come aumento di capitale
company.SharePrice = Math.Max(company.SharePrice, Corporate.FundamentalPrice(w, company));
var proceeds = Money.FromCentsRounded(shares * Corporate.BidPrice(w, company));
company.Shares.Founder -= shares;
company.Shares.Public += shares;
bool first = !company.Listed;
company.Listed = true;
Corporate.Milestone(w, company, first ? $"si quota in borsa ({c.FloatShare * 100:0} %)" : $"aumento di capitale ({c.FloatShare * 100:0} %)");
w.Money.Transfer(Account.External, Account.Of(company.Id), proceeds, LedgerEntry.Shares);
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Opportunity,
first ? $"{company.Name} si quota in borsa: collocato il {c.FloatShare * 100:0} % per {proceeds}"
: $"{company.Name} colloca un altro {c.FloatShare * 100:0} % del capitale per {proceeds}",
EntityKind.Company, company.Id.Value, company.Id));
return reply(CommandError.None, $"Collocate {shares:N0} azioni per {proceeds}");
}
public static CommandResult BuyShares(World w, Company company, BuySharesCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Company, out var target) || target.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (c.Shares <= 0) return reply(CommandError.InvalidArgument, "Numero di azioni non valido");
long maxDaily = (long)(target.Shares.Total * sm.MaxDailyTradeShare);
if (c.Shares > maxDaily) return reply(CommandError.InvalidArgument, $"Al massimo {maxDaily:N0} azioni per ordine");
double ask = Corporate.Ask(w, target);
if (c.MaxPrice.Cents > 0 && ask > c.MaxPrice.Cents) return reply(CommandError.InvalidArgument, $"Prezzo di mercato {Money.FromCentsRounded(ask)} sopra il limite");
if (target.Id == company.Id) return Buyback(w, company, c.Shares, ask, reply);
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
long free = Corporate.FreeFloat(w, target);
if (free < c.Shares) return reply(CommandError.NotAllowed, $"Sul mercato ci sono solo {free:N0} azioni di {target.Name}");
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled
&& (double)(target.Shares.Of(company.Id) + c.Shares) / target.Shares.Outstanding > sm.ControlShare)
return reply(CommandError.NotAllowed, "Con questa difficoltà nessuno può controllare la compagnia del giocatore");
var cost = Money.FromCentsRounded(c.Shares * ask);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}");
w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= c.Shares;
target.Shares.Add(company.Id, c.Shares);
return reply(CommandError.None, $"Acquistate {c.Shares:N0} azioni di {target.Name} per {cost} ({target.Shares.FractionOf(company.Id) * 100:0.0} %)");
}
/// <summary>
/// Riacquisto di azioni proprie per conto del fondatore: dal flottante e, in amministrazione
/// controllata, dal controllante con il premio di riscatto (12.3).
/// </summary>
private static CommandResult Buyback(World w, Company company, long shares, double ask, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
long fromFloat = Math.Min(shares, Corporate.FreeFloat(w, company));
long fromController = 0;
if (company.Receivership && company.ReceivershipBy.IsValid)
fromController = Math.Min(shares - fromFloat, company.Shares.Of(company.ReceivershipBy));
if (fromFloat + fromController <= 0) return reply(CommandError.NotAllowed, "Nessuna azione propria disponibile da riacquistare");
double ransom = ask * (1 + sm.RansomPremium);
var costFloat = Money.FromCentsRounded(fromFloat * ask);
var costController = Money.FromCentsRounded(fromController * ransom);
if (company.Cash < costFloat + costController) return reply(CommandError.InsufficientFunds, $"Servono {costFloat + costController}");
if (fromFloat > 0)
{
w.Money.Transfer(Account.Of(company.Id), Account.External, costFloat, LedgerEntry.Shares);
company.Shares.Public -= fromFloat;
company.Shares.Founder += fromFloat;
}
if (fromController > 0)
{
w.Money.Transfer(Account.Of(company.Id), Account.Of(company.ReceivershipBy), costController, LedgerEntry.Shares);
company.Shares.ByCompany[company.ReceivershipBy.Value] -= fromController;
company.Shares.Founder += fromController;
}
return reply(CommandError.None,
$"Riacquistate {fromFloat + fromController:N0} azioni per {costFloat + costController}: il fondatore ha ora il {company.Shares.FounderFraction * 100:0.0} %");
}
public static CommandResult SellShares(World w, Company company, SellSharesCommand c, RailCommandHandlers.Reply reply)
{
if (!TryCompany(w, c.Company, out var target) || target.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (target.Id == company.Id) return reply(CommandError.NotAllowed, "Per collocare azioni proprie serve la quotazione");
if (c.Shares <= 0 || c.Shares > target.Shares.Of(company.Id)) return reply(CommandError.InvalidArgument, "Azioni insufficienti");
long maxDaily = (long)(target.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
if (c.Shares > maxDaily) return reply(CommandError.InvalidArgument, $"Al massimo {maxDaily:N0} azioni per ordine");
double bid = Corporate.BidPrice(w, target);
if (c.MinPrice.Cents > 0 && bid < c.MinPrice.Cents) return reply(CommandError.InvalidArgument, $"Prezzo di mercato {Money.FromCentsRounded(bid)} sotto il limite");
var proceeds = Money.FromCentsRounded(c.Shares * bid);
target.Shares.ByCompany[company.Id.Value] -= c.Shares;
target.Shares.Public += c.Shares;
w.Money.Transfer(Account.External, Account.Of(company.Id), proceeds, LedgerEntry.Shares);
return reply(CommandError.None, $"Vendute {c.Shares:N0} azioni di {target.Name} per {proceeds}");
}
public static CommandResult PayDividend(World w, Company company, PayDividendCommand c, RailCommandHandlers.Reply reply)
{
if (c.PerShare.Cents <= 0) return reply(CommandError.InvalidArgument, "Dividendo non valido");
var total = new Money(c.PerShare.Cents * company.Shares.Outstanding);
if (company.Cash < total) return reply(CommandError.InsufficientFunds, $"Servono {total}");
Dividends.Distribute(w, company, total);
return reply(CommandError.None, $"Distribuiti {total} di dividendi ({c.PerShare} per azione)");
}
public static CommandResult LaunchBid(World w, Company company, LaunchBidCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Target, out var target)) return reply(CommandError.NotFound, "Compagnia inesistente");
if (target.Id == company.Id) return reply(CommandError.InvalidArgument, "Non si può lanciare un'offerta su sé stessi");
// compagnia fallita: l'offerta è un'offerta all'asta degli attivi (prezzo × azioni)
var auction = w.Auctions.FirstOrDefault(a => a.Seller == target.Id && !a.Closed);
if (auction is not null) return AuctionBid(w, company, target, auction, c, reply);
if (target.Defunct) return reply(CommandError.NotAllowed, $"{target.Name} non è più attiva");
if (company.IsPlayer && !Tiers.Unlocks(w, company).HostileTakeover)
return reply(CommandError.TierLocked, "Le scalate ostili si sbloccano al livello «Impero ferroviario»");
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
return reply(CommandError.NotAllowed, "Con questa difficoltà la compagnia del giocatore non è scalabile");
if (target.ControlledBy == company.Id) return reply(CommandError.NotAllowed, $"{target.Name} è già controllata");
if (w.Bids.Any(b => b.State == BidState.Open && b.Target == target.Id))
return reply(CommandError.NotAllowed, $"C'è già un'offerta in corso su {target.Name}");
double premium = c.PricePerShare.Cents / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
if (premium < sm.BidPremiumMin - 1e-9 || premium > sm.BidPremiumMax + 1e-9)
return reply(CommandError.InvalidArgument,
$"Il premio deve stare tra il {sm.BidPremiumMin * 100:0} e il {sm.BidPremiumMax * 100:0} % sul prezzo di mercato ({Money.FromCentsRounded(target.SharePrice)})");
double current = target.Shares.FractionOf(company.Id);
if (!(c.TargetShare > current) || c.TargetShare > 1) return reply(CommandError.InvalidArgument, "Quota obiettivo non valida");
long needed = (long)Math.Ceiling(c.TargetShare * target.Shares.Outstanding) - target.Shares.Of(company.Id);
var cost = new Money(needed * c.PricePerShare.Cents);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost} per l'offerta");
var bid = new TakeoverBid
{
Id = new BidId(w.NextIds.Bid++),
Bidder = company.Id,
Target = target.Id,
PricePerShare = c.PricePerShare.Cents,
TargetShare = c.TargetShare,
StartDay = w.Clock.Day,
EndDay = w.Clock.Day + sm.BidDurationDays,
};
w.Bids.Add(bid);
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Critical,
$"{company.Name} lancia un'offerta pubblica su {target.Name}: {c.PricePerShare} per azione (+{premium * 100:0} %) fino al {c.TargetShare * 100:0} %",
EntityKind.Company, target.Id.Value, company.Id));
return reply(CommandError.None, $"Offerta lanciata su {target.Name} per {sm.BidDurationDays} giorni", bid.Id.Value);
}
private static CommandResult AuctionBid(World w, Company company, Company seller, Auction a, LaunchBidCommand c, RailCommandHandlers.Reply reply)
{
long offer = checked(c.PricePerShare.Cents * seller.Shares.Total);
if (offer < a.MinPriceCents) return reply(CommandError.InvalidArgument, $"Base d'asta {new Money(a.MinPriceCents)}");
if (offer <= a.BestPriceCents) return reply(CommandError.InvalidArgument, $"Serve più di {new Money(a.BestPriceCents)}");
if (company.Cash.Cents < offer) return reply(CommandError.InsufficientFunds, $"Servono {new Money(offer)}");
a.BestBidder = company.Id;
a.BestPriceCents = offer;
return reply(CommandError.None, $"Offerta di {new Money(offer)} per gli attivi di {seller.Name} (chiusura al giorno {a.EndDay})");
}
public static CommandResult RespondBid(World w, Company company, RespondBidCommand c, RailCommandHandlers.Reply reply)
{
var bid = w.Bids.FirstOrDefault(b => b.Id == c.Bid);
if (bid is null || bid.State != BidState.Open) return reply(CommandError.NotFound, "Offerta inesistente o conclusa");
var target = w.Company(bid.Target);
if (company.Id == bid.Target) return Defend(w, company, bid, c, reply);
if (company.Id == bid.Bidder) return reply(CommandError.NotAllowed, "L'offerente non può aderire alla propria offerta");
long held = target.Shares.Of(company.Id);
if (held <= 0) return reply(CommandError.NotAllowed, $"La compagnia non possiede azioni di {target.Name}");
if (!c.Accept)
{
bid.Accepted.Remove(company.Id);
return reply(CommandError.None, "Adesione ritirata");
}
if (!bid.Accepted.Contains(company.Id)) bid.Accepted.Add(company.Id);
return reply(CommandError.None, $"Aderito all'offerta con {held:N0} azioni di {target.Name}");
}
/// <summary>Difese del bersaglio (12.2): riacquisto, dividendo straordinario, cavaliere bianco.</summary>
private static CommandResult Defend(World w, Company target, TakeoverBid bid, RespondBidCommand c, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
switch (c.Defense)
{
case BidDefense.Buyback:
{
double ask = Corporate.Ask(w, target);
long free = Corporate.FreeFloat(w, target);
long affordable = (long)Math.Floor(Math.Max(0, target.Cash.Cents) / Math.Max(Corporate.MinPrice, ask));
long shares = Math.Min(free, affordable);
if (shares <= 0) return reply(CommandError.InsufficientFunds, "Nessuna azione riacquistabile con la cassa disponibile");
var cost = Money.FromCentsRounded(shares * ask);
w.Money.Transfer(Account.Of(target.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= shares;
target.Shares.Founder += shares;
bid.Defenses |= 1 << (int)BidDefense.Buyback;
return reply(CommandError.None, $"Riacquistate {shares:N0} azioni dal mercato per {cost}");
}
case BidDefense.ExtraDividend:
{
var total = Money.FromCentsRounded(Math.Max(0, target.Cash.Cents) * sm.ExtraDividendCashShare);
if (total.Cents <= 0) return reply(CommandError.InsufficientFunds, "Cassa insufficiente per un dividendo straordinario");
Dividends.Distribute(w, target, total);
target.ExtraSentiment += sm.ExtraDividendSentimentBoost;
bid.Defenses |= 1 << (int)BidDefense.ExtraDividend;
return reply(CommandError.None, $"Dividendo straordinario di {total}: il titolo diventa più caro");
}
case BidDefense.WhiteKnight:
{
if (!TryCompany(w, c.Knight, out var knight) || knight.Defunct || knight.Id == bid.Bidder || knight.Id == target.Id)
return reply(CommandError.InvalidArgument, "Cavaliere bianco non valido");
if (!knight.IsPlayer && w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == knight.AiPersonality)?.TargetsPlayer == true && target.IsPlayer)
return reply(CommandError.NotAllowed, $"{knight.Name} rifiuta di fare da cavaliere bianco");
double price = bid.PricePerShare * (1 + sm.WhiteKnightPremium);
long free = Corporate.FreeFloat(w, target);
long affordable = (long)Math.Floor(Math.Max(0, knight.Cash.Cents) / price);
long shares = Math.Min(free, affordable);
if (shares <= 0) return reply(CommandError.InsufficientFunds, $"{knight.Name} non ha cassa sufficiente");
var cost = Money.FromCentsRounded(shares * price);
w.Money.Transfer(Account.Of(knight.Id), Account.External, cost, LedgerEntry.Shares);
target.Shares.Public -= shares;
target.Shares.Add(knight.Id, shares);
bid.Knight = knight.Id;
bid.Defenses |= 1 << (int)BidDefense.WhiteKnight;
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Company, EventSeverity.Info,
$"{knight.Name} interviene come cavaliere bianco e compra {shares:N0} azioni di {target.Name}", EntityKind.Company, target.Id.Value, knight.Id));
return reply(CommandError.None, $"{knight.Name} compra {shares:N0} azioni dal mercato");
}
default:
bid.Defenses |= 1 << (int)BidDefense.None;
return reply(CommandError.None, "Offerta respinta: il consiglio invita gli azionisti a non aderire");
}
}
public static CommandResult MergeCompany(World w, Company company, MergeCompanyCommand c, WorldContext ctx, RailCommandHandlers.Reply reply)
{
var sm = w.Data.Balance.StockMarket;
if (!TryCompany(w, c.Subsidiary, out var sub) || sub.Defunct) return reply(CommandError.NotFound, "Compagnia inesistente");
if (sub.ControlledBy != company.Id) return reply(CommandError.NotAllowed, $"{sub.Name} non è controllata dalla compagnia");
if (w.Clock.Day - sub.ControlSinceDay < sm.MergeAfterDays)
return reply(CommandError.NotAllowed, $"La fusione è possibile dopo {sm.MergeAfterDays} giorni di controllo");
double minority = (sub.Shares.Outstanding - sub.Shares.Of(company.Id)) * sub.SharePrice;
if (company.Cash.Cents < minority) return reply(CommandError.InsufficientFunds, $"Servono {Money.FromCentsRounded(minority)} per liquidare le minoranze");
if (sub.IsPlayer && w.GameOver is null)
return reply(CommandError.NotAllowed, "La compagnia del giocatore non si può incorporare finché la partita è in corso");
Corporate.Merge(ctx, company, sub);
return reply(CommandError.None, $"{sub.Name} incorporata");
}
private static bool TryCompany(World w, CompanyId id, out Company c)
{
c = null!;
if (!id.IsValid || id.Value >= w.Companies.Count) return false;
c = w.Companies[id.Value];
return true;
}
}
@@ -0,0 +1,91 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation;
/// <summary>
/// Stimatori economici condivisi da IA e tooltip «perché» (12.1): ricavi per unità e per viaggio,
/// tempi di giro, costi di costruzione ed esercizio. Leggono solo informazioni pubbliche.
/// </summary>
public static class Estimators
{
/// <summary>Ricavo per unità di merce su <paramref name="km"/> al prezzo globale corrente (centesimi).</summary>
public static double FreightPerUnit(World w, int good, double km)
{
var t = w.Data.Balance.Tariffs;
double priceFactor = t.FreightFixedWeight + t.FreightPriceWeight * w.Market.GlobalPrice[good] / w.Data.Goods[good].BasePrice;
return t.FreightBaseRate * priceFactor * DMath.Pow(Math.Max(km, 0.1), t.FreightKmExponent) * w.Difficulty.TariffMultiplier;
}
/// <summary>Ricavo per passeggero su <paramref name="km"/> nella classe indicata (centesimi).</summary>
public static double PassengerPerTrip(World w, PaxClass cls, double km)
{
var t = w.Data.Balance.Tariffs;
double mult = t.ClassMultipliers[cls == PaxClass.Staff ? "staff" : "worker"];
return t.PaxBaseFare * DMath.Pow(Math.Max(km, 0.1), t.PaxKmExponent) * mult * w.Difficulty.TariffMultiplier;
}
/// <summary>Durata di un giro completo (andata e ritorno con le soste) in giorni di calendario.</summary>
public static double RoundTripDays(World w, double km, double maxSpeedKmh)
{
var p = w.Data.Ai.Planning;
double minutes = 2 * km / Math.Max(1, maxSpeedKmh * p.SpeedFactor) * 60 + 2 * p.DwellMinutes;
return w.Calendar.TrainMinutesToDays(minutes);
}
/// <summary>Costo d'esercizio annuo di un treno con la manutenzione stimata.</summary>
public static double TrainCostPerYear(World w, VehicleDef loco, VehicleDef car, int cars) =>
(loco.RunningCostPerYear + car.RunningCostPerYear * cars) * (1 + w.Data.Ai.Planning.MaintenanceCostShare);
public static long TrainPrice(VehicleDef loco, VehicleDef car, int cars) => loco.Price + car.Price * cars;
/// <summary>Costo di una stazione con i binari indicati per la compagnia.</summary>
public static long StationCost(World w, Company c, int platforms) =>
(long)((w.Data.Construction.Costs.StationBase + w.Data.Construction.Costs.StationPerPlatform * platforms) * RailCommandHandlers.CostMultiplier(w, c));
public static long DepotCost(World w, Company c, string size) =>
(long)(w.Data.Construction.Costs.DepotBySize[size] * RailCommandHandlers.CostMultiplier(w, c));
/// <summary>Costo di massima di un binario in linea d'aria (senza opere), per ordinare i candidati.</summary>
public static long RoughTrackCost(World w, Company c, double km) =>
(long)(w.Data.Construction.Costs.BasePerMeter * 1000 * km * RailCommandHandlers.CostMultiplier(w, c));
/// <summary>Locomotiva più recente non elettrica disponibile nell'anno.</summary>
public static VehicleDef? BestLocomotive(World w, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Locomotive || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (v.Traction is Traction.Electric or Traction.HighSpeed) continue;
if (best is null || v.EraFrom > best.EraFrom) best = v;
}
return best;
}
/// <summary>Carro più economico che trasporta il bene nell'anno.</summary>
public static VehicleDef? WagonFor(World w, int good, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Wagon || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (Array.IndexOf(v.GoodIndices, good) < 0) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
}
/// <summary>Carrozza della classe indicata disponibile nell'anno.</summary>
public static VehicleDef? CoachFor(World w, PaxClass cls, int year)
{
VehicleDef? best = null;
foreach (var v in w.Data.Vehicles)
{
if (v.Kind != VehicleKind.Coach || v.Class != cls || v.EraFrom > year || (v.EraTo is { } to && year > to)) continue;
if (best is null || v.Price < best.Price) best = v;
}
return best;
}
}
@@ -0,0 +1,111 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>Comandi delle industrie possedute (sezione 11): acquisto, budget, revisione, ammodernamento, ricambi.</summary>
public static class IndustryCommandHandlers
{
public static CommandResult BuyIndustry(World w, Company company, BuyIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!Tiers.Unlocks(w, company).BuyIndustry)
return reply(CommandError.TierLocked, "L'acquisto di industrie si sblocca al livello «Compagnia nazionale»");
if (!TryIndustry(w, c.Industry, out var ind) || ind.Closed) return reply(CommandError.NotFound, "Industria inesistente");
if (ind.Owner == company.Id) return reply(CommandError.NotAllowed, $"{ind.Name} è già della compagnia");
if (ind.Owner.IsValid) return reply(CommandError.NotAllowed, $"{ind.Name} appartiene a {w.Company(ind.Owner).Name}");
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva e non è in vendita");
var price = IndustryMath.Valuation(w, ind);
if (c.Offer < price) return reply(CommandError.InvalidArgument, $"Offerta troppo bassa: i proprietari chiedono almeno {price}");
if (company.Cash < c.Offer) return reply(CommandError.InsufficientFunds, "Cassa insufficiente");
w.Money.Transfer(Account.Of(company.Id), Account.External, c.Offer, LedgerEntry.IndustryPurchase);
ind.Owner = company.Id;
ind.AcquiredDay = w.Clock.Day;
ind.MonthsHighMargin = 0;
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.Industry, EventSeverity.Info,
$"{company.Name} acquista {ind.Name} per {c.Offer}", EntityKind.Industry, ind.Id.Value, company.Id));
return reply(CommandError.None, $"{ind.Name} acquistata per {c.Offer}", ind.Id.Value);
}
public static CommandResult SetPolicy(World w, Company company, SetIndustryPolicyCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (c.Budget > IndustryBudget.High) return reply(CommandError.InvalidArgument, "Budget non valido");
ind.Budget = c.Budget;
var b = w.Data.Balance.IndustryMaintenance.For(c.Budget);
return reply(CommandError.None,
$"{ind.Name}: budget {BudgetName(c.Budget)} (recupero {b.RecoveryPerDay:0.00} punti al giorno, {b.CostShareOfRevenue * 100:0} % dei ricavi, {b.SparePartsPerLevelPerMonth * ind.Level} ricambi al mese)");
}
public static CommandResult Overhaul(World w, Company company, OverhaulIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva");
if (ind.IsStopped(w.Clock.Day)) return reply(CommandError.NotAllowed, $"{ind.Name} è già ferma");
if (ind.PendingWork != IndustryWork.None) return reply(CommandError.NotAllowed, $"{ind.Name} ha già un lavoro programmato");
var m = w.Data.Balance.IndustryMaintenance;
ind.PendingWork = IndustryWork.Overhaul;
int need = IndustryMath.MachineryRequired(ind, m);
return reply(CommandError.None,
$"{ind.Name}: revisione programmata ({m.OverhaulDays} giorni di fermo); servono {need} macchinari (in scorta {ind.Machinery}) e personale almeno all'{m.OverhaulMinStaffCoverage * 100:0} %");
}
public static CommandResult Upgrade(World w, Company company, UpgradeIndustryCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
if (ind.Level <= 0) return reply(CommandError.NotAllowed, $"{ind.Name} è inattiva");
if (ind.Level >= w.Data.Balance.Growth.MaxLevel) return reply(CommandError.NotAllowed, $"{ind.Name} è già al livello massimo");
if (ind.IsStopped(w.Clock.Day)) return reply(CommandError.NotAllowed, $"{ind.Name} è ferma");
if (ind.PendingWork != IndustryWork.None) return reply(CommandError.NotAllowed, $"{ind.Name} ha già un lavoro programmato");
var cost = IndustryMaintenanceSystem.UpgradeCost(ind);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost} per l'ammodernamento");
var m = w.Data.Balance.IndustryMaintenance;
ind.PendingWork = IndustryWork.Upgrade;
int need = IndustryMath.MachineryRequired(ind, m);
return reply(CommandError.None,
$"{ind.Name}: ammodernamento al livello {ind.Level + 1} programmato ({cost}, {m.UpgradeDays} giorni); servono {need} macchinari (in scorta {ind.Machinery})");
}
public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply)
{
if (!TryOwned(w, company, c.Industry, out var ind, out var error)) return reply(error.Error, error.Message);
int max = w.Data.Balance.IndustryMaintenance.MaxOrderedParts;
if (c.Quantity < 0 || c.Quantity > max) return reply(CommandError.InvalidArgument, $"Ordine tra 0 e {max} unità");
ind.PartsOrdered = c.Quantity;
string unit = w.Data.Goods[w.Data.SparePartsGood].Unit;
return reply(CommandError.None,
$"{ind.Name}: ordinati {c.Quantity} {unit} di ricambi oltre la scorta della politica (scorta attuale {ind.SpareParts})");
}
public static string BudgetName(IndustryBudget b) => b switch
{
IndustryBudget.None => "Nessuno",
IndustryBudget.High => "Alto",
_ => "Base",
};
private static bool TryIndustry(World w, IndustryId id, out Industry ind)
{
ind = null!;
if (!id.IsValid || id.Value >= w.Industries.Count) return false;
ind = w.Industries[id.Value];
return true;
}
private static bool TryOwned(World w, Company company, IndustryId id, out Industry ind, out (CommandError Error, string Message) error)
{
error = default;
if (!TryIndustry(w, id, out ind) || ind.Closed)
{
error = (CommandError.NotFound, "Industria inesistente");
return false;
}
if (ind.Owner != company.Id)
{
error = (CommandError.NotAllowed, "L'industria non appartiene alla compagnia");
return false;
}
return true;
}
}
@@ -3,6 +3,8 @@ using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
/// <summary>Creazione e collocazione delle industrie durante la partita (nascita per domanda insoddisfatta).</summary>
@@ -47,6 +49,10 @@ public static class IndustryPlacer
ind.OutputStock[o] = units;
w.Goods.Produced[def.Recipe.Outputs[o].GoodIndex] += units;
}
// scorta iniziale di ricambi per la manutenzione degli impianti (sezione 11)
var im = w.Data.Balance.IndustryMaintenance;
ind.SpareParts = (int)Math.Round(IndustryMath.MonthlyPartsUse(ind, im) * im.InitialPartsMonths);
w.Goods.Produced[w.Data.SparePartsGood] += ind.SpareParts;
w.Money.Transfer(Account.External, Account.Of(ind.Id), new Money(ib.StartingCash), LedgerEntry.Other);
MarkFootprint(w, cellX, cellY, footprint, CellType.Industry);
return ind;
@@ -90,6 +90,7 @@ public static class MaintenanceCommandHandlers
public static CommandResult OrderParts(World w, Company company, OrderPartsCommand c, RailCommandHandlers.Reply reply)
{
if (c.Industry.IsValid) return IndustryCommandHandlers.OrderParts(w, company, c, reply);
if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count) return reply(CommandError.NotFound, "Deposito inesistente");
var d = w.Network.Depots[c.Depot.Value];
if (d.Owner != company.Id || !w.Network.IsAlive(d)) return reply(CommandError.NotFound, "Deposito inesistente");
@@ -14,6 +14,8 @@ public sealed class ScenarioFile
public required ulong Seed { get; init; }
public int StartYear { get; set; } = 1850;
public string Difficulty { get; set; } = "imprenditore";
/// <summary>Numero di concorrenti IA (sostituisce quello della difficoltà; null = come la difficoltà).</summary>
public int? AiCompetitors { get; set; }
public required ScenarioTerrain Terrain { get; init; }
public List<ScenarioTown> Towns { get; set; } = [];
public List<ScenarioIndustry> Industries { get; set; } = [];
@@ -104,6 +104,9 @@ public static class ScenarioLoader
StartYear = file.StartYear,
DifficultyId = file.Difficulty,
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
DifficultyOverride = file.AiCompetitors is { } ai
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), [("aiCompetitors", ai)])
: null,
};
var world = WorldFactory.FromMap(data, map, settings);
if (file.Player?.Cash is { } cash)
@@ -1,4 +1,5 @@
using System.Diagnostics;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Core.Simulation;
@@ -35,9 +36,12 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
new DemandSystem(),
new EmploymentSystem(),
new IndustrySystem(),
new IndustryMaintenanceSystem(),
new TownSystem(),
new MarketSystem(),
new FinanceSystem(),
new StockMarketSystem(),
new AiSystem(),
new HashSystem(),
]);
@@ -4,8 +4,9 @@ using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo) e input
/// richiesti dalle industrie al loro potenziale di lavoro. Alimenta D del mercato.
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo), input
/// richiesti dalle industrie al loro potenziale di lavoro e ricambi per gli impianti.
/// Alimenta D del mercato.
/// </summary>
public sealed class DemandSystem : ISimSystem
{
@@ -30,6 +31,7 @@ public sealed class DemandSystem : ISimSystem
}
int dpm = w.Calendar.DaysPerMonth;
var im = data.Balance.IndustryMaintenance;
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0)
@@ -37,6 +39,8 @@ public sealed class DemandSystem : ISimSystem
Array.Clear(ind.InputDemandToday);
continue;
}
// ricambi per la manutenzione degli impianti (sezione 11)
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
@@ -21,7 +21,7 @@ public sealed class FinanceSystem : ISimSystem
PayRunningCosts(w);
foreach (var c in w.Companies)
{
if (c.Bankrupt) continue;
if (c.Defunct) continue;
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
{
@@ -35,8 +35,14 @@ public sealed class FinanceSystem : ISimSystem
UpdateBookValues(w);
foreach (var c in w.Companies)
{
if (c.Merged) continue;
if (!c.Bankrupt) PayLoans(w, c);
c.Rating = ComputeRating(w, c);
if (!c.Bankrupt) Tiers.Evaluate(ctx, c);
// utile del mese chiuso nell'anello dei 12 mesi (borsa, 12.2); il nuovo mese parte senza dividendi
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
c.DividendRing[c.ProfitRingIndex] = 0;
Array.Clear(c.MonthEntries);
}
}
@@ -72,7 +78,7 @@ public sealed class FinanceSystem : ISimSystem
}
for (int i = 0; i < w.Companies.Count; i++)
{
if (_running[i] <= 0 || w.Companies[i].Bankrupt) continue;
if (_running[i] <= 0 || w.Companies[i].Defunct) continue;
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
}
}
@@ -0,0 +1,236 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Manutenzione degli impianti (guida, sezione 11): usura giornaliera con l'utilizzo, recupero e
/// costo del budget del proprietario, consumo mensile di ricambi, fermi per guasto e incidenti,
/// revisioni e ammodernamenti che aspettano i macchinari, decisioni dei proprietari privati e
/// conguaglio mensile della cassa delle industrie possedute da una compagnia (ADR 0011).
/// </summary>
public sealed class IndustryMaintenanceSystem : ISimSystem
{
public string Name => "IndustryMaintenance";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
var m = w.Data.Balance.IndustryMaintenance;
var rng = w.Stream("industry-maintenance");
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
Daily(ctx, ind, m, rng);
}
if (ctx.IsNewMonth && ctx.Day > 0)
{
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
ConsumeParts(w, ind, m);
if (!ind.Owner.IsValid) NpcOwner(w, ind, m);
else SettleWithOwner(w, ind, m);
}
}
if (ctx.IsNewYear)
{
foreach (var ind in w.Industries) ind.MaintenanceSpentYear = 0;
}
}
private static void Daily(WorldContext ctx, Industry ind, IndustryMaintenanceBalance m, Rng rng)
{
var w = ctx.World;
if (ind.StoppedUntilDay >= 0 && !ind.IsStopped(ctx.Day)) EndStop(ctx, ind);
if (ind.PendingWork != IndustryWork.None && !ind.IsStopped(ctx.Day)) TryStartWork(ctx, ind, m);
if (ind.Level <= 0) return;
// usura con l'utilizzo e recupero del budget (dimezzato senza ricambi)
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1.0);
ind.Condition = Math.Clamp(ind.Condition - wear + recovery, 0, 100);
// costo del budget: quota dei ricavi medi giornalieri
if (budget.CostShareOfRevenue > 0 && ind.RevenueEma > 0)
{
var cost = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
ind.PurchasesToday += cost.Cents;
ind.MaintenanceSpentYear += cost.Cents;
}
// rischio di fermo sotto la soglia
if (ind.IsStopped(ctx.Day) || ind.Condition >= m.BreakdownPivot) return;
double hazard = m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
if (rng.NextDouble() >= hazard) return;
var town = NearestTown(w, ind, m.TownEffectRadiusKm);
if (ind.Condition < m.AccidentBelow && ind.Def.Kind != IndustryKind.Primary)
{
Stop(w, ind, IndustryStop.Accident, m.AccidentDays, m);
string where = "";
if (town is not null)
{
int lost = (int)Math.Round(town.Population * m.AccidentPopulationLoss);
town.Population = Math.Max(0, town.Population - lost);
where = $"; {town.Name} perde {lost} abitanti";
}
ctx.Emit(EventKind.Industry, EventSeverity.Critical,
$"Incidente grave a {ind.Name}: impianti fermi per {m.AccidentDays} giorni{where}", EntityKind.Industry, ind.Id.Value);
return;
}
int days = m.BreakdownDays[0] + rng.NextInt(m.BreakdownDays[1] - m.BreakdownDays[0] + 1);
Stop(w, ind, IndustryStop.Breakdown, days, m);
if (town is not null)
{
for (int c = 0; c < Town.CategoryCount; c++)
town.Satisfaction[c] = Math.Max(0, town.Satisfaction[c] - m.BreakdownTownSatisfaction);
}
ctx.Emit(EventKind.Industry, EventSeverity.Warning,
$"Guasto agli impianti di {ind.Name} (condizione {ind.Condition:0}): fermo di {days} giorni", EntityKind.Industry, ind.Id.Value);
}
/// <summary>Ferma l'industria per i giorni indicati e lo annota nello storico.</summary>
public static void Stop(World w, Industry ind, IndustryStop kind, int days, IndustryMaintenanceBalance m)
{
long today = w.Clock.Day;
ind.StoppedUntilDay = Math.Max(ind.StoppedUntilDay, today + days);
ind.StopKind = kind;
ind.StopHistory.Add(new IndustryStopRecord(today, days, kind));
while (ind.StopHistory.Count > m.StopHistoryLength) ind.StopHistory.RemoveAt(0);
}
private static void EndStop(WorldContext ctx, Industry ind)
{
var kind = ind.StopKind;
ind.StoppedUntilDay = -1;
ind.StopKind = IndustryStop.None;
switch (kind)
{
case IndustryStop.Overhaul:
ind.Condition = 100;
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: revisione conclusa, impianti come nuovi", EntityKind.Industry, ind.Id.Value);
break;
case IndustryStop.Upgrade:
int max = ctx.World.Data.Balance.Growth.MaxLevel;
ind.Level = Math.Min(max, ind.Level + 1);
ind.Condition = Math.Max(ind.Condition, 100);
ctx.Emit(EventKind.Industry, EventSeverity.Opportunity, $"{ind.Name}: ammodernamento concluso, ora al livello {ind.Level}", EntityKind.Industry, ind.Id.Value);
break;
}
}
/// <summary>Avvia la revisione o l'ammodernamento quando ci sono macchinari, personale e cassa.</summary>
private static void TryStartWork(WorldContext ctx, Industry ind, IndustryMaintenanceBalance m)
{
var w = ctx.World;
int machinery = IndustryMath.MachineryRequired(ind, m);
if (ind.Machinery < machinery) return;
if (ind.PendingWork == IndustryWork.Overhaul)
{
if (ind.CovStaff < m.OverhaulMinStaffCoverage) return;
ConsumeMachinery(w, ind, machinery);
ind.PendingWork = IndustryWork.None;
Stop(w, ind, IndustryStop.Overhaul, m.OverhaulDays, m);
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: inizia la revisione programmata ({m.OverhaulDays} giorni)", EntityKind.Industry, ind.Id.Value);
return;
}
if (ind.Level >= w.Data.Balance.Growth.MaxLevel)
{
ind.PendingWork = IndustryWork.None;
return;
}
var cost = UpgradeCost(ind);
var payer = ind.Owner.IsValid ? Account.Of(ind.Owner) : Account.Of(ind.Id);
var cash = ind.Owner.IsValid ? w.Company(ind.Owner).Cash : ind.Cash;
if (cash < cost) return;
w.Money.Transfer(payer, Account.External, cost, ind.Owner.IsValid ? LedgerEntry.IndustryPurchase : LedgerEntry.Other);
ConsumeMachinery(w, ind, machinery);
ind.PendingWork = IndustryWork.None;
Stop(w, ind, IndustryStop.Upgrade, m.UpgradeDays, m);
ctx.Emit(EventKind.Industry, EventSeverity.Info, $"{ind.Name}: inizia l'ammodernamento al livello {ind.Level + 1} ({m.UpgradeDays} giorni)", EntityKind.Industry, ind.Id.Value);
}
/// <summary>Costo in capitale dell'ammodernamento al livello successivo.</summary>
public static Money UpgradeCost(Industry ind) => new(ind.Def.UpgradeCost * Math.Max(1, ind.Level));
private static void ConsumeMachinery(World w, Industry ind, int units)
{
ind.Machinery -= units;
w.Goods.Consumed[w.Data.MachineryGood] += units;
}
/// <summary>Consumo mensile di ricambi della politica: senza scorta sufficiente il recupero si dimezza.</summary>
private static void ConsumeParts(World w, Industry ind, IndustryMaintenanceBalance m)
{
int need = IndustryMath.MonthlyPartsUse(ind, m);
int used = Math.Min(need, ind.SpareParts);
ind.SpareParts -= used;
w.Goods.Consumed[w.Data.SparePartsGood] += used;
ind.PartsShort = used < need;
if (ind.PartsOrdered > 0)
{
// i ricambi ordinati arrivati restano in scorta: l'ordine si riduce di quanto consegnato
int target = IndustryMath.PartsTarget(ind, m);
if (ind.SpareParts >= target) ind.PartsOrdered = 0;
}
}
/// <summary>Proprietario privato (NPC): budget dal margine, revisione sotto soglia, ammodernamento se conviene.</summary>
private static void NpcOwner(World w, Industry ind, IndustryMaintenanceBalance m)
{
double margin = ind.Margin;
ind.Budget = margin > m.NpcHighMargin ? IndustryBudget.High : margin < 0 ? IndustryBudget.None : IndustryBudget.Base;
ind.MonthsHighMargin = margin > m.NpcUpgradeMargin ? ind.MonthsHighMargin + 1 : 0;
if (ind.PendingWork != IndustryWork.None || ind.IsStopped(w.Clock.Day) || ind.Level <= 0) return;
double machineryPrice = w.Market.GlobalPrice[w.Data.MachineryGood];
if (ind.Condition < m.NpcOverhaulBelow)
{
double cost = machineryPrice * m.OverhaulMachineryPerLevel * ind.Level;
if (ind.Cash.Cents >= cost) ind.PendingWork = IndustryWork.Overhaul;
return;
}
if (ind.MonthsHighMargin >= m.NpcUpgradeYears * w.Calendar.MonthsPerYear && ind.Level < w.Data.Balance.Growth.MaxLevel
&& ind.SpareParts >= IndustryMath.PartsTarget(ind, m) && !ind.PartsShort)
{
double cost = machineryPrice * m.UpgradeMachineryPerLevel * ind.Level + UpgradeCost(ind).Cents;
if (ind.Cash.Cents >= cost)
{
ind.PendingWork = IndustryWork.Upgrade;
ind.MonthsHighMargin = 0;
}
}
}
/// <summary>
/// Industria di una compagnia: trattiene la cassa di riserva e versa il resto al proprietario,
/// che ne copre le perdite (voce «Industrie» del conto economico).
/// </summary>
private static void SettleWithOwner(World w, Industry ind, IndustryMaintenanceBalance m)
{
var owner = w.Company(ind.Owner);
long delta = ind.Cash.Cents - m.OwnerCashReserve;
if (delta > 0) w.Money.Transfer(Account.Of(ind.Id), Account.Of(owner.Id), new Money(delta), LedgerEntry.Industries);
else if (delta < 0 && !owner.Bankrupt) w.Money.Transfer(Account.Of(owner.Id), Account.Of(ind.Id), new Money(-delta), LedgerEntry.Industries);
}
/// <summary>Città più vicina entro il raggio (al bordo), o null.</summary>
public static Town? NearestTown(World w, Industry ind, double radiusKm)
{
Town? best = null;
double bestKm = radiusKm;
foreach (var t in w.Towns)
{
double km = w.TownEdgeDistanceKm(t, ind.Position);
if (km <= bestKm)
{
bestKm = km;
best = t;
}
}
return best;
}
}
@@ -1,3 +1,4 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
@@ -36,4 +37,63 @@ public static class IndustryMath
double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle;
return (int)Math.Ceiling(perDay * ind.Def.StorageDays);
}
/// <summary>Ricambi consumati al mese dalla politica corrente: unità per livello.</summary>
public static int MonthlyPartsUse(Industry ind, IndustryMaintenanceBalance m) =>
ind.Level <= 0 || ind.Closed ? 0 : m.For(ind.Budget).SparePartsPerLevelPerMonth * ind.Level;
/// <summary>Scorta di ricambi desiderata: mesi di consumo della politica più quanto ordinato dal proprietario.</summary>
public static int PartsTarget(Industry ind, IndustryMaintenanceBalance m) =>
ind.Closed ? 0 : (int)Math.Ceiling(MonthlyPartsUse(ind, m) * m.PartsTargetMonths) + ind.PartsOrdered;
/// <summary>Macchinari richiesti dal lavoro programmato (revisione o ammodernamento).</summary>
public static int MachineryRequired(Industry ind, IndustryMaintenanceBalance m) => ind.PendingWork switch
{
IndustryWork.Overhaul => m.OverhaulMachineryPerLevel * Math.Max(1, ind.Level),
IndustryWork.Upgrade => m.UpgradeMachineryPerLevel * Math.Max(1, ind.Level),
_ => 0,
};
/// <summary>
/// Bisogno di ricambi o macchinari per la manutenzione degli impianti (domanda esplicita: scorta
/// desiderata − scorta); 0 per gli altri beni e per le industrie chiuse.
/// </summary>
public static int ServiceNeed(World w, Industry ind, int good)
{
if (ind.Closed) return 0;
var m = w.Data.Balance.IndustryMaintenance;
if (good == w.Data.SparePartsGood) return Math.Max(0, PartsTarget(ind, m) - ind.SpareParts);
if (good == w.Data.MachineryGood) return Math.Max(0, MachineryRequired(ind, m) - ind.Machinery);
return 0;
}
/// <summary>Riceve ricambi o macchinari pagandoli al prezzo indicato; restituisce le unità prese.</summary>
public static int ReceiveService(World w, Industry ind, int good, int units, double unitPrice)
{
int take = Math.Min(units, ServiceNeed(w, ind, good));
if (take <= 0) return 0;
if (good == w.Data.SparePartsGood) ind.SpareParts += take;
else ind.Machinery += take;
var cost = Common.Money.FromCentsRounded(take * unitPrice);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
ind.PurchasesToday += cost.Cents;
ind.MaintenanceSpentYear += cost.Cents;
ind.LastServedDay = w.Clock.Day;
return take;
}
/// <summary>Utile annuo stimato dell'industria (ricavi − costi medi giornalieri × giorni dell'anno).</summary>
public static double AnnualProfit(World w, Industry ind) => (ind.RevenueEma - ind.CostEma) * w.Calendar.DaysPerYear;
/// <summary>
/// Prezzo di vendita di un'industria: quota del costo cumulato degli impianti (pesato dalla
/// condizione) + multiplo dell'utile annuo positivo + cassa dell'impresa.
/// </summary>
public static Common.Money Valuation(World w, Industry ind)
{
var p = w.Data.Balance.IndustryMaintenance.Purchase;
double plant = ind.Def.UpgradeCost * Math.Max(1, ind.Level) * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
double earnings = Math.Max(0, AnnualProfit(w, ind)) * p.EarningsMultiple;
return Common.Money.FromCentsRounded(plant + earnings + Math.Max(0, ind.Cash.Cents));
}
}
@@ -42,6 +42,9 @@ public sealed class IndustrySystem : ISimSystem
double pf = IndustryMath.ProfitFactor(ind, ib);
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * pf * mc;
// fermo per guasto, incidente, revisione o ammodernamento: nessuna produzione (sezione 11)
bool stopped = ind.IsStopped(ctx.Day);
if (stopped) eLabor = 0;
// giacimento: sotto la soglia la capacità cala linearmente, a zero l'industria chiude
double depletion = 1.0;
@@ -58,7 +61,7 @@ public sealed class IndustrySystem : ISimSystem
}
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
for (int o = 0; o < recipe.Outputs.Count; o++)
for (int o = 0; o < recipe.Outputs.Count && !stopped; o++)
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
// copertura degli input di oggi: limita la produzione alle scorte disponibili
@@ -53,8 +53,17 @@ public sealed class LocalTransportSystem : ISimSystem
{
if (available <= 0) break;
var consumer = w.Industries[ci];
if (consumer.Closed) continue;
int serviced = IndustryMath.ReceiveService(w, consumer, good, available, w.Market.GlobalPrice[good]);
if (serviced > 0)
{
producer.OutputStock[o] -= serviced;
available -= serviced;
Sell(w, producer, o, serviced, sellPrice);
if (available <= 0) break;
}
int i = consumer.InputIndexOf(good);
if (i < 0 || consumer.Closed) continue;
if (i < 0) continue;
int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
int units = Math.Min(available, free);
if (units <= 0) continue;
@@ -102,6 +111,8 @@ public sealed class LocalTransportSystem : ISimSystem
{
if (consumer.Closed || hub.RemainingCapacity <= 0) continue;
if (Vec2.Distance(hub.Position, consumer.Position) > lt.RadiusKm * 1000) continue;
ImportService(w, hub, consumer, w.Data.SparePartsGood, lt);
ImportService(w, hub, consumer, w.Data.MachineryGood, lt);
var inputs = consumer.Def.Recipe.Inputs;
for (int i = 0; i < inputs.Count; i++)
{
@@ -119,6 +130,17 @@ public sealed class LocalTransportSystem : ISimSystem
}
}
/// <summary>Un hub vicino vende ricambi o macchinari a un'industria che ne ha bisogno (sezione 11).</summary>
private static void ImportService(World w, Hub hub, Industry consumer, int good, LocalTransportBalance lt)
{
int units = Math.Min(Math.Min(lt.MaxUnitsPerDay, IndustryMath.ServiceNeed(w, consumer, good)), hub.RemainingCapacity);
if (units <= 0) return;
units = IndustryMath.ReceiveService(w, consumer, good, units, hub.SellPrice(w.Market.GlobalPrice[good]));
hub.UsedThisMonth += units;
hub.ImportedThisMonth[good] += units;
w.Goods.Imported[good] += units;
}
private static void Sell(World w, Industry producer, int outputIndex, int units, double unitPrice)
{
var amount = Money.FromCentsRounded(units * unitPrice);
@@ -37,10 +37,47 @@ public sealed class StationSystem : ISimSystem
foreach (var s in net.Stations)
{
if (net.Nodes[s.Node.Value].Station != s.Id || !LoadsHere(w, s)) continue;
LocalService(w, s, w.Data.SparePartsGood);
LocalService(w, s, w.Data.MachineryGood);
CollectFreight(ctx, s);
}
}
/// <summary>
/// Trasbordo nel bacino (ADR 0011): una stazione servita passa ricambi e macchinari dai produttori
/// e dagli hub del suo bacino alle officine e alle industrie dello stesso bacino, senza treno.
/// </summary>
private static void LocalService(World w, Station s, int good)
{
if (ServiceNeed(w, s, good) <= 0) return;
foreach (var id in s.Industries)
{
var producer = w.Industries[id.Value];
int o = producer.OutputIndexOf(good);
if (producer.Closed || o < 0 || producer.OutputStock[o] <= 0) continue;
int offered = producer.OutputStock[o];
int sold = offered - StationWork.DeliverService(w, s, good, offered, w.Market.GlobalPrice[good]);
if (sold <= 0) continue;
producer.OutputStock[o] -= sold;
var sale = Money.FromCentsRounded(sold * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.External, Account.Of(producer.Id), sale, LedgerEntry.Other);
producer.SalesToday += sale.Cents;
producer.LastServedDay = w.Clock.Day;
if (o == 0) producer.ShippedToday += sold;
}
foreach (var id in s.Hubs)
{
var hub = w.Hubs[id.Value];
int units = Math.Min(ServiceNeed(w, s, good), hub.RemainingCapacity);
if (units <= 0) continue;
int delivered = units - StationWork.DeliverService(w, s, good, units, hub.SellPrice(w.Market.GlobalPrice[good]));
if (delivered <= 0) continue;
hub.UsedThisMonth += delivered;
hub.ImportedThisMonth[good] += delivered;
w.Goods.Imported[good] += delivered;
}
}
private static bool LoadsHere(World w, Station s)
{
foreach (var line in w.Lines)
@@ -131,17 +168,21 @@ public sealed class StationSystem : ISimSystem
if (o == 0) ind.ShippedToday += units;
}
}
if (s.Hubs.Count > 0) ImportSpareParts(ctx, s, graph);
if (s.Hubs.Count > 0)
{
ImportServiceGood(ctx, s, graph, w.Data.SparePartsGood);
ImportServiceGood(ctx, s, graph, w.Data.MachineryGood);
}
}
/// <summary>
/// Un hub nel bacino importa i ricambi richiesti dalle officine raggiungibili sulle linee (10.2):
/// li spedisce verso la stazione con più bisogno, entro la capacità mensile dell'hub.
/// Un hub nel bacino importa ricambi e macchinari richiesti dalle officine e dalle industrie
/// raggiungibili sulle linee (10.2, 11): li spedisce verso la stazione con più bisogno, entro la
/// capacità mensile dell'hub.
/// </summary>
private void ImportSpareParts(WorldContext ctx, Station s, LineGraph graph)
private void ImportServiceGood(WorldContext ctx, Station s, LineGraph graph, int good)
{
var w = ctx.World;
int good = w.Data.SparePartsGood;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) return;
_candidates.Clear();
@@ -152,7 +193,7 @@ public sealed class StationSystem : ISimSystem
foreach (var (sid, _) in _candidates)
{
var dest = w.Network.Stations[sid];
int need = DepotNeed(w, dest) - dest.Incoming[good];
int need = ServiceNeed(w, dest, good) - dest.Incoming[good];
if (need <= bestNeed) continue;
bestNeed = need;
best = reach[sid];
@@ -187,6 +228,14 @@ public sealed class StationSystem : ISimSystem
}
}
/// <summary>Ricambi o macchinari mancanti a officine e industrie nel bacino della stazione.</summary>
private static int ServiceNeed(World w, Station s, int good)
{
int need = good == w.Data.SparePartsGood ? DepotNeed(w, s) : 0;
foreach (var id in s.Industries) need += IndustryMath.ServiceNeed(w, w.Industries[id.Value], good);
return need;
}
/// <summary>Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta).</summary>
private static int DepotNeed(World w, Station s)
{
@@ -217,8 +266,15 @@ public sealed class StationSystem : ISimSystem
foreach (var id in dest.Industries)
{
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
int service = IndustryMath.ServiceNeed(w, ind, good);
if (service > 0)
{
consumer = true;
need += service;
}
int i = ind.InputIndexOf(good);
if (i < 0 || ind.Closed) continue;
if (i < 0) continue;
consumer = true;
need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
}
@@ -206,6 +206,9 @@ public static class StationWork
if (units <= 0) return 0;
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
// ricambi e macchinari per gli impianti (sezione 11)
units -= IndustryMath.ReceiveService(w, ind, good, units, w.Market.GlobalPrice[good]);
if (units <= 0) return 0;
int i = ind.InputIndexOf(good);
if (i < 0) continue;
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
@@ -261,6 +264,34 @@ public static class StationWork
return units;
}
/// <summary>
/// Consegna ricambi o macchinari solo alle officine e alle industrie del bacino che ne hanno
/// bisogno (manutenzione); le industrie pagano <paramref name="industryPrice"/>, le officine il
/// prezzo globale. Restituisce le unità rimaste.
/// </summary>
public static int DeliverService(World w, Station s, int good, int units, double industryPrice)
{
foreach (var id in s.Industries)
{
if (units <= 0) return 0;
units -= IndustryMath.ReceiveService(w, w.Industries[id.Value], good, units, industryPrice);
}
if (good != w.Data.SparePartsGood) return units;
foreach (var id in s.Depots)
{
if (units <= 0) return 0;
var depot = w.Network.Depots[id.Value];
if (!w.Network.IsAlive(depot)) continue;
int take = Math.Min(units, Math.Max(0, depot.PartsTarget - depot.SpareParts));
if (take <= 0) continue;
depot.SpareParts += take;
units -= take;
var cost = Money.FromCentsRounded(take * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.Of(depot.Owner), Account.External, cost, LedgerEntry.FleetMaintenance);
}
return units;
}
// ------------------------------------------------------------------ carico
/// <summary>Carica i pacchetti in attesa che viaggiano sulla linea del treno; restituisce le unità caricate.</summary>
@@ -0,0 +1,424 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Borsa e vita societaria (12.1–12.3), una volta al giorno: prezzi e sentiment, valore delle
/// partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate,
/// amministrazione controllata del giocatore, fallimenti con asta degli attivi, storico annuale
/// e nuovi concorrenti quando il mercato è troppo concentrato (ADR 0012).
/// </summary>
public sealed class StockMarketSystem : ISimSystem
{
public string Name => "StockMarket";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
UpdatePrices(w, ctx);
UpdatePortfolios(w);
ProcessBids(ctx);
UpdateControl(ctx);
HandleBankruptcies(ctx);
ProcessAuctions(ctx);
Receivership(ctx);
if (ctx.IsNewMonth && ctx.Day > 0)
{
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
c.PriceHistory.Add(c.SharePrice);
while (c.PriceHistory.Count > w.Data.Balance.StockMarket.PriceHistoryMonths) c.PriceHistory.RemoveAt(0);
PaySubsidiaryProfit(w, c);
}
}
if (ctx.IsNewYear && ctx.Day > 0)
{
foreach (var c in w.Companies)
{
if (c.Merged) continue;
RecordPreviousYear(w, c);
c.LastAnnualProfit = c.AnnualProfit;
}
NewCompetitors(ctx);
}
w.Bids.RemoveAll(b => b.State != BidState.Open && ctx.Day - b.ClosedDay > w.Data.Balance.StockMarket.BidDurationDays);
}
// ------------------------------------------------------------------ prezzi
private static void UpdatePrices(World w, WorldContext ctx)
{
var sm = w.Data.Balance.StockMarket;
var mb = w.Data.Balance.Market;
double years = (double)ctx.Day / w.Calendar.DaysPerYear;
double cycle = mb.World.Amplitude * w.Difficulty.MarketVolatilityMultiplier * DMath.Sin(DMath.TwoPi * years / mb.World.PeriodYears);
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double fundamental = Corporate.FundamentalPrice(w, c);
long annual = c.AnnualProfit;
double baseline = Math.Max(Math.Max(Math.Abs(c.LastAnnualProfit), c.NetWorth.Cents * 0.05), 1);
double growth = Math.Clamp((annual - c.LastAnnualProfit) / baseline, -1, 1);
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
double cap = Math.Max(1, fundamental * c.Shares.Outstanding);
double yield = Math.Clamp(dividends / cap, 0, 0.5);
double target = 1 + sm.SentimentEarningsWeight * growth + sm.SentimentCycleWeight * cycle + sm.SentimentDividendWeight * yield + c.ExtraSentiment;
target = Math.Clamp(target, sm.SentimentMin, sm.SentimentMax);
c.Sentiment = Ema.Step(c.Sentiment, target, sm.SentimentSmoothingDays);
c.ExtraSentiment = Math.Max(0, c.ExtraSentiment - sm.ExtraDividendSentimentBoost / sm.ExtraDividendDecayDays);
c.SharePrice = Math.Max(Corporate.MinPrice, fundamental * c.Sentiment);
}
}
private static void UpdatePortfolios(World w)
{
foreach (var holder in w.Companies)
{
double value = 0;
foreach (var c in w.Companies)
{
if (c.Id == holder.Id || c.Defunct) continue;
long held = c.Shares.Of(holder.Id);
if (held > 0) value += held * c.SharePrice;
}
holder.PortfolioValue = Money.FromCentsRounded(value);
}
}
// ------------------------------------------------------------------ offerte pubbliche
private static void ProcessBids(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
foreach (var bid in w.Bids)
{
if (bid.State != BidState.Open) continue;
var target = w.Company(bid.Target);
var bidder = w.Company(bid.Bidder);
if (target.Defunct || bidder.Defunct)
{
Close(w, bid, BidState.Failed);
continue;
}
// il flottante aderisce in proporzione al premio sul prezzo di mercato
double premium = bid.PricePerShare / Math.Max(Corporate.MinPrice, target.SharePrice) - 1;
double rate = premium <= 0 ? 0 : sm.TenderDailyShare * Math.Clamp(premium / sm.BidPremiumMin, 0, 2);
long free = Corporate.FreeFloat(w, target);
long tender = (long)Math.Ceiling(free * rate);
bid.TenderedPublic += Math.Min(free, tender);
// il proprietario privato di un'IA vende tutto solo a un premio molto alto
if (!target.IsPlayer && bid.TenderedFounder == 0 && premium >= w.Data.Ai.Market.FounderAcceptPremium)
bid.TenderedFounder = target.Shares.Founder;
if (Committed(w, bid) >= Needed(bid, target)) Settle(ctx, bid);
else if (ctx.Day >= bid.EndDay)
{
Close(w, bid, BidState.Failed);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"Offerta di {bidder.Name} su {target.Name} scaduta: adesioni insufficienti", EntityKind.Company, target.Id.Value, bidder.Id));
}
}
}
/// <summary>Azioni che l'offerente avrebbe a esito positivo: già sue + adesioni.</summary>
public static long Committed(World w, TakeoverBid bid)
{
var target = w.Company(bid.Target);
long sum = target.Shares.Of(bid.Bidder) + bid.TenderedPublic + bid.TenderedFounder;
foreach (var holder in bid.Accepted) sum += target.Shares.Of(holder);
return sum;
}
/// <summary>Azioni da raggiungere: la quota obiettivo delle azioni in circolazione.</summary>
public static long Needed(TakeoverBid bid, Company target) =>
(long)Math.Ceiling(bid.TargetShare * target.Shares.Outstanding);
private static void Settle(WorldContext ctx, TakeoverBid bid)
{
var w = ctx.World;
var target = w.Company(bid.Target);
var bidder = w.Company(bid.Bidder);
long bought = bid.TenderedPublic + bid.TenderedFounder;
foreach (var holder in bid.Accepted) bought += target.Shares.Of(holder);
var cost = Money.FromCentsRounded((double)bought * bid.PricePerShare);
if (bidder.Cash < cost)
{
Close(w, bid, BidState.Failed);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"Offerta di {bidder.Name} su {target.Name} fallita: cassa insufficiente al pagamento", EntityKind.Company, target.Id.Value, bidder.Id));
return;
}
var price = (double)bid.PricePerShare;
long fromMarket = bid.TenderedPublic + bid.TenderedFounder;
w.Money.Transfer(Account.Of(bidder.Id), Account.External, Money.FromCentsRounded(fromMarket * price), LedgerEntry.Shares);
target.Shares.Public -= bid.TenderedPublic;
target.Shares.Founder -= bid.TenderedFounder;
target.Shares.Add(bidder.Id, fromMarket);
foreach (var holder in bid.Accepted)
{
long held = target.Shares.Of(holder);
if (held <= 0) continue;
w.Money.Transfer(Account.Of(bidder.Id), Account.Of(holder), Money.FromCentsRounded(held * price), LedgerEntry.Shares);
target.Shares.ByCompany[holder.Value] = 0;
target.Shares.Add(bidder.Id, held);
}
Close(w, bid, BidState.Succeeded);
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{bidder.Name} conclude l'offerta su {target.Name}: ora possiede il {target.Shares.FractionOf(bidder.Id) * 100:0.0} %",
EntityKind.Company, target.Id.Value, bidder.Id));
}
private static void Close(World w, TakeoverBid bid, BidState state)
{
bid.State = state;
bid.ClosedDay = w.Clock.Day;
}
// ------------------------------------------------------------------ controllo
private static void UpdateControl(WorldContext ctx)
{
var w = ctx.World;
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
var controller = Corporate.Controller(w, c);
if (controller == c.ControlledBy) continue;
c.ControlledBy = controller;
c.ControlSinceDay = controller.IsValid ? ctx.Day : -1;
if (!controller.IsValid) continue;
var parent = w.Company(controller);
Corporate.Milestone(w, parent, $"prende il controllo di {c.Name}");
Corporate.Milestone(w, c, $"passa sotto il controllo di {parent.Name}");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"{parent.Name} prende il controllo di {c.Name}", EntityKind.Company, c.Id.Value, parent.Id));
if (c.IsPlayer) Corporate.PlayerTakenOver(ctx, parent);
}
}
/// <summary>La controllata versa al controllante la sua quota dell'utile operativo del mese chiuso.</summary>
private static void PaySubsidiaryProfit(World w, Company c)
{
if (!c.ControlledBy.IsValid || c.Bankrupt) return;
int last = (c.ProfitRingIndex + 11) % 12;
long profit = c.ProfitRing[last];
if (profit <= 0) return;
var amount = Money.FromCentsRounded(profit * c.Shares.FractionOf(c.ControlledBy));
amount = Money.Min(amount, Money.Max(Money.Zero, c.Cash));
if (amount.Cents <= 0) return;
// per la controllata è una distribuzione (dividendo), per il controllante un ricavo del gruppo
w.Money.Transfer(Account.Of(c.Id), Account.External, amount, LedgerEntry.Dividends);
w.Money.Transfer(Account.External, Account.Of(c.ControlledBy), amount, LedgerEntry.Subsidiaries);
}
// ------------------------------------------------------------------ amministrazione controllata (12.3)
private static void Receivership(WorldContext ctx)
{
var w = ctx.World;
var player = w.Player;
if (!player.Receivership || w.GameOver is not null) return;
var sm = w.Data.Balance.StockMarket;
if (player.Shares.FounderFraction >= sm.RansomShare)
{
player.Receivership = false;
player.ReceivershipBy = CompanyId.None;
player.ReceivershipUntilDay = -1;
Corporate.Milestone(w, player, "esce dall'amministrazione controllata");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"{player.Name} esce dall'amministrazione controllata: il fondatore ha di nuovo il {player.Shares.FounderFraction * 100:0} %",
EntityKind.Company, player.Id.Value, player.Id));
return;
}
if (ctx.Day >= player.ReceivershipUntilDay)
{
var by = player.ReceivershipBy.IsValid ? w.Company(player.ReceivershipBy) : null;
Corporate.EndGame(ctx, GameOverReason.ReceivershipExpired,
$"scaduti i termini per il riscatto: {player.Name} passa definitivamente a {by?.Name ?? "un concorrente"}", player.ReceivershipBy);
return;
}
// dividendo obbligatorio: a ogni trimestre la quota dell'utile del trimestre va agli azionisti
if (ctx.IsNewQuarter && ctx.Day > 0)
{
long quarter = 0;
for (int k = 1; k <= 3; k++) quarter += player.ProfitRing[(player.ProfitRingIndex + 12 - k) % 12];
if (quarter <= 0) return;
var total = Money.FromCentsRounded(quarter * sm.ReceivershipDividend);
total = Money.Min(total, Money.Max(Money.Zero, player.Cash));
if (total.Cents > 0) Dividends.Distribute(w, player, total);
}
}
// ------------------------------------------------------------------ fallimenti e aste
private static void HandleBankruptcies(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
foreach (var c in w.Companies)
{
if (!c.Bankrupt || c.Merged || c.BankruptDay >= 0) continue;
c.BankruptDay = ctx.Day;
Corporate.CloseBidsOn(w, c.Id);
if (c.IsPlayer)
{
PlayerInsolvency(ctx, c);
continue;
}
FinanceSystem.UpdateBookValues(w);
long min = (long)(c.AssetBookValue.Cents * sm.AuctionMinBookShare);
w.Auctions.Add(new Auction { Seller = c.Id, StartDay = ctx.Day, EndDay = ctx.Day + sm.AuctionDays, MinPriceCents = Math.Max(1, min) });
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"Asta degli attivi di {c.Name}: base d'asta {new Money(Math.Max(1, min))}, chiusura tra {sm.AuctionDays} giorni",
EntityKind.Company, c.Id.Value, c.Id));
}
}
/// <summary>
/// Insolvenza del giocatore (12.3): i creditori vendono la compagnia al miglior offerente tra le IA
/// (che ne salda i debiti e ne prende il controllo); senza compratori o con «Apprendista» la partita finisce.
/// </summary>
private static void PlayerInsolvency(WorldContext ctx, Company player)
{
var w = ctx.World;
if (w.Difficulty.PlayerTakeover == TakeoverRule.Disabled || w.GameOver is not null)
{
Corporate.EndGame(ctx, GameOverReason.Bankruptcy, $"{player.Name} fallisce dopo {player.NegativeCashDays} giorni di cassa negativa", CompanyId.None);
return;
}
long price = Math.Max(0, player.Debt.Cents - player.Cash.Cents);
Company? buyer = null;
foreach (var c in w.Companies)
{
if (c.IsPlayer || c.Defunct || c.Cash.Cents < price) continue;
if (buyer is null || c.Cash > buyer.Cash) buyer = c;
}
if (buyer is null)
{
Corporate.EndGame(ctx, GameOverReason.Bankruptcy, $"{player.Name} fallisce: nessun concorrente rileva i debiti", CompanyId.None);
return;
}
// il compratore salda i debiti, riporta la cassa a zero e riceve tutte le azioni
foreach (var loan in player.Loans)
{
w.Money.Transfer(Account.Of(buyer.Id), Account.External, loan.Remaining, LedgerEntry.Shares);
}
player.Loans.Clear();
if (player.Cash.IsNegative) w.Money.Transfer(Account.Of(buyer.Id), Account.Of(player.Id), -player.Cash, LedgerEntry.Shares);
var shares = player.Shares;
shares.Founder = 0;
shares.Public = 0;
shares.Treasury = 0;
Array.Clear(shares.ByCompany);
shares.Add(buyer.Id, shares.Total);
player.Bankrupt = false;
player.BankruptDay = -1;
player.NegativeCashDays = 0;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Critical,
$"I creditori vendono {player.Name} a {buyer.Name}, che ne salda i debiti", EntityKind.Company, player.Id.Value, buyer.Id));
player.ControlledBy = buyer.Id;
player.ControlSinceDay = ctx.Day;
Corporate.PlayerTakenOver(ctx, buyer);
}
private static void ProcessAuctions(WorldContext ctx)
{
var w = ctx.World;
foreach (var a in w.Auctions)
{
if (a.Closed || ctx.Day < a.EndDay) continue;
a.Closed = true;
var seller = w.Company(a.Seller);
if (a.BestBidder.IsValid && !w.Company(a.BestBidder).Defunct && w.Company(a.BestBidder).Cash.Cents >= a.BestPriceCents)
{
var buyer = w.Company(a.BestBidder);
// il prezzo va ai creditori: i debiti del fallito si estinguono, gli attivi passano al compratore
w.Money.Transfer(Account.Of(buyer.Id), Account.External, new Money(a.BestPriceCents), LedgerEntry.IndustryPurchase);
seller.Loans.Clear();
if (seller.Cash.IsNegative) w.Money.Transfer(Account.External, Account.Of(seller.Id), -seller.Cash, LedgerEntry.Other);
Corporate.TransferAssets(w, seller, buyer);
seller.Merged = true;
seller.MergedInto = buyer.Id;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Info,
$"{buyer.Name} si aggiudica all'asta gli attivi di {seller.Name} per {new Money(a.BestPriceCents)}", EntityKind.Company, seller.Id.Value, buyer.Id));
}
else
{
Corporate.Liquidate(ctx, seller);
}
}
w.Auctions.RemoveAll(a => a.Closed && ctx.Day - a.EndDay > w.Data.Balance.StockMarket.AuctionDays);
}
// ------------------------------------------------------------------ storico e concorrenza
private static void RecordPreviousYear(World w, Company c) =>
Corporate.AddYear(w, c, Corporate.Snapshot(w, c, w.Clock.Year - 1, c.LastYearEntries));
/// <summary>
/// Nuovi concorrenti (12.1): se una compagnia supera la soglia di concentrazione dei ricavi
/// dell'anno, entra una nuova IA (al massimo una ogni pochi anni e fino al numero massimo).
/// </summary>
private static void NewCompetitors(WorldContext ctx)
{
var w = ctx.World;
var sm = w.Data.Balance.StockMarket;
if (ctx.Year - w.LastCompetitorYear < sm.NewCompetitorCooldownYears) return;
int active = 0;
long total = 0, best = 0;
Company? leader = null;
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
active++;
long r = Company.Revenue(c.LastYearEntries);
total += r;
if (r > best)
{
best = r;
leader = c;
}
}
if (leader is null || total <= 0 || active >= sm.MaxCompanies || w.Companies.Count >= sm.MaxCompanies * 2) return;
double share = (double)best / total;
if (share <= sm.ConcentrationThreshold) return;
var entrant = WorldFactory.CreateAiCompany(w, w.Stream("companies"));
w.LastCompetitorYear = ctx.Year;
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Warning,
$"Entra nel mercato {entrant.Name}: {leader.Name} controlla il {share * 100:0} % dei trasporti", EntityKind.Company, entrant.Id.Value, entrant.Id));
}
}
/// <summary>Distribuzione dei dividendi agli azionisti (12.2).</summary>
public static class Dividends
{
/// <summary>
/// Paga <paramref name="total"/> agli azionisti in proporzione alle azioni in circolazione:
/// fondatore e flottante ricevono dal conto Esterno, le compagnie azioniste in cassa.
/// </summary>
public static void Distribute(World w, Company payer, Money total)
{
var shares = payer.Shares;
long outstanding = shares.Outstanding;
if (outstanding <= 0 || total.Cents <= 0) return;
double perShare = (double)total.Cents / outstanding;
long paid = 0;
for (int i = 0; i < shares.ByCompany.Length; i++)
{
long held = shares.ByCompany[i];
if (held <= 0 || i == payer.Id.Value) continue;
var amount = Money.FromCentsRounded(held * perShare);
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends);
paid += amount.Cents;
}
var rest = new Money(total.Cents - paid);
if (rest.Cents > 0) w.Money.Transfer(Account.Of(payer.Id), Account.External, rest, LedgerEntry.Dividends);
payer.DividendRing[payer.ProfitRingIndex] += total.Cents;
}
}
@@ -0,0 +1,77 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Livelli della compagnia (tiers.json): ogni mese, dopo il rating, una compagnia che soddisfa i
/// requisiti del livello successivo (patrimonio netto, città collegate sopra una popolazione,
/// rating) sale di un livello. Il livello non scende: gli sblocchi restano acquisiti (ADR 0011).
/// </summary>
public static class Tiers
{
/// <summary>Sblocchi del livello attuale della compagnia.</summary>
public static TierUnlocks Unlocks(World w, Company c) =>
w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1].Unlocks;
/// <summary>Promuove la compagnia se soddisfa i requisiti del livello successivo.</summary>
public static void Evaluate(WorldContext ctx, Company c)
{
var w = ctx.World;
var tiers = w.Data.Tiers.Tiers;
while (c.Tier < tiers.Count && Meets(w, c, tiers[c.Tier].Requirements))
{
var next = tiers[c.Tier];
c.Tier = next.Level;
Corporate.Milestone(w, c, $"diventa «{next.NameIt}»");
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
$"{c.Name} diventa «{next.NameIt}» (livello {next.Level})", EntityKind.Company, c.Id.Value, c.Id));
}
}
/// <summary>Requisiti di un livello soddisfatti dalla compagnia.</summary>
public static bool Meets(World w, Company c, TierRequirements req) =>
c.NetWorth.Cents >= req.NetWorth
&& c.Rating <= req.CreditRating
&& ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population) >= req.ConnectedTownsOver.Count;
/// <summary>
/// Città con almeno <paramref name="minPopulation"/> abitanti collegate dalla compagnia: nel bacino
/// di una sua stazione fermata di una linea con almeno un treno.
/// </summary>
public static int ConnectedTowns(World w, CompanyId company, int minPopulation)
{
var served = ServedStations(w, company);
var towns = new bool[w.Towns.Count];
int count = 0;
foreach (var s in w.Network.Stations)
{
if (s.Owner != company || !served[s.Id.Value] || !w.Network.IsAlive(s)) continue;
foreach (var t in s.Towns)
{
if (towns[t.Value] || w.Towns[t.Value].Population < minPopulation) continue;
towns[t.Value] = true;
count++;
}
}
return count;
}
/// <summary>Stazioni della compagnia fermate di una linea con almeno un treno assegnato.</summary>
public static bool[] ServedStations(World w, CompanyId company)
{
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (t.Owner == company && t.Line.IsValid && !t.Removed) lineHasTrain[t.Line.Value] = true;
}
var served = new bool[w.Network.Stations.Count];
foreach (var l in w.Lines)
{
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
foreach (var stop in l.Stops) served[stop.Station.Value] = true;
}
return served;
}
}
+20
View File
@@ -60,6 +60,24 @@ public sealed class World
/// <summary>Convenzioni di pendolarismo (proposte, attive e concluse di recente).</summary>
public List<CommuteAgreement> Agreements { get; } = [];
/// <summary>Offerte pubbliche di acquisto (in corso e concluse di recente).</summary>
public List<TakeoverBid> Bids { get; } = [];
/// <summary>Aste degli attivi delle compagnie fallite.</summary>
public List<Auction> Auctions { get; } = [];
/// <summary>Fine della partita del giocatore (null finché gioca): poi si osserva il mondo.</summary>
public GameOverState? GameOver { get; set; }
/// <summary>Stato degli agenti delle compagnie IA, in ordine di compagnia.</summary>
public List<Ai.AiState> AiStates { get; } = [];
/// <summary>Agenti IA sospesi (le compagnie IA esistono ma non agiscono): test e scenari didattici.</summary>
public bool AiPaused { get; set; }
/// <summary>Ultimo anno in cui è entrato un nuovo concorrente (12.1).</summary>
public int LastCompetitorYear { get; set; } = int.MinValue;
/// <summary>Rete ferroviaria di tutte le compagnie.</summary>
public RailNetwork Network { get; } = new();
public List<Vehicle> Vehicles { get; } = [];
@@ -181,6 +199,8 @@ public sealed class World
}
foreach (var ind in Industries)
{
if (good == Data.SparePartsGood) sum += ind.SpareParts;
if (good == Data.MachineryGood) sum += ind.Machinery;
int i = ind.InputIndexOf(good);
if (i >= 0) sum += ind.InputStock[i];
int o = ind.OutputIndexOf(good);
+31 -18
View File
@@ -116,25 +116,38 @@ public static class WorldFactory
};
w.Companies.Add(player);
w.Money.Transfer(Account.External, Account.Of(player.Id), new Money(d.InitialCapital), LedgerEntry.Other);
Corporate.InitShares(w, player, d.PublicFromStart, d.PublicFromStart ? d.PlayerShareAtStart : 1.0);
var names = data.Ai.CompanyNames.ToList();
for (int i = 0; i < d.AiCompetitors; i++)
for (int i = 0; i < d.AiCompetitors; i++) CreateAiCompany(w, rng);
}
/// <summary>
/// Crea una compagnia IA con nome e personalità estratti dal flusso indicato, capitale e fido
/// della difficoltà (× capitale IA) e flottante iniziale in borsa (12.1–12.2).
/// </summary>
public static Company CreateAiCompany(World w, Rng rng)
{
var data = w.Data;
var d = w.Difficulty;
var used = new HashSet<string>(w.Companies.Select(c => c.Name), StringComparer.Ordinal);
var names = data.Ai.CompanyNames.Where(n => !used.Contains(n)).ToList();
int aiIndex = w.Companies.Count(c => !c.IsPlayer);
string name = names.Count > 0 ? names[rng.NextInt(names.Count)] : $"Compagnia {aiIndex + 1}";
var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)];
var ai = new Company
{
string name = names.Count > 0 ? names[rng.NextInt(names.Count)] : $"Compagnia {i + 1}";
names.Remove(name);
var personality = data.Ai.Personalities[rng.NextInt(data.Ai.Personalities.Count)];
var ai = new Company
{
Id = new CompanyId(w.Companies.Count),
Name = name,
IsPlayer = false,
AiPersonality = personality.Id,
Color = data.Ai.Colors[i % data.Ai.Colors.Count],
BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier,
Rating = data.Balance.Finance.StartingRating,
};
w.Companies.Add(ai);
w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
}
Id = new CompanyId(w.Companies.Count),
Name = name,
IsPlayer = false,
AiPersonality = personality.Id,
Color = data.Ai.Colors[aiIndex % data.Ai.Colors.Count],
BaseCredit = new Money(d.InitialCredit) * d.AiCapitalMultiplier,
Rating = data.Balance.Finance.StartingRating,
FoundedDay = w.Clock.Day,
};
w.Companies.Add(ai);
w.Money.Transfer(Account.External, Account.Of(ai.Id), new Money(d.InitialCapital) * d.AiCapitalMultiplier, LedgerEntry.Other);
Corporate.InitShares(w, ai, listed: true, 1 - data.Balance.StockMarket.AiFloatAtStart);
return ai;
}
}
@@ -41,6 +41,15 @@ public sealed class ClientWorld(GameData data)
public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
public EmploymentReport? Employment { get; private set; }
/// <summary>Dati della F5: listino di borsa, schede di compagnie e industrie, Cronaca finale.</summary>
public MarketTape? Tape { get; private set; }
public Dictionary<int, CompanyCard> CompanyCards { get; } = [];
public Dictionary<int, IndustryCard> IndustryCards { get; } = [];
public Chronicle? Chronicle { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
/// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
public List<MaintenanceAlert> Alerts { get; } = [];
private const int AlertCapacity = 50;
@@ -102,6 +111,22 @@ public sealed class ClientWorld(GameData data)
Employment = m;
DetailVersion++;
return true;
case MarketTape m:
Tape = m;
TapeVersion++;
return true;
case CompanyCard m:
CompanyCards[m.Company] = m;
DetailVersion++;
return true;
case IndustryCard m:
IndustryCards[m.Industry] = m;
DetailVersion++;
return true;
case Chronicle m:
Chronicle = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -117,6 +142,10 @@ public sealed class ClientWorld(GameData data)
Cards.Clear();
Workshops.Clear();
Employment = null;
Tape = null;
CompanyCards.Clear();
IndustryCards.Clear();
Chronicle = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
+28 -2
View File
@@ -160,10 +160,26 @@ public static class CommandCodec
w.String(c.Objective);
w.Money(c.Budget);
break;
case MergeCompanyCommand c: w.I32(c.Subsidiary.Value); break;
default:
throw new ProtocolException($"comando senza codifica: {command.Type}");
}
w.Flags(0);
// blocco 1 (F5): industria destinataria dei ricambi, difesa del bersaglio di un'offerta
switch (command)
{
case OrderPartsCommand c when c.Industry.IsValid:
w.Flags(1);
w.I32(c.Industry.Value);
break;
case RespondBidCommand c when c.Defense != BidDefense.None || c.Knight.IsValid:
w.Flags(1);
w.U8((byte)c.Defense);
w.I32(c.Knight.Value);
break;
default:
w.Flags(0);
break;
}
}
public static GameCommand Read(CommandType type, ref SpanReader r)
@@ -208,9 +224,19 @@ public static class CommandCodec
CommandType.AcceptContract => new AcceptContractCommand(new ContractId(r.I32())),
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), r.String(), r.Money()),
CommandType.MergeCompany => new MergeCompanyCommand(new CompanyId(r.I32())),
_ => throw new ProtocolException($"tipo di comando sconosciuto: {(ushort)type}"),
};
r.Flags();
byte flags = r.Flags();
if ((flags & 1) != 0)
{
c = c switch
{
OrderPartsCommand op => op with { Industry = new IndustryId(r.I32()) },
RespondBidCommand rb => rb with { Defense = Enum<BidDefense>(r.U8(), 3), Knight = new CompanyId(r.I32()) },
_ => c,
};
}
return c;
}
+6
View File
@@ -31,6 +31,12 @@ public enum MessageId : ushort
MaintenanceCard = 124,
/// <summary>Registro officina di un deposito (F4).</summary>
WorkshopRegister = 125,
/// <summary>Scheda di una compagnia: soci, storico, prezzi (F5).</summary>
CompanyCard = 126,
/// <summary>Scheda del proprietario di un'industria: manutenzione, fermi, valore (F5).</summary>
IndustryCard = 127,
/// <summary>Cronaca finale della partita del giocatore (F5).</summary>
Chronicle = 128,
CommandResult = 130,
Notification = 131,
Newspaper = 132,
@@ -231,6 +231,12 @@ public enum DetailKind : byte
Workshop = 2,
/// <summary>Registro degli impieghi della compagnia (risposta EmploymentReport; Id ignorato).</summary>
Employment = 3,
/// <summary>Scheda di una compagnia (risposta CompanyCard, F5).</summary>
Company = 4,
/// <summary>Scheda del proprietario di un'industria (risposta IndustryCard, F5).</summary>
Industry = 5,
/// <summary>Cronaca finale (risposta Chronicle, F5; Id ignorato).</summary>
Chronicle = 6,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,266 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol.Messages;
// Messaggi della fase F5: scheda di una compagnia (soci e storico), scheda del proprietario di
// un'industria, Cronaca finale. Arrivano solo su richiesta (RequestDetail) o, la Cronaca, alla fine
// della partita del giocatore.
/// <summary>Quota di un titolare nel libro dei soci (Holder = id compagnia, −1 fondatore, −2 mercato).</summary>
public sealed class HoldingInfo
{
public const int Founder = -1;
public const int Market = -2;
public int Holder { get; init; }
public long Shares { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Holder); w.I64(Shares);
w.Flags(0);
}
public static HoldingInfo Read(ref SpanReader r)
{
var m = new HoldingInfo { Holder = r.I32(), Shares = r.I64() };
r.Flags();
return m;
}
}
/// <summary>Anno di storia di una compagnia (grafici della scheda e della Cronaca).</summary>
public sealed class CompanyYearInfo
{
public int Year { get; init; }
public Money NetWorth { get; init; }
public Money Cash { get; init; }
public Money Revenue { get; init; }
public Money Profit { get; init; }
public byte Tier { get; init; }
public int Trains { get; init; }
public float TrackKm { get; init; }
public Money SharePrice { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Year); w.Money(NetWorth); w.Money(Cash); w.Money(Revenue); w.Money(Profit); w.U8(Tier); w.I32(Trains); w.F32(TrackKm); w.Money(SharePrice);
w.Flags(0);
}
public static CompanyYearInfo Read(ref SpanReader r)
{
var m = new CompanyYearInfo
{
Year = r.I32(), NetWorth = r.Money(), Cash = r.Money(), Revenue = r.Money(), Profit = r.Money(), Tier = r.U8(), Trains = r.I32(),
TrackKm = r.F32(), SharePrice = r.Money(),
};
r.Flags();
return m;
}
}
/// <summary>Scheda di una compagnia (borsa e controllo, 12.2).</summary>
public sealed class CompanyCard : IMessage
{
public MessageId Id => MessageId.CompanyCard;
public int Company { get; init; }
public long TotalShares { get; init; }
public long Treasury { get; init; }
public List<HoldingInfo> Holdings { get; init; } = [];
/// <summary>Prezzo dell'azione a fine mese (centesimi), il più recente in coda.</summary>
public List<double> PriceHistory { get; init; } = [];
public List<CompanyYearInfo> History { get; init; } = [];
public Money AnnualProfit { get; init; }
public Money DividendsYear { get; init; }
public Money Debt { get; init; }
public Money MarketCap { get; init; }
/// <summary>Giorni di controllo da parte del titolare di maggioranza (−1 se nessuno).</summary>
public long ControlDays { get; init; } = -1;
/// <summary>Asta in corso degli attivi (compagnia fallita): base, miglior offerta, chiusura.</summary>
public Money AuctionMin { get; init; }
public Money AuctionBest { get; init; }
public int AuctionBestBidder { get; init; } = -1;
public long AuctionEndDay { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Company); w.I64(TotalShares); w.I64(Treasury);
w.Count(Holdings.Count);
foreach (var h in Holdings) h.Write(ref w);
w.Count(PriceHistory.Count);
foreach (double p in PriceHistory) w.F64(p);
w.Count(History.Count);
foreach (var y in History) y.Write(ref w);
w.Money(AnnualProfit); w.Money(DividendsYear); w.Money(Debt); w.Money(MarketCap); w.I64(ControlDays);
w.Money(AuctionMin); w.Money(AuctionBest); w.I32(AuctionBestBidder); w.I64(AuctionEndDay);
w.Flags(0);
}
public static CompanyCard Read(ref SpanReader r)
{
int company = r.I32();
long total = r.I64(), treasury = r.I64();
var holdings = new List<HoldingInfo>();
for (int n = r.Count(), i = 0; i < n; i++) holdings.Add(HoldingInfo.Read(ref r));
var prices = new List<double>();
for (int n = r.Count(), i = 0; i < n; i++) prices.Add(r.F64());
var history = new List<CompanyYearInfo>();
for (int n = r.Count(), i = 0; i < n; i++) history.Add(CompanyYearInfo.Read(ref r));
var m = new CompanyCard
{
Company = company, TotalShares = total, Treasury = treasury, Holdings = holdings, PriceHistory = prices, History = history,
AnnualProfit = r.Money(), DividendsYear = r.Money(), Debt = r.Money(), MarketCap = r.Money(), ControlDays = r.I64(),
AuctionMin = r.Money(), AuctionBest = r.Money(), AuctionBestBidder = r.I32(), AuctionEndDay = r.I64(),
};
r.Flags();
return m;
}
}
/// <summary>Fermo passato o in corso di un'industria.</summary>
public sealed class IndustryStopInfo
{
public long Day { get; init; }
public int Days { get; init; }
public byte Kind { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I32(Days); w.U8(Kind);
w.Flags(0);
}
public static IndustryStopInfo Read(ref SpanReader r)
{
var m = new IndustryStopInfo { Day = r.I64(), Days = r.I32(), Kind = r.U8() };
r.Flags();
return m;
}
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public sealed class IndustryCard : IMessage
{
public MessageId Id => MessageId.IndustryCard;
public int Industry { get; init; }
public float Margin { get; init; }
public float ConditionMultiplier { get; init; }
/// <summary>Usura e recupero giornalieri attuali (punti di condizione).</summary>
public float WearPerDay { get; init; }
public float RecoveryPerDay { get; init; }
public Money MaintenanceCostPerDay { get; init; }
public Money MaintenanceSpentYear { get; init; }
public int PartsTarget { get; init; }
public int PartsPerMonth { get; init; }
public int PartsOrdered { get; init; }
public int MachineryRequired { get; init; }
public Money UpgradeCost { get; init; }
/// <summary>Prezzo chiesto dai proprietari privati (per BuyIndustry).</summary>
public Money Valuation { get; init; }
public Money Cash { get; init; }
public float BreakdownChancePerYear { get; init; }
public List<IndustryStopInfo> Stops { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Industry); w.F32(Margin); w.F32(ConditionMultiplier); w.F32(WearPerDay); w.F32(RecoveryPerDay);
w.Money(MaintenanceCostPerDay); w.Money(MaintenanceSpentYear); w.I32(PartsTarget); w.I32(PartsPerMonth); w.I32(PartsOrdered);
w.I32(MachineryRequired); w.Money(UpgradeCost); w.Money(Valuation); w.Money(Cash); w.F32(BreakdownChancePerYear);
w.Count(Stops.Count);
foreach (var s in Stops) s.Write(ref w);
w.Flags(0);
}
public static IndustryCard Read(ref SpanReader r)
{
var m = new IndustryCard
{
Industry = r.I32(), Margin = r.F32(), ConditionMultiplier = r.F32(), WearPerDay = r.F32(), RecoveryPerDay = r.F32(),
MaintenanceCostPerDay = r.Money(), MaintenanceSpentYear = r.Money(), PartsTarget = r.I32(), PartsPerMonth = r.I32(), PartsOrdered = r.I32(),
MachineryRequired = r.I32(), UpgradeCost = r.Money(), Valuation = r.Money(), Cash = r.Money(), BreakdownChancePerYear = r.F32(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.Stops.Add(IndustryStopInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Primato della Cronaca finale (descrizione e valore già formattati in italiano).</summary>
public sealed class RecordInfo
{
public string Title { get; init; } = "";
public string Value { get; init; } = "";
public int Year { get; init; }
public void Write(ref SpanWriter w)
{
w.String(Title); w.String(Value); w.I32(Year);
w.Flags(0);
}
public static RecordInfo Read(ref SpanReader r)
{
var m = new RecordInfo { Title = r.String(), Value = r.String(), Year = r.I32() };
r.Flags();
return m;
}
}
/// <summary>
/// Cronaca finale (12.3): storia della compagnia del giocatore, grafici, primati e prestigio.
/// Dopo la Cronaca il giocatore può continuare come osservatore o iniziare una Nuova partita+.
/// </summary>
public sealed class Chronicle : IMessage
{
public MessageId Id => MessageId.Chronicle;
public bool GameOver { get; init; }
/// <summary>Motivo (GameOverReason): 1 fallimento, 2 scalata, 3 riscatto scaduto.</summary>
public byte Reason { get; init; }
public string Text { get; init; } = "";
public int Winner { get; init; } = -1;
public long Day { get; init; }
public string Company { get; init; } = "";
public int FoundedYear { get; init; }
public long Prestige { get; init; }
public List<CompanyYearInfo> History { get; init; } = [];
public List<RecordInfo> Records { get; init; } = [];
/// <summary>Fatti salienti della compagnia, dal più vecchio.</summary>
public List<string> Highlights { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.Bool(GameOver); w.U8(Reason); w.String(Text); w.I32(Winner); w.I64(Day); w.String(Company); w.I32(FoundedYear); w.I64(Prestige);
w.Count(History.Count);
foreach (var y in History) y.Write(ref w);
w.Count(Records.Count);
foreach (var rec in Records) rec.Write(ref w);
w.Count(Highlights.Count);
foreach (var h in Highlights) w.String(h);
w.Flags(0);
}
public static Chronicle Read(ref SpanReader r)
{
bool over = r.Bool();
byte reason = r.U8();
string text = r.String();
int winner = r.I32();
long day = r.I64();
string company = r.String();
int founded = r.I32();
long prestige = r.I64();
var history = new List<CompanyYearInfo>();
for (int n = r.Count(), i = 0; i < n; i++) history.Add(CompanyYearInfo.Read(ref r));
var records = new List<RecordInfo>();
for (int n = r.Count(), i = 0; i < n; i++) records.Add(RecordInfo.Read(ref r));
var highlights = new List<string>();
for (int n = r.Count(), i = 0; i < n; i++) highlights.Add(r.String());
r.Flags();
return new Chronicle
{
GameOver = over, Reason = reason, Text = text, Winner = winner, Day = day, Company = company, FoundedYear = founded,
Prestige = prestige, History = history, Records = records, Highlights = highlights,
};
}
}
@@ -28,6 +28,9 @@ public static class MessageCodec
MessageId.EmploymentReport => EmploymentReport.Read(ref r),
MessageId.MaintenanceCard => MaintenanceCard.Read(ref r),
MessageId.WorkshopRegister => WorkshopRegister.Read(ref r),
MessageId.CompanyCard => CompanyCard.Read(ref r),
MessageId.IndustryCard => IndustryCard.Read(ref r),
MessageId.Chronicle => Chronicle.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
+42 -3
View File
@@ -71,12 +71,28 @@ public sealed class CompanyInfo : IWritable
// blocco 1 (F4): politica di manutenzione della flotta
public byte MaintenancePolicy { get; set; } = 1;
// blocco 2 (F5): borsa, controllo, stato societario
public string Personality { get; set; } = "";
public bool Listed { get; set; }
/// <summary>Prezzo per azione in centesimi (frazionario).</summary>
public double SharePriceCents { get; set; }
public float Sentiment { get; set; } = 1;
/// <summary>Quota del fondatore sulle azioni in circolazione.</summary>
public float FounderShare { get; set; } = 1;
public int ControlledBy { get; set; } = -1;
public bool Merged { get; set; }
public bool Receivership { get; set; }
public long ReceivershipUntilDay { get; set; } = -1;
public Money AnnualProfit { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Name); w.String(Color); w.Bool(IsPlayer); w.Money(Cash); w.Money(NetWorth);
w.String(Rating); w.U8(Tier); w.Bool(Bankrupt);
w.Flags(1);
w.Flags(3);
w.U8(MaintenancePolicy);
w.String(Personality); w.Bool(Listed); w.F64(SharePriceCents); w.F32(Sentiment); w.F32(FounderShare);
w.I32(ControlledBy); w.Bool(Merged); w.Bool(Receivership); w.I64(ReceivershipUntilDay); w.Money(AnnualProfit);
}
public static CompanyInfo Read(ref SpanReader r)
@@ -88,6 +104,11 @@ public sealed class CompanyInfo : IWritable
};
byte flags = r.Flags();
if ((flags & 1) != 0) m.MaintenancePolicy = r.U8();
if ((flags & 2) != 0)
{
m.Personality = r.String(); m.Listed = r.Bool(); m.SharePriceCents = r.F64(); m.Sentiment = r.F32(); m.FounderShare = r.F32();
m.ControlledBy = r.I32(); m.Merged = r.Bool(); m.Receivership = r.Bool(); m.ReceivershipUntilDay = r.I64(); m.AnnualProfit = r.Money();
}
return m;
}
}
@@ -129,11 +150,24 @@ public sealed class IndustryInfo : IWritable
public float Condition { get; init; }
public int Owner { get; init; } = -1;
// blocco 1 (F5): manutenzione degli impianti (sezione 11)
/// <summary>Budget di manutenzione: 0 nessuno, 1 base, 2 alto.</summary>
public byte Budget { get; set; } = 1;
public int SpareParts { get; set; }
public int Machinery { get; set; }
/// <summary>Giorno di fine del fermo in corso (−1 se lavora) e motivo (IndustryStop).</summary>
public long StoppedUntilDay { get; set; } = -1;
public byte StopKind { get; set; }
/// <summary>Lavoro programmato in attesa (IndustryWork).</summary>
public byte PendingWork { get; set; }
public bool PartsShort { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Type); w.String(Name); w.Vec2(Position); w.I32(FootprintCells); w.I32(Level); w.Bool(Closed);
w.F32(Efficiency); w.F32(Condition); w.I32(Owner);
w.Flags(0);
w.Flags(1);
w.U8(Budget); w.I32(SpareParts); w.I32(Machinery); w.I64(StoppedUntilDay); w.U8(StopKind); w.U8(PendingWork); w.Bool(PartsShort);
}
public static IndustryInfo Read(ref SpanReader r)
@@ -143,7 +177,12 @@ public sealed class IndustryInfo : IWritable
Id = r.I32(), Type = r.String(), Name = r.String(), Position = r.Vec2(), FootprintCells = r.I32(), Level = r.I32(), Closed = r.Bool(),
Efficiency = r.F32(), Condition = r.F32(), Owner = r.I32(),
};
r.Flags();
byte flags = r.Flags();
if ((flags & 1) != 0)
{
m.Budget = r.U8(); m.SpareParts = r.I32(); m.Machinery = r.I32(); m.StoppedUntilDay = r.I64(); m.StopKind = r.U8();
m.PendingWork = r.U8(); m.PartsShort = r.Bool();
}
return m;
}
}
@@ -739,16 +739,27 @@ public sealed class SharePrice
public float Change { get; init; }
public bool Listed { get; init; }
// blocco 1 (F5): prezzo esatto, capitalizzazione, flottante libero, quota del fondatore
public double PriceCents { get; set; }
public long Outstanding { get; set; }
public long FreeFloat { get; set; }
public float FounderShare { get; set; }
public int ControlledBy { get; set; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Company); w.Money(Price); w.F32(Change); w.Bool(Listed);
w.Flags(0);
w.Flags(1);
w.F64(PriceCents); w.I64(Outstanding); w.I64(FreeFloat); w.F32(FounderShare); w.I32(ControlledBy);
}
public static SharePrice Read(ref SpanReader r)
{
var m = new SharePrice { Company = r.I32(), Price = r.Money(), Change = r.F32(), Listed = r.Bool() };
r.Flags();
if ((r.Flags() & 1) != 0)
{
m.PriceCents = r.F64(); m.Outstanding = r.I64(); m.FreeFloat = r.I64(); m.FounderShare = r.F32(); m.ControlledBy = r.I32();
}
return m;
}
}
@@ -762,16 +773,28 @@ public sealed class BidInfo
public double TargetShare { get; init; }
public long ExpiresDay { get; init; }
// blocco 1 (F5): stato, quota già impegnata (azioni dell'offerente + adesioni), difese, cavaliere bianco
public byte State { get; set; }
public double CommittedShare { get; set; }
public byte Defenses { get; set; }
public int Knight { get; set; } = -1;
/// <summary>Vero se la compagnia della sessione ha già aderito.</summary>
public bool Accepted { get; set; }
public void Write(ref SpanWriter w)
{
w.I32(Bid); w.I32(Bidder); w.I32(Target); w.Money(PricePerShare); w.F64(TargetShare); w.I64(ExpiresDay);
w.Flags(0);
w.Flags(1);
w.U8(State); w.F64(CommittedShare); w.U8(Defenses); w.I32(Knight); w.Bool(Accepted);
}
public static BidInfo Read(ref SpanReader r)
{
var m = new BidInfo { Bid = r.I32(), Bidder = r.I32(), Target = r.I32(), PricePerShare = r.Money(), TargetShare = r.F64(), ExpiresDay = r.I64() };
r.Flags();
if ((r.Flags() & 1) != 0)
{
m.State = r.U8(); m.CommittedShare = r.F64(); m.Defenses = r.U8(); m.Knight = r.I32(); m.Accepted = r.Bool();
}
return m;
}
}
+17
View File
@@ -619,6 +619,13 @@ public sealed class GameHost : IDisposable
}
}
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company));
// listino di borsa del giorno (12.2) e, a fine partita, la Cronaca finale una volta per sessione
s.Send(Projection.Tape(w, s.Company));
if (w.GameOver is not null && !s.ChronicleSent)
{
s.Send(Projection.Chronicle(w));
s.ChronicleSent = true;
}
}
_monthlyDue = false;
_dayEvents.Clear();
@@ -641,6 +648,16 @@ public sealed class GameHost : IDisposable
case DetailKind.Employment:
s.Send(Projection.Employment(w, s.Company));
break;
case DetailKind.Company:
if (m.Target >= 0 && m.Target < w.Companies.Count) s.Send(Projection.CompanyCard(w, w.Companies[m.Target]));
break;
case DetailKind.Industry:
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
break;
}
}
+105 -1
View File
@@ -79,6 +79,9 @@ public static class Projection
{
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt, MaintenancePolicy = (byte)c.MaintenancePolicy,
Personality = c.AiPersonality ?? "", Listed = c.Listed, SharePriceCents = Math.Round(c.SharePrice, 2), Sentiment = (float)c.Sentiment,
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value, Merged = c.Merged,
Receivership = c.Receivership, ReceivershipUntilDay = c.ReceivershipUntilDay, AnnualProfit = new Money(c.AnnualProfit),
});
}
foreach (var t in w.Towns)
@@ -94,7 +97,9 @@ public static class Projection
e.Industries.Add(new IndustryInfo
{
Id = i.Id.Value, Type = i.Def.Id, Name = i.Name, Position = i.Position, FootprintCells = i.FootprintCells, Level = i.Level,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)i.Condition, Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)Math.Round(i.Condition, 1), Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Budget = (byte)i.Budget, SpareParts = i.SpareParts, Machinery = i.Machinery, StoppedUntilDay = i.StoppedUntilDay,
StopKind = (byte)i.StopKind, PendingWork = (byte)i.PendingWork, PartsShort = i.PartsShort,
});
}
foreach (var h in w.Hubs)
@@ -414,4 +419,103 @@ public static class Projection
record.Write(ref w);
return XxHash64.Hash(w.Written);
}
// ------------------------------------------------------------------ F5: borsa, industrie, Cronaca
/// <summary>Listino del giorno: prezzi delle compagnie attive e offerte pubbliche in corso.</summary>
public static MarketTape Tape(World w, CompanyId viewer)
{
var tape = new MarketTape { Day = w.Clock.Day };
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double last = c.PriceHistory.Count > 0 ? c.PriceHistory[^1] : c.SharePrice;
tape.Shares.Add(new SharePrice
{
Company = c.Id.Value, Price = Money.FromCentsRounded(c.SharePrice), Change = last > 0 ? (float)(c.SharePrice / last - 1) : 0,
Listed = c.Listed, PriceCents = Math.Round(c.SharePrice, 4), Outstanding = c.Shares.Outstanding, FreeFloat = Corporate.FreeFloat(w, c),
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value,
});
}
foreach (var b in w.Bids)
{
if (b.State != BidState.Open) continue;
var target = w.Company(b.Target);
tape.Bids.Add(new BidInfo
{
Bid = b.Id.Value, Bidder = b.Bidder.Value, Target = b.Target.Value, PricePerShare = new Money(b.PricePerShare), TargetShare = b.TargetShare,
ExpiresDay = b.EndDay, State = (byte)b.State,
CommittedShare = target.Shares.Outstanding > 0 ? (double)StockMarketSystem.Committed(w, b) / target.Shares.Outstanding : 0,
Defenses = b.Defenses, Knight = b.Knight.Value, Accepted = b.Accepted.Contains(viewer),
});
}
return tape;
}
private static CompanyYearInfo YearInfo(CompanyYear y) => new()
{
Year = y.Year, NetWorth = new Money(y.NetWorthCents), Cash = new Money(y.CashCents), Revenue = new Money(y.RevenueCents),
Profit = new Money(y.ProfitCents), Tier = (byte)y.Tier, Trains = y.Trains, TrackKm = (float)y.TrackKm, SharePrice = new Money(y.SharePriceCents),
};
/// <summary>Scheda di una compagnia: libro dei soci, prezzi mensili, storico annuale, asta.</summary>
public static CompanyCard CompanyCard(World w, Company c)
{
var holdings = new List<HoldingInfo>
{
new() { Holder = HoldingInfo.Founder, Shares = c.Shares.Founder },
new() { Holder = HoldingInfo.Market, Shares = c.Shares.Public },
};
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (c.Shares.ByCompany[i] > 0) holdings.Add(new HoldingInfo { Holder = i, Shares = c.Shares.ByCompany[i] });
}
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
var auction = w.Auctions.FirstOrDefault(a => a.Seller == c.Id && !a.Closed);
return new CompanyCard
{
Company = c.Id.Value, TotalShares = c.Shares.Total, Treasury = c.Shares.Treasury, Holdings = holdings,
PriceHistory = [.. c.PriceHistory], History = c.History.Select(YearInfo).ToList(),
AnnualProfit = new Money(c.AnnualProfit), DividendsYear = new Money(dividends), Debt = c.Debt, MarketCap = Money.FromCentsRounded(c.MarketCap),
ControlDays = c.ControlledBy.IsValid ? w.Clock.Day - c.ControlSinceDay : -1,
AuctionMin = new Money(auction?.MinPriceCents ?? 0), AuctionBest = new Money(auction?.BestPriceCents ?? 0),
AuctionBestBidder = auction?.BestBidder.Value ?? -1, AuctionEndDay = auction?.EndDay ?? -1,
};
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public static IndustryCard IndustryCard(World w, Industry ind)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1);
double hazard = ind.Condition >= m.BreakdownPivot ? 0 : m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
double perYear = 1 - DMath.Pow(1 - Math.Min(1, hazard), w.Calendar.DaysPerYear);
return new IndustryCard
{
Industry = ind.Id.Value, Margin = (float)ind.Margin, ConditionMultiplier = (float)IndustryMath.ConditionMultiplier(ind.Condition, m),
WearPerDay = (float)wear, RecoveryPerDay = (float)recovery, MaintenanceCostPerDay = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue),
MaintenanceSpentYear = new Money(ind.MaintenanceSpentYear), PartsTarget = IndustryMath.PartsTarget(ind, m), PartsPerMonth = IndustryMath.MonthlyPartsUse(ind, m),
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
};
}
/// <summary>Cronaca finale (o provvisoria, se la partita è in corso) della compagnia del giocatore.</summary>
public static Chronicle Chronicle(World w)
{
var report = ChronicleReport.Build(w);
return new Chronicle
{
GameOver = w.GameOver is not null, Reason = (byte)(w.GameOver?.Reason ?? GameOverReason.None), Text = w.GameOver?.Text ?? "",
Winner = w.GameOver?.Winner.Value ?? -1, Day = w.GameOver?.Day ?? w.Clock.Day, Company = w.Player.Name,
FoundedYear = w.Calendar.StartYear, Prestige = report.Prestige,
History = report.History.Select(YearInfo).ToList(),
Records = report.Records.Select(r => new RecordInfo { Title = r.Title, Value = r.Value, Year = r.Year }).ToList(),
Highlights = report.Highlights,
};
}
}
+3
View File
@@ -38,6 +38,9 @@ public sealed class Session
public Dictionary<int, (long Tick, byte State)> MotionSent { get; } = [];
public bool NeedsFullState { get; set; } = true;
/// <summary>Cronaca finale già inviata a questa sessione.</summary>
public bool ChronicleSent { get; set; }
public Session(ulong id, CompanyId company)
{
Id = id;
@@ -17,7 +17,7 @@ public sealed class SimulateCommand : IToolCommand
{
public string Name => "simulate";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>]";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>] [--trace-ai]";
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
@@ -30,7 +30,9 @@ public sealed class SimulateCommand : IToolCommand
string? scenario = args.String("scenario");
string output = args.String("out", "kpi.csv");
string? savePath = args.String("save");
bool trace = args.Flag("trace-ai");
args.EnsureAllUsed();
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
var data = GameData.LoadDefault();
var total = Stopwatch.StartNew();
@@ -65,6 +67,8 @@ public sealed class SimulateCommand : IToolCommand
Console.WriteLine($" data finale {world.Clock.Date}, hash {world.LastStateHash:x16}");
Console.WriteLine($" popolazione {Core.Common.Money.GroupThousands((ulong)world.Towns.Sum(t => (long)t.Population))}, industrie aperte {world.Industries.Count(i => !i.Closed)} su {world.Industries.Count}");
Console.WriteLine($" invarianti: denaro {(world.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}, merci {(Enumerable.Range(0, data.GoodCount).All(g => world.TotalStock(g) == world.Goods.ExpectedStock(g)) ? "ok" : "ROTTO")}");
foreach (var c in world.Companies)
Console.WriteLine($" {c.Name}: patrimonio {c.NetWorth}, cassa {c.Cash}, livello {c.Tier}, rating {c.Rating}, azione {c.SharePrice / 100:0.00} lire{AiNote(world, c)}{(c.Defunct ? " (fuori gioco)" : "")}");
Console.WriteLine($" KPI in {output}");
return 0;
}
@@ -91,12 +95,22 @@ public sealed class SimulateCommand : IToolCommand
{
long revenue = Company.Revenue(c.LastYearEntries);
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}";
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "",
fleet ? Dec(Fleet.FleetCondition(w, c.Id)) : "", "", Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
}
}
/// <summary>Diagnostica dell'agente IA: progetti, treni, comandi rifiutati.</summary>
private static string AiNote(World w, Company c)
{
var s = w.AiStates.FirstOrDefault(a => a.Company == c.Id);
if (s is null) return "";
int running = s.Projects.Count(p => p.Stage == Core.Simulation.Ai.AiProjectStage.Running);
int trains = w.Trains.Count(t => !t.Removed && t.Owner == c.Id);
return $", progetti {running}/{s.Projects.Count}, treni {trains}, città collegate {Tiers.ConnectedTowns(w, c.Id, 1000)} (≥1000) {Tiers.ConnectedTowns(w, c.Id, 2000)} (≥2000), comandi {s.Issued} (rifiutati {s.RejectedShare * 100:0.0} %)";
}
private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ',');
}
+87
View File
@@ -0,0 +1,87 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Concorrenti IA (guida 12.1, test di 14.5): comandi validi, crescita, determinismo.</summary>
public static class AiTests
{
[Test(Slow = true, Description = "Le IA agiscono solo con i comandi e ne vedono rifiutati al massimo il 5 %")]
public static void AiCommandsAreRarelyRejected()
{
var w = TestWorlds.Small(42);
w.RunYears(5);
Assert.True(w.AiStates.Count >= 2, "uno stato per ogni IA");
long issued = 0;
foreach (var s in w.AiStates)
{
issued += s.Issued;
Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare,
$"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
}
Assert.True(issued > 20, $"le IA costruiscono e gestiscono la rete ({issued} comandi)");
Assert.True(w.AiStates.Any(s => s.Projects.Any(p => p.Stage == AiProjectStage.Running)), "almeno una linea in esercizio");
// i binari, i treni e le stazioni delle IA esistono davvero nel mondo
foreach (var s in w.AiStates)
{
foreach (var p in s.Projects.Where(p => p.Stage == AiProjectStage.Running))
{
Assert.True(w.Network.IsAlive(w.Network.Stations[p.StationA.Value]) || w.Company(s.Company).Defunct);
Assert.True(p.Trains.All(t => w.Trains[t.Value].Owner == s.Company || w.Company(s.Company).Merged));
}
}
}
[Test(Slow = true, Description = "Un'IA con capitale ×2 supera il giocatore passivo in 10 anni")]
public static void AiWithDoubleCapitalBeatsAPassivePlayer()
{
var w = TestWorlds.Small(42, "imprenditore", ("aiCapitalMultiplier", 2));
w.RunYears(10);
var player = w.Player;
var best = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => c.NetWorth.Cents)!;
Assert.True(best.NetWorth > player.NetWorth, $"{best.Name}: {best.NetWorth} contro {player.NetWorth}");
Assert.True(best.NetWorth.Cents > w.Difficulty.InitialCapital * 2, $"{best.Name} ha fatto crescere il capitale: {best.NetWorth}");
}
[Test(Slow = true, Description = "Determinismo con le IA: stesso seme e stessi comandi, stesso hash dopo 5 anni (anche passando da un salvataggio)")]
public static void SameSeedWithAiGivesSameHash()
{
static World Make()
{
var w = TestWorlds.Small(77, "magnate");
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
return w;
}
var a = Make();
var b = Make();
a.RunYears(2);
b.RunYears(2);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
var c = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
a.RunYears(3);
c.RunYears(3);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
Assert.True(a.AiStates.Sum(s => s.Issued) > 0, "le IA hanno agito");
}
[Test(Slow = true, Description = "Accettazione F5: in «Magnate», con il giocatore passivo, almeno un'IA raggiunge il livello 3 in 15 anni")]
public static void OnMagnateAnAiReachesTierThreeIn15Years()
{
var w = WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = 7, SizeKm = 128, DifficultyId = "magnate" });
int best = 1;
for (int y = 0; y < 15 && best < 3; y++)
{
w.RunYears(1);
best = w.Companies.Where(c => !c.IsPlayer).Max(c => c.Tier);
}
var leader = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => (c.Tier, c.NetWorth.Cents))!;
Console.WriteLine($" {leader.Name}: livello {leader.Tier} nel {w.Clock.Year}, patrimonio {leader.NetWorth}, rating {leader.Rating}, " +
$"città collegate {Core.Simulation.Systems.Tiers.ConnectedTowns(w, leader.Id, 1000)}");
Assert.True(best >= 3, $"livello massimo delle IA: {best}");
Assert.Equal(1, w.Player.Tier, "il giocatore passivo resta al livello 1");
}
}
@@ -66,9 +66,9 @@ public static class EconomyTests
public static void FreightAndPassengerTariffsFollowFormulas()
{
var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × 150 × 1 × 20^0,9 centesimi
// a prezzo base: 40 t × tariffa base × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * 150 * DMath.Pow(20, 0.9)), freight);
Assert.Equal(Money.FromCentsRounded(40 * t.FreightBaseRate * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2);
@@ -182,7 +182,7 @@ public static class EconomyTests
{
var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
@@ -0,0 +1,206 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Manutenzione degli impianti (guida, sezione 11) e industrie possedute dal giocatore.</summary>
public static class IndustryMaintenanceTests
{
private static Industry Pick(World w, IndustryKind kind) =>
w.Industries.First(i => !i.Closed && i.Level > 0 && i.Def.Kind == kind);
private static CommandResult Do(World w, GameCommand c)
{
w.Enqueue(c with { Issuer = w.Player.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
[Test]
public static void EfficiencyMultiplierFollowsTheGuide()
{
var m = TestData.Data.Balance.IndustryMaintenance;
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(100, m), 1e-9);
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(70, m), 1e-9);
Assert.Approx(0.75, IndustryMath.ConditionMultiplier(45, m), 1e-9);
Assert.Approx(0.5, IndustryMath.ConditionMultiplier(20, m), 1e-9);
Assert.Approx(0.3, IndustryMath.ConditionMultiplier(10, m), 1e-9);
}
[Test(Description = "Usura con l'utilizzo; il budget Alto recupera; senza ricambi il recupero si dimezza")]
public static void WearFollowsUseAndBudgetRecovers()
{
var w = TestWorlds.NoAi(301);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
w.RunDays(5);
// senza manutenzione la condizione scende con l'utilizzo
ind.Budget = IndustryBudget.None;
ind.Condition = 80;
w.RunDays(60);
double dropped = 80 - ind.Condition;
Assert.True(dropped > 0, $"usura senza budget: {dropped:F3}");
Assert.True(dropped <= m.WearPerDay * 1.2 * ind.Def.WearIntensity * w.Difficulty.WearMultiplier * 60 + 1e-6, "usura entro il massimo della formula");
// budget alto con ricambi: il recupero (0,12 al giorno) supera l'usura; senza ricambi si dimezza.
// Due finestre di 10 giorni nello stesso mese (il consumo mensile ricalcola la mancanza di ricambi).
int dpm = w.Calendar.DaysPerMonth;
w.RunDays(dpm - (int)(w.Clock.Day % dpm) + 1);
ind.Budget = IndustryBudget.High;
ind.Condition = 60;
ind.PartsShort = false;
w.RunDays(10);
double withParts = ind.Condition - 60;
Assert.True(withParts > 0, $"recupero con budget alto: {withParts:F3}");
ind.Condition = 60;
ind.PartsShort = true;
w.RunDays(10);
double withoutParts = ind.Condition - 60;
var budget = m.For(IndustryBudget.High);
Assert.Approx(budget.RecoveryPerDay * (1 - m.NoPartsRecoveryFactor) * 10, withParts - withoutParts, 0.05,
$"senza ricambi il recupero si dimezza: {withoutParts:F3} contro {withParts:F3}");
Assert.Equal(0L, w.MoneyBalanceSum());
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"bene {w.Data.Goods[g].Id}");
}
[Test(Description = "Sotto 40 arrivano i fermi: niente produzione, storico, città colpita; sotto 10 l'incidente grave")]
public static void LowConditionBringsStopsAndAccidents()
{
var w = TestWorlds.NoAi(302);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Processing);
ind.Budget = IndustryBudget.None;
ind.Condition = 5;
bool stopped = false;
for (int d = 0; d < 720 && !stopped; d++)
{
ind.Condition = 5;
w.RunDays(1);
stopped = ind.IsStopped(w.Clock.Day);
}
Assert.True(stopped, "con condizione 5 un fermo arriva");
Assert.Equal(IndustryStop.Accident, ind.StopKind, "un'industria di trasformazione sotto 10 ha un incidente grave");
Assert.Equal(m.AccidentDays, ind.StopHistory[^1].Days);
w.RunDays(2);
Assert.Equal(0, ind.ProducedToday.Sum(), "nessuna produzione durante il fermo");
Assert.Approx(0.0, ind.Efficiency, 1e-9);
// un'industria primaria a 25 ha solo fermi per guasto da 5 a 20 giorni
var mine = Pick(w, IndustryKind.Primary);
mine.Budget = IndustryBudget.None;
bool broke = false;
for (int d = 0; d < 2000 && !broke; d++)
{
mine.Condition = 25;
w.RunDays(1);
broke = mine.IsStopped(w.Clock.Day);
}
Assert.True(broke, "a 25 il rischio giornaliero produce un fermo");
Assert.Equal(IndustryStop.Breakdown, mine.StopKind);
Assert.InRange(mine.StopHistory[^1].Days, m.BreakdownDays[0], m.BreakdownDays[1]);
// il rischio cresce al calare della condizione
Assert.True(m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 10) / m.BreakdownScale) > m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 30) / m.BreakdownScale));
}
[Test(Description = "Acquisto (livello 3, offerta ≥ valore), revisione che aspetta i macchinari e riporta la condizione a 100, ammodernamento di livello")]
public static void OwnedIndustryOverhaulAndUpgrade()
{
var w = TestWorlds.NoAi(303);
var m = w.Data.Balance.IndustryMaintenance;
var player = w.Player;
w.Money.Transfer(Account.External, Account.Of(player.Id), Money.FromLire(10_000_000), LedgerEntry.Other);
var ind = Pick(w, IndustryKind.Processing);
w.RunDays(3);
var locked = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(9_000_000)));
Assert.Equal(CommandError.TierLocked, locked.Error, "l'acquisto si sblocca al livello 3");
player.Tier = 3;
var price = IndustryMath.Valuation(w, ind);
var low = Do(w, new BuyIndustryCommand(ind.Id, price - Money.FromLire(1)));
Assert.Equal(CommandError.InvalidArgument, low.Error, "offerta sotto il valore");
price = IndustryMath.Valuation(w, ind);
var cash = player.Cash;
var ok = Do(w, new BuyIndustryCommand(ind.Id, price + Money.FromLire(100)));
Assert.True(ok.Ok, ok.Message);
Assert.Equal(player.Id, ind.Owner);
Assert.True(player.Cash < cash, "l'acquisto si paga");
// revisione: aspetta i macchinari (e il personale), poi 30 giorni di fermo e condizione 100
ind.Condition = 30;
Assert.True(Do(w, new OverhaulIndustryCommand(ind.Id)).Ok);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork);
w.RunDays(5);
Assert.False(ind.IsStopped(w.Clock.Day), "senza macchinari la revisione non parte");
int need = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += need;
w.Goods.Produced[w.Data.MachineryGood] += need;
ind.CovStaff = 1;
w.RunDays(2);
Assert.True(ind.IsStopped(w.Clock.Day), "con macchinari e personale la revisione parte");
Assert.Equal(IndustryStop.Overhaul, ind.StopKind);
w.RunDays(m.OverhaulDays + 1);
Assert.False(ind.IsStopped(w.Clock.Day));
Assert.True(ind.Condition > 99, $"condizione dopo la revisione: {ind.Condition:F1}");
// ammodernamento: costo in capitale e macchinari, 60 giorni, livello + 1
int level = ind.Level;
if (level < w.Data.Balance.Growth.MaxLevel)
{
Assert.True(Do(w, new UpgradeIndustryCommand(ind.Id)).Ok);
int machinery = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += machinery;
w.Goods.Produced[w.Data.MachineryGood] += machinery;
var before = player.Cash;
w.RunDays(2);
Assert.Equal(IndustryStop.Upgrade, ind.StopKind);
Assert.True(player.Cash < before, "il proprietario paga l'ammodernamento");
w.RunDays(m.UpgradeDays + 1);
Assert.Equal(level + 1, ind.Level);
}
// «Ordina ricambi» crea domanda esplicita oltre la scorta della politica
Assert.True(Do(w, new OrderPartsCommand(DepotId.None, 30) { Industry = ind.Id }).Ok);
Assert.True(IndustryMath.ServiceNeed(w, ind, w.Data.SparePartsGood) >= 30);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Ogni mese l'industria posseduta trattiene la riserva e versa il resto al proprietario")]
public static void OwnerReceivesTheSurplus()
{
var w = TestWorlds.NoAi(304);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
ind.Owner = w.Player.Id;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(500_000), LedgerEntry.Other);
var before = w.Player.Cash;
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(m.OwnerCashReserve, ind.Cash.Cents, "l'industria trattiene la riserva");
Assert.True(w.Player.Cash > before, "il surplus va al proprietario");
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Industries] > 0);
}
[Test(Description = "Proprietari privati: budget dal margine e revisione sotto 35 se la cassa basta")]
public static void NpcOwnersFollowTheirRules()
{
var w = TestWorlds.NoAi(305);
var ind = Pick(w, IndustryKind.Primary);
ind.RevenueEma = 10_000;
ind.CostEma = 5_000;
ind.Condition = 30;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork, "sotto 35 il privato programma la revisione");
// margine negativo: nessun budget
var other = w.Industries.First(i => !i.Closed && i.Level > 0 && i != ind && i.Def.Kind == IndustryKind.Primary);
other.RevenueEma = 1_000;
other.CostEma = 5_000;
w.RunDays(w.Calendar.DaysPerMonth);
Assert.True(other.Margin < 0);
Assert.Equal(IndustryBudget.None, other.Budget);
}
}
@@ -0,0 +1,285 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Borsa, quotazione, dividendi, scalate e loro esiti (guida 12.2–12.3, test di 14.5).</summary>
public static class StockMarketTests
{
private static CommandResult Do(World w, GameCommand c, Company issuer)
{
w.Enqueue(c with { Issuer = issuer.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
private static void Give(World w, Company c, long lire) =>
w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(lire), LedgerEntry.Other);
/// <summary>Le IA non devono intervenire: mondo con concorrenti ma senza agenti attivi.</summary>
private static World WithIdleAi(ulong seed, string difficulty = "imprenditore", int competitors = 2)
{
var w = TestWorlds.Small(seed, difficulty, ("aiCompetitors", competitors));
w.AiPaused = true;
return w;
}
[Test(Description = "Prezzo = max(patrimonio, 8 × utile) / azioni × sentiment, con il sentiment tra 0,8 e 1,3")]
public static void PriceFollowsFundamentals()
{
var w = WithIdleAi(401);
var sm = w.Data.Balance.StockMarket;
w.RunDays(40);
foreach (var c in w.Companies)
{
Assert.Equal(sm.Shares, c.Shares.Total);
Assert.Equal(c.Shares.Total, c.Shares.Sum());
Assert.InRange(c.Sentiment, sm.SentimentMin, sm.SentimentMax);
double fundamental = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit) / c.Shares.Outstanding;
Assert.Approx(fundamental * c.Sentiment, c.SharePrice, fundamental * 0.05 + 0.01, c.Name);
}
Assert.False(w.Player.Listed, "il giocatore parte privato (Imprenditore)");
Assert.True(w.Companies.Where(c => !c.IsPlayer).All(c => c.Listed), "le IA sono quotate");
var iron = WithIdleAi(402, "ferro_e_sangue");
Assert.True(iron.Player.Listed, "Ferro e sangue: quotata dall'inizio");
Assert.Approx(0.6, iron.Player.Shares.FounderFraction, 1e-6);
}
[Test(Description = "Quotazione al livello 4 fino al 40 %, compravendita al prezzo con lo spread, dividendi agli azionisti")]
public static void IpoTradingAndDividends()
{
var w = WithIdleAi(403);
var player = w.Player;
var ai = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 5_000_000);
w.RunDays(2);
Assert.Equal(CommandError.TierLocked, Do(w, new IpoCommand(0.3), player).Error);
player.Tier = 4;
Assert.Equal(CommandError.InvalidArgument, Do(w, new IpoCommand(0.5), player).Error, "oltre il 40 %");
var cash = player.Cash;
Assert.True(Do(w, new IpoCommand(0.3), player).Ok);
Assert.True(player.Listed);
Assert.True(player.Cash > cash, "la quotazione porta capitale");
Assert.Approx(0.7, player.Shares.FounderFraction, 1e-6);
// acquisto di azioni di un'IA: lettera = prezzo × (1 + spread/2)
long n = 20_000;
double ask = Corporate.Ask(w, ai);
cash = player.Cash;
long free = ai.Shares.Public;
var buy = Do(w, new BuySharesCommand(ai.Id, n, Money.Zero), player);
Assert.True(buy.Ok, buy.Message);
Assert.Equal(n, ai.Shares.Of(player.Id));
Assert.Equal(free - n, ai.Shares.Public);
Assert.Approx(n * ask, (cash - player.Cash).Cents, n * ask * 0.02 + 2);
w.RunDays(1);
Assert.True(player.PortfolioValue.Cents > 0, "le partecipazioni contano nel patrimonio");
var sell = Do(w, new SellSharesCommand(ai.Id, n / 2, Money.Zero), player);
Assert.True(sell.Ok, sell.Message);
Assert.Equal(n / 2, ai.Shares.Of(player.Id));
// dividendo: ogni azione in circolazione riceve l'importo; le compagnie azioniste lo incassano
var aiCash = ai.Cash;
Give(w, ai, 1_000_000);
aiCash = ai.Cash;
var holderCash = player.Cash;
Assert.True(Do(w, new PayDividendCommand(new Money(10)), ai).Ok);
Assert.Equal(aiCash.Cents - 10 * ai.Shares.Outstanding, ai.Cash.Cents);
Assert.Equal(holderCash.Cents + 10 * (n / 2), player.Cash.Cents);
Assert.True(ai.DividendRing.Sum() > 0, "i dividendi entrano nel sentiment");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Scalata ostile completata quando il flottante lo consente (14.5); fallita quando non basta")]
public static void HostileTakeoverCompletesWhenTheFloatAllows()
{
var w = WithIdleAi(404);
var player = w.Player;
var target = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 50_000_000);
w.RunDays(2);
// flottante del 70 %: il fondatore privato non aderisce (premio sotto la sua soglia)
long moved = target.Shares.Founder - (long)(target.Shares.Total * 0.3);
target.Shares.Founder -= moved;
target.Shares.Public += moved;
Assert.Equal(CommandError.TierLocked, Do(w, new LaunchBidCommand(target.Id, new Money(1), 0.51), player).Error);
player.Tier = 5;
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
var bid = Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player);
Assert.True(bid.Ok, bid.Message);
bool done = false;
for (int d = 0; d < 100 && !done; d++)
{
w.RunDays(1);
done = w.Bids.Any(b => b.State != BidState.Open);
}
Assert.Equal(BidState.Succeeded, w.Bids.Single().State);
Assert.True(target.Shares.FractionOf(player.Id) >= 0.51, $"quota {target.Shares.FractionOf(player.Id):P1}");
w.RunDays(1);
Assert.Equal(player.Id, target.ControlledBy, "chi supera il 50 % controlla");
// stessa offerta su un'IA con il 30 % di flottante: le adesioni non bastano, l'offerta scade
var other = w.Companies.Last(c => !c.IsPlayer);
long p2 = (long)Math.Ceiling(other.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(other.Id, new Money(p2), 0.51), player).Ok);
w.RunDays(w.Data.Balance.StockMarket.BidDurationDays + 2);
var second = w.Bids.Single(b => b.Target == other.Id);
Assert.Equal(BidState.Failed, second.State);
Assert.Equal(0L, other.Shares.Of(player.Id));
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Difese del bersaglio: il riacquisto toglie flottante all'offerente, il cavaliere bianco lo compra")]
public static void TargetsCanDefend()
{
var w = WithIdleAi(405, competitors: 3);
var player = w.Player;
var target = w.Companies[1];
var knight = w.Companies[2];
Give(w, player, 50_000_000);
Give(w, knight, 50_000_000);
Give(w, target, 5_000_000);
player.Tier = 5;
w.RunDays(2);
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player).Ok);
var bid = w.Bids.Single();
long floatBefore = Corporate.FreeFloat(w, target);
var buyback = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.Buyback }, target);
Assert.True(buyback.Ok, buyback.Message);
Assert.True(Corporate.FreeFloat(w, target) < floatBefore, "il riacquisto riduce il flottante");
var white = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.WhiteKnight, Knight = knight.Id }, target);
if (Corporate.FreeFloat(w, target) > 0 || white.Ok) Assert.True(white.Ok || white.Error == CommandError.InsufficientFunds, white.Message);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "La controllata versa gli utili; dopo un anno di controllo si può fondere")]
public static void SubsidiaryPaysAndCanBeMerged()
{
var w = WithIdleAi(406);
var player = w.Player;
var sub = w.Companies[1];
Give(w, player, 50_000_000);
// il giocatore compra il 60 % dal fondatore privato (come dopo un'offerta riuscita)
long stake = (long)(sub.Shares.Total * 0.6);
sub.Shares.Founder -= stake;
sub.Shares.Add(player.Id, stake);
w.RunDays(2);
Assert.Equal(player.Id, sub.ControlledBy);
Assert.Equal(CommandError.NotAllowed, Do(w, new MergeCompanyCommand(sub.Id), player).Error, "serve un anno di controllo");
w.RunDays(w.Data.Balance.StockMarket.MergeAfterDays + 1);
int trainsBefore = w.Trains.Count(t => t.Owner == player.Id);
var merge = Do(w, new MergeCompanyCommand(sub.Id), player);
Assert.True(merge.Ok, merge.Message);
Assert.True(sub.Merged && sub.Defunct);
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), sub).Error, "la fusa non dà più comandi");
Assert.True(w.Trains.Count(t => t.Owner == player.Id) >= trainsBefore);
Assert.Equal(0L, w.MoneyBalanceSum());
}
/// <summary>Un'IA prende più del 50 % del giocatore quotato.</summary>
private static (World W, Company Ai) PlayerTakenOver(string difficulty)
{
var w = WithIdleAi(407, difficulty);
var player = w.Player;
var ai = w.Companies[1];
w.RunDays(2);
if (!player.Listed) Corporate.InitShares(w, player, true, 0.45);
long stake = (long)(player.Shares.Total * 0.55);
long fromPublic = Math.Min(stake, player.Shares.Public);
player.Shares.Public -= fromPublic;
player.Shares.Founder -= stake - fromPublic;
player.Shares.Add(ai.Id, stake);
w.RunDays(2);
return (w, ai);
}
[Test(Description = "Se l'IA compra il giocatore: amministrazione controllata (Imprenditore), fine immediata (Ferro e sangue), mai (Apprendista)")]
public static void PlayerTakeoverOutcomesByDifficulty()
{
// Imprenditore: amministrazione controllata per 3 anni, niente prestiti, riscatto possibile
var (w, ai) = PlayerTakenOver("imprenditore");
var player = w.Player;
Assert.True(player.Receivership, "amministrazione controllata");
Assert.True(w.GameOver is null, "la partita continua");
Assert.Equal(w.Clock.Day - 2 + 3L * w.Calendar.DaysPerYear, player.ReceivershipUntilDay, "3 anni per il riscatto");
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), player).Error);
Give(w, player, 100_000_000);
long max = (long)(player.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
for (int i = 0; i < 40 && player.Receivership; i++)
{
var r = Do(w, new BuySharesCommand(player.Id, max, Money.Zero), player);
Assert.True(r.Ok, r.Message);
w.RunDays(1);
}
Assert.False(player.Receivership, $"riscatto riuscito: fondatore al {player.Shares.FounderFraction:P0}");
// Ferro e sangue: fine immediata, poi si osserva
var (w2, ai2) = PlayerTakenOver("ferro_e_sangue");
Assert.NotNull(w2.GameOver);
Assert.Equal(GameOverReason.Takeover, w2.GameOver!.Reason);
Assert.Equal(ai2.Id, w2.GameOver.Winner);
Assert.Equal(CommandError.NotAllowed, Do(w2, new TakeLoanCommand(Money.FromLire(1000)), w2.Player).Error, "osservatore");
w2.RunDays(10); // il mondo continua
// Apprendista: nessuna IA può superare il 50 % del giocatore
var w3 = WithIdleAi(408, "apprendista");
var p3 = w3.Player;
var ai3 = w3.Companies[1];
Corporate.InitShares(w3, p3, true, 0.3);
Give(w3, ai3, 100_000_000);
w3.RunDays(1);
long chunk = (long)(p3.Shares.Total * w3.Data.Balance.StockMarket.MaxDailyTradeShare);
CommandResult last = null!;
for (int i = 0; i < 20; i++) last = Do(w3, new BuySharesCommand(p3.Id, chunk, Money.Zero), ai3);
Assert.Equal(CommandError.NotAllowed, last.Error);
Assert.True(p3.Shares.FractionOf(ai3.Id) <= 0.5);
Assert.Equal(CommandError.NotAllowed, Do(w3, new LaunchBidCommand(p3.Id, new Money(1), 0.51), ai3).Error);
}
[Test(Description = "Un'IA fallita va all'asta: il giocatore se ne aggiudica gli attivi")]
public static void BankruptAiIsAuctioned()
{
var w = WithIdleAi(409);
var player = w.Player;
var ai = w.Companies[1];
Give(w, player, 10_000_000);
w.RunDays(2);
ai.Bankrupt = true;
w.RunDays(1);
var auction = w.Auctions.Single(a => a.Seller == ai.Id);
long perShare = auction.MinPriceCents / ai.Shares.Total + 1;
var offer = Do(w, new LaunchBidCommand(ai.Id, new Money(perShare), 1), player);
Assert.True(offer.Ok, offer.Message);
w.RunDays(w.Data.Balance.StockMarket.AuctionDays + 1);
Assert.True(ai.Merged, "attivi passati al compratore");
Assert.Equal(player.Id, ai.MergedInto);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Offerte, soci, amministrazione controllata e storico sopravvivono al salvataggio")]
public static void CorporateStateSurvivesSaveAndLoad()
{
var w = WithIdleAi(410, "magnate");
var player = w.Player;
Give(w, player, 50_000_000);
player.Tier = 5;
w.RunDays(370);
var target = w.Companies[1];
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.6), player).Ok);
w.RunDays(5);
var bytes = SaveFile.Save(w, "test");
var loaded = SaveFile.Load(TestData.Data, bytes);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
w.RunDays(30);
loaded.RunDays(30);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
Assert.True(player.History.Count >= 1, "storico annuale");
}
}
@@ -99,8 +99,31 @@ public static class ProtocolTests
yield return new MarketTape
{
Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180 }],
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true, PriceCents = 1234.25, Outstanding = 990_000, FreeFloat = 300_000, FounderShare = 0.6f, ControlledBy = 2 }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180, State = 1, CommittedShare = 0.42, Defenses = 3, Knight = 3, Accepted = true }],
};
yield return new CompanyCard
{
Company = 1, TotalShares = 1_000_000, Treasury = 10_000,
Holdings = [new HoldingInfo { Holder = HoldingInfo.Founder, Shares = 600_000 }, new HoldingInfo { Holder = HoldingInfo.Market, Shares = 290_000 }, new HoldingInfo { Holder = 2, Shares = 100_000 }],
PriceHistory = [12.5, 13.25, 14],
History = [new CompanyYearInfo { Year = 1851, NetWorth = new Money(500), Cash = new Money(-20), Revenue = new Money(900), Profit = new Money(-30), Tier = 2, Trains = 4, TrackKm = 12.5f, SharePrice = new Money(13) }],
AnnualProfit = new Money(-123), DividendsYear = new Money(45), Debt = new Money(678), MarketCap = new Money(9_000_000), ControlDays = 400,
AuctionMin = new Money(10), AuctionBest = new Money(20), AuctionBestBidder = 3, AuctionEndDay = 999,
};
yield return new IndustryCard
{
Industry = 4, Margin = -0.1f, ConditionMultiplier = 0.8f, WearPerDay = 0.05f, RecoveryPerDay = 0.12f, MaintenanceCostPerDay = new Money(77),
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
};
yield return new Chronicle
{
GameOver = true, Reason = 2, Text = "La Predatoria prende il controllo", Winner = 2, Day = 3600, Company = "Società", FoundedYear = 1850, Prestige = 1234,
History = [new CompanyYearInfo { Year = 1850, NetWorth = new Money(1), Tier = 1 }],
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
};
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() };
@@ -137,9 +160,18 @@ public static class ProtocolTests
private static EntityLists SampleEntities() => new()
{
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2 }],
Companies = [new CompanyInfo
{
Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2,
Personality = "predatory", Listed = true, SharePriceCents = 22.75, Sentiment = 1.1f, FounderShare = 0.55f, ControlledBy = 2, Merged = true,
Receivership = true, ReceivershipUntilDay = 777, AnnualProfit = new Money(-5),
}],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }],
Industries = [new IndustryInfo
{
Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1,
Budget = 2, SpareParts = 5, Machinery = 3, StoppedUntilDay = 1234, StopKind = 3, PendingWork = 2, PartsShort = true,
}],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
@@ -178,6 +210,7 @@ public static class ProtocolTests
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new OrderPartsCommand(DepotId.None, 25) { Industry = new IndustryId(4) };
yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5));
@@ -194,10 +227,12 @@ public static class ProtocolTests
yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false);
yield return new RespondBidCommand(new BidId(2), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(3) };
yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8));
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
yield return new MergeCompanyCommand(new CompanyId(2));
}
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
@@ -1,6 +1,7 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
using static ViaFerrea.Tests.Rail.RailFixture;
@@ -61,7 +62,9 @@ public static class RailNetworkTests
public static void CrossingForeignTrackBuildsAnOverpass()
{
var f = Valdoria();
var rival = f.W.Companies.First(c => !c.IsPlayer).Id;
// lo scenario non ha concorrenti: se ne aggiunge uno fermo (agenti sospesi)
f.W.AiPaused = true;
var rival = WorldFactory.CreateAiCompany(f.W, f.W.Stream("companies")).Id;
f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival);
var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) }));
Assert.True(r.Ok, r.Message);
+11
View File
@@ -9,6 +9,17 @@ public static class TestWorlds
public static World Small(ulong seed = 42, string difficulty = "imprenditore") =>
WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty });
/// <summary>Mondo piccolo con i ritocchi di difficoltà indicati (es. nessun concorrente IA).</summary>
public static World Small(ulong seed, string difficulty, params (string Key, double Value)[] overrides) =>
WorldFactory.Create(TestData.Data, new NewGameSettings
{
Seed = seed, SizeKm = 64, DifficultyId = difficulty,
DifficultyOverride = Core.Data.DifficultyOverrides.Apply(TestData.Data.DifficultyPreset(difficulty), overrides),
});
/// <summary>Mondo piccolo senza concorrenti IA.</summary>
public static World NoAi(ulong seed = 42, string difficulty = "imprenditore") => Small(seed, difficulty, ("aiCompetitors", 0));
public static GeneratedMap Map(ulong seed, int sizeKm) =>
MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear));
}
@@ -4,6 +4,7 @@
"seed": 1872,
"startYear": 1850,
"difficulty": "imprenditore",
"aiCompetitors": 0,
"terrain": {
"widthCells": 160,
"heightCells": 120,