F6: scheda industria e schermata di connessione definitive

La scheda dell'industria e la schermata di connessione si allineano alle
immagini di riferimento 07 e 09. I dati che mancavano li calcola il Core
con una funzione pura, e viaggiano in blocchi compatibili del protocollo.
Il formato dei salvataggi non cambia (ADR 0021).

- IndustryOutlook calcola la scheda in sola lettura:
  - fattori dell'efficienza e quello che la limita;
  - ingressi e uscite al mese, con giorni di scorta o di magazzino;
  - fornitori e clienti con prezzo, distanza e linea che li collega;
  - forza lavoro dai contratti dei pendolari;
  - punteggio di crescita del trimestre con le soglie;
  - prezzo medio, utile annuo, stazioni che la servono, sblocco
    dell'acquisto.
  IndustryMath.GrowthScore è ora l'unica formula del punteggio e la usa
  anche IndustrySystem: gli hash non cambiano. Nuovi parametri in
  balance.json, industry.outlook.
- Protocollo:
  - IndustryCard: blocco 1 IndustrySheetInfo;
  - Welcome: blocco 1 ServerInfo (versione, sistema, Docker, tempo di
    attività, passo del ciclo, client collegati);
  - ClientWorld conserva lo stato del server e l'elenco dei salvataggi.
- Client:
  - IndustryPanel a tutto schermo, con tre schede, il grafo della
    catena, impianti e crescita, e i comandi del proprietario;
  - ConnectScreen sostituisce MenuScreen: server locale o in rete,
    stato del server, partite salvate, «Connetti e riprendi» e «Nuova
    partita sul server» su una sessione di prova;
  - testi in strings.csv;
  - pilota automatico: schermate 19_scheda_industria e 20_connessione.
- Test:
  - IndustryOutlookTests;
  - scheda e stato del server via WebSocket;
  - campioni del protocollo con i blocchi nuovi.
  200 test, 181 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:04:28 +01:00
1 parent 7eec322202
commit 45462bf9ec
28 files changed
+2810 -329

No files matched your search

@@ -1,9 +1,13 @@
keys,it,en
a piena capacità,,at full capacity
Abitanti,,Population
Accetta,,Accept
Acquista,,Buy
Aderisci con le tue azioni,,Tender your shares
adesso,,just now
Aggiorna,,Refresh
al giorno,,per day
al lavoro ora,,at work now
Alto,,High
Ambra,,Amber
Amministrazione controllata,,Receivership
@@ -20,23 +24,29 @@ 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
Attivo da,,Up for
automatico,,automatic
Avvio del server locale…,,Starting the local server…
Azioni proprie (non votano),,Treasury shares (no vote)
Base,,Base
Base d'asta,,Reserve price
bastano per,,enough for
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
Capacità ridotta da un evento,,Capacity reduced by an event
Capitalizz.,,Market cap
Capitalizzazione,,Market cap
Caricamento di,,Loading
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
Catena produttiva,,Production chain
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."
@@ -334,11 +344,21 @@ capacità mancante da,,capacity short for
carica,,load
cavaliere bianco,,white knight
città senza servizi per il personale,,towns without services for staff
Client collegati,,Connected clients
Collegato a,,Connected to
Collo di bottiglia,,Bottleneck
Condizione degli impianti,,Plant condition
Connetti a un server,,Connect to a server
Connetti e riprendi,,Connect and resume
consumo,,use
controlla la compagnia,,controls the company
controllata da,,controlled by
copertura,,coverage
Copertura degli ingressi,,Input coverage
Crea una linea verso questa industria,,Build a line to this industry
Creazione della nuova partita sul server…,,Creating the new game on the server…
da,,from
dati compatibili,,compatible data
degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans.
dei ricavi,,of revenue
del capitale,,of the capital
@@ -346,28 +366,44 @@ 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
Disponibile al livello,,Available at level
dividendo straordinario,,extra dividend
Dove gira il motore di gioco?,,Where does the game engine run?
durata,,duration
e altre,,and
e il,,and
e personale sufficiente,,and enough staff
Fai un'offerta di acquisto,,Make a purchase offer
fallita,,bankrupt
"fallita, attivi all'asta",,"bankrupt, assets at auction"
Fattore di redditività,,Profitability factor
ferma,,stopped
ferma fino al,,stopped until
fermo in linea,,stranded on the line
fermo in salita,,stalled on grade
Forza lavoro,,Workforce
g,,d
Giacimento residuo,,Remaining reserve
Gioca in locale,,Play locally
giorni,,days
giorni di fermo,,days of shutdown
giorni di produzione,,days of production
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
giorni fa,,days ago
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
i lavoratori,,workers
il fondatore ha,,the founder holds
"Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso.",,"The world always lives in a server: on your computer, started together with the game, or on the network, where the game goes on even when the client is closed."
il personale qualificato,,skilled staff
Il server ha chiuso la connessione,,The server closed the connection
Il server non ha risposto,,The server did not respond
impegnato,,committed
Impianti e crescita,,Plant and growth
in arrivo,,arriving
in attesa,,waiting
in attesa di via libera,,waiting for clearance
@@ -378,19 +414,33 @@ in officina,,in the workshop
in scorta,,in stock
in servizio,,in service
in stazione,,at station
inattiva,,inactive
incasso stimato,,estimated proceeds
intervento prenotato,,intervention booked
L'industria è tua: gli utili entrano nel conto economico della compagnia.,,The industry is yours: its profits go into the company's income statement.
la fusione è possibile dopo,,the merger is possible after
la tua compagnia,,your company
large,Grande,Large
Latenza,,Latency
lavoratori,,workers
lavori,,jobs
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
limitata da un evento,,limited by an event
limitata dagli impianti,,limited by the plant
limitata dai lavoratori,,limited by workers
limitata dal giacimento,,limited by the reserve
limitata dal personale,,limited by staff
limitata dalla redditività,,limited by profitability
limitata dalle materie prime,,limited by raw materials
linea,,line
livello,,level
Livello massimo raggiunto,,Maximum level reached
locale,,local
macchinari,,machinery
macchinari per il prossimo lavoro,,machinery for the next job
macchinari per livello,,machinery per level
Mancano,,Missing
Mappa,,Map
medium,Medio,Medium
mesi,,months
mila km,,thousand km
@@ -498,22 +548,56 @@ in 30 giorni,,in 30 days
lug,,Jul
mag,,May
mar,,Mar
Materie prime in ingresso,,Incoming raw materials
mese,,month
mesi e previsione a,,months and forecast for
minuti fa,,minutes ago
Moltiplicatore di resa,,Output multiplier
"nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa",,"in industry storage and at stations, divided by the map's monthly demand"
Nessun cliente nella regione,,No customer in the region
Nessun posto per i lavoratori,,No jobs for workers
Nessun posto per il personale,,No jobs for staff
Nessun vettore la serve: il livello resta fermo finché una linea non la collega.,,No carrier serves it: the level stays put until a line connects it.
Nessuna produzione,,No production
nessuna stazione la serve,,no station serves it
nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino,,none of your stations served by a line with trains has this destination in its catchment
non collegata,,not connected
non collegato,,not connected
Non collegato,,Not connected
nov,,Nov
Nuova partita sul server,,New game on the server
oggi,,today
ore fa,,hours ago
ott,,Oct
Partita in corso,,Current game
perde un livello,,it loses a level
Personale qualificato,,Skilled staff
persone: portale in treno dalle città vicine.,,people: bring them by train from nearby towns.
presenti,,present
prev.,,fcst.
prezzo mondiale in calo,,world price falling
prezzo mondiale in rialzo,,world price rising
Produzione,,Production
proprietari privati,,private owners
provenienze,,more origins
Punteggio di crescita,,Growth score
quota mondiale dagli hub,,world share through the hubs
recupero,,recovery
rispetto al ciclo per circa,,compared with the cycle for about
Scegli un'industria nell'elenco in alto.,,Choose an industry from the list above.
Scheda dell'industria,,Industry sheet
scorta,,stock
serve,,needs
Server locale spento: scegli «Gioca in locale» per avviarlo,,Local server off: choose «Play locally» to start it
"Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui.",,"Server on this computer, started and stopped with the game. Games stay here."
servita dalla stazione,,served by station
servita dalla tua linea,,served by your line
set,,Sep
Sistema,,System
sopra,,above
sotto,,below
spedito,,shipped
tick al secondo,,ticks per second
unità/mese,,units/month
è più alto del,,is higher by
è più basso del,,is lower by
@@ -561,6 +645,8 @@ Scalate ai concorrenti,,Takeovers of rivals
Concessioni,,Concessions
fondata nel,,founded in
con,,with
magazzino,,storage
Partite salvate sul server,,Games saved on the server
verso,,towards
raggiunta nel,,reached in
raggiunta,,reached
@@ -576,14 +662,20 @@ Patrimonio netto di,,Net worth of
città oltre,,towns over
collegata su,,connected out of
collegate su,,connected out of
merci su linea,,goods on a line
Prezzo medio realizzato,,Average realised price
Rating creditizio,,Credit rating
attuale,,current
Binari e opere,,Track and structures
Stazioni e depositi,,Stations and depots
Materiale rotabile,,Rolling stock
Industrie possedute,,Owned industries
magazzino pieno,,storage full
Merce propria,,Own goods
Nessun fornitore nella regione,,No supplier in the region
"Non consuma materie prime: estrae, coltiva o raccoglie da sé.",,"It consumes no raw materials: it mines, farms or gathers on its own."
Partecipazioni,,Shareholdings
"Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa.",,"Dedicated server on the network, for example in Docker on a NAS. Several players, the game is always on."
Totale attivo,,Total assets
Prestiti al,,Loans at
Prestiti,,Loans
@@ -611,6 +703,9 @@ Bancarotta dichiarata,,Bankruptcy declared
La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.,,The company did not bring its cash back above zero within the difficulty limit.
in corso,,in progress
finora,,so far
utile,,profit
Utile annuo stimato,,Estimated annual profit
Valore stimato,,Estimated value
Voce,,Item
Utile operativo,,Operating profit
Flusso di cassa,,Cash flow
@@ -633,6 +728,8 @@ Magazzini,,Storage
Penali,,Penalties
Costruzioni,,Construction
Acquisto di treni,,Train purchases
ultimo trimestre,,last quarter
usura,,wear
Vendita di treni,,Train sales
Prestiti ricevuti,,Loans received
Prestiti rimborsati,,Loans repaid
@@ -660,6 +757,8 @@ Residuo,,Outstanding
fisso,,fixed
Rata mensile,,Monthly payment
interessi,,interest
pieno tra,,full in
Ricorda questo server,,Remember this server
scadenza,,maturity
Estingui,,Pay off
La cassa è tornata positiva,,Cash is back above zero
@@ -670,6 +769,8 @@ Cassa negativa da {0}: bancarotta tra {1},,Cash negative for {0}: bankruptcy in
neutro,,neutral
"Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating.",,"The margin counts once there are at least {0} closed months with revenue (now {1}): until then it is 0, so the first takings do not sink the rating."
"Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese.",,"The score {0} is already worth {1}: the rating is updated at the next monthly calculation, at the start of the month."
Simulazione,,Simulation
trimestri sale,,quarters it rises
un margine di almeno {0},,a margin of at least {0}
una leva non oltre {0},,leverage no higher than {0}
una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repaying {1})
@@ -677,3 +778,7 @@ una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repayi
Per il gradino {0} serve un punteggio di {1}: {2}.,,To reach {0} you need a score of {1}: {2}.
In bancarotta non si possono chiedere prestiti,,Loans cannot be requested while bankrupt
Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni.,,Available credit {0} of {1}. Rate of a new loan: {2} fixed (base {3} + rating {4} {5}) for {6} years.
Verifica connessione,,Test connection
Versione,,Version
Versione del gioco,,Game version
viaggio medio,,average trip
1 keys it en
2 a piena capacità at full capacity
3 Abitanti Population
4 Accetta Accept
5 Acquista Buy
6 Aderisci con le tue azioni Tender your shares
7 adesso just now
8 Aggiorna Refresh
9 al giorno per day
10 al lavoro ora at work now
11 Alto High
12 Ambra Amber
13 Amministrazione controllata Receivership
24 Asta degli attivi Asset auction
25 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
26 Attiva Active
27 Attivo da Up for
28 automatico automatic
29 Avvio del server locale… Starting the local server…
30 Azioni proprie (non votano) Treasury shares (no vote)
31 Base Base
32 Base d'asta Reserve price
33 bastano per enough for
34 Binari Track
35 Binari di stazione Platforms
36 Blu Blue
37 Budget di manutenzione Maintenance budget
38 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.
39 Cantiere Construction
40 Capacità ridotta da un evento Capacity reduced by an event
41 Capitalizz. Market cap
42 Capitalizzazione Market cap
43 Caricamento di Loading
44 Carico Load
45 Cartella di manutenzione Maintenance record
46 Cartella in arrivo dal server… Record on its way from the server…
47 Cassa Cash
48 Cassa dell'industria Industry cash
49 Catena produttiva Production chain
50 Cavaliere bianco White knight
51 Celeste Light blue
52 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.
344 carica load
345 cavaliere bianco white knight
346 città senza servizi per il personale towns without services for staff
347 Client collegati Connected clients
348 Collegato a Connected to
349 Collo di bottiglia Bottleneck
350 Condizione degli impianti Plant condition
351 Connetti a un server Connect to a server
352 Connetti e riprendi Connect and resume
353 consumo use
354 controlla la compagnia controls the company
355 controllata da controlled by
356 copertura coverage
357 Copertura degli ingressi Input coverage
358 Crea una linea verso questa industria Build a line to this industry
359 Creazione della nuova partita sul server… Creating the new game on the server…
360 da from
361 dati compatibili compatible data
362 degli utili come dividendo e non puoi chiedere prestiti. of profits as dividends and cannot take new loans.
363 dei ricavi of revenue
364 del capitale of the capital
366 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
367 delle azioni entro il of the shares by
368 di of
369 Disponibile al livello Available at level
370 dividendo straordinario extra dividend
371 Dove gira il motore di gioco? Where does the game engine run?
372 durata duration
373 e altre and
374 e il and
375 e personale sufficiente and enough staff
376 Fai un'offerta di acquisto Make a purchase offer
377 fallita bankrupt
378 fallita, attivi all'asta bankrupt, assets at auction
379 Fattore di redditività Profitability factor
380 ferma stopped
381 ferma fino al stopped until
382 fermo in linea stranded on the line
383 fermo in salita stalled on grade
384 Forza lavoro Workforce
385 g d
386 Giacimento residuo Remaining reserve
387 Gioca in locale Play locally
388 giorni days
389 giorni di fermo days of shutdown
390 giorni di produzione days of production
391 giorni e liquida le minoranze al prezzo di mercato. days and buys out the minorities at market price.
392 giorni e offre un premio tra il days and offers a premium between
393 giorni fa days ago
394 giorno day
395 gli impianti rendono pieno; sotto calano fino a plants run at full output; below they drop to
396 guasto broken down
397 guasto lieve minor failure
398 hub mercato mondiale world market hub
399 i lavoratori workers
400 il fondatore ha the founder holds
401 Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso. The world always lives in a server: on your computer, started together with the game, or on the network, where the game goes on even when the client is closed.
402 il personale qualificato skilled staff
403 Il server ha chiuso la connessione The server closed the connection
404 Il server non ha risposto The server did not respond
405 impegnato committed
406 Impianti e crescita Plant and growth
407 in arrivo arriving
408 in attesa waiting
409 in attesa di via libera waiting for clearance
414 in scorta in stock
415 in servizio in service
416 in stazione at station
417 inattiva inactive
418 incasso stimato estimated proceeds
419 intervento prenotato intervention booked
420 L'industria è tua: gli utili entrano nel conto economico della compagnia. The industry is yours: its profits go into the company's income statement.
421 la fusione è possibile dopo the merger is possible after
422 la tua compagnia your company
423 large Grande Large
424 Latenza Latency
425 lavoratori workers
426 lavori jobs
427 le città raggiungibili non hanno lavoratori liberi reachable towns have no free workers
428 limitata da un evento limited by an event
429 limitata dagli impianti limited by the plant
430 limitata dai lavoratori limited by workers
431 limitata dal giacimento limited by the reserve
432 limitata dal personale limited by staff
433 limitata dalla redditività limited by profitability
434 limitata dalle materie prime limited by raw materials
435 linea line
436 livello level
437 Livello massimo raggiunto Maximum level reached
438 locale local
439 macchinari machinery
440 macchinari per il prossimo lavoro machinery for the next job
441 macchinari per livello machinery per level
442 Mancano Missing
443 Mappa Map
444 medium Medio Medium
445 mesi months
446 mila km thousand km
548 lug Jul
549 mag May
550 mar Mar
551 Materie prime in ingresso Incoming raw materials
552 mese month
553 mesi e previsione a months and forecast for
554 minuti fa minutes ago
555 Moltiplicatore di resa Output multiplier
556 nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa in industry storage and at stations, divided by the map's monthly demand
557 Nessun cliente nella regione No customer in the region
558 Nessun posto per i lavoratori No jobs for workers
559 Nessun posto per il personale No jobs for staff
560 Nessun vettore la serve: il livello resta fermo finché una linea non la collega. No carrier serves it: the level stays put until a line connects it.
561 Nessuna produzione No production
562 nessuna stazione la serve no station serves it
563 nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino none of your stations served by a line with trains has this destination in its catchment
564 non collegata not connected
565 non collegato not connected
566 Non collegato Not connected
567 nov Nov
568 Nuova partita sul server New game on the server
569 oggi today
570 ore fa hours ago
571 ott Oct
572 Partita in corso Current game
573 perde un livello it loses a level
574 Personale qualificato Skilled staff
575 persone: portale in treno dalle città vicine. people: bring them by train from nearby towns.
576 presenti present
577 prev. fcst.
578 prezzo mondiale in calo world price falling
579 prezzo mondiale in rialzo world price rising
580 Produzione Production
581 proprietari privati private owners
582 provenienze more origins
583 Punteggio di crescita Growth score
584 quota mondiale dagli hub world share through the hubs
585 recupero recovery
586 rispetto al ciclo per circa compared with the cycle for about
587 Scegli un'industria nell'elenco in alto. Choose an industry from the list above.
588 Scheda dell'industria Industry sheet
589 scorta stock
590 serve needs
591 Server locale spento: scegli «Gioca in locale» per avviarlo Local server off: choose «Play locally» to start it
592 Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui. Server on this computer, started and stopped with the game. Games stay here.
593 servita dalla stazione served by station
594 servita dalla tua linea served by your line
595 set Sep
596 Sistema System
597 sopra above
598 sotto below
599 spedito shipped
600 tick al secondo ticks per second
601 unità/mese units/month
602 è più alto del is higher by
603 è più basso del is lower by
645 Concessioni Concessions
646 fondata nel founded in
647 con with
648 magazzino storage
649 Partite salvate sul server Games saved on the server
650 verso towards
651 raggiunta nel reached in
652 raggiunta reached
662 città oltre towns over
663 collegata su connected out of
664 collegate su connected out of
665 merci su linea goods on a line
666 Prezzo medio realizzato Average realised price
667 Rating creditizio Credit rating
668 attuale current
669 Binari e opere Track and structures
670 Stazioni e depositi Stations and depots
671 Materiale rotabile Rolling stock
672 Industrie possedute Owned industries
673 magazzino pieno storage full
674 Merce propria Own goods
675 Nessun fornitore nella regione No supplier in the region
676 Non consuma materie prime: estrae, coltiva o raccoglie da sé. It consumes no raw materials: it mines, farms or gathers on its own.
677 Partecipazioni Shareholdings
678 Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa. Dedicated server on the network, for example in Docker on a NAS. Several players, the game is always on.
679 Totale attivo Total assets
680 Prestiti al Loans at
681 Prestiti Loans
703 La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà. The company did not bring its cash back above zero within the difficulty limit.
704 in corso in progress
705 finora so far
706 utile profit
707 Utile annuo stimato Estimated annual profit
708 Valore stimato Estimated value
709 Voce Item
710 Utile operativo Operating profit
711 Flusso di cassa Cash flow
728 Penali Penalties
729 Costruzioni Construction
730 Acquisto di treni Train purchases
731 ultimo trimestre last quarter
732 usura wear
733 Vendita di treni Train sales
734 Prestiti ricevuti Loans received
735 Prestiti rimborsati Loans repaid
757 fisso fixed
758 Rata mensile Monthly payment
759 interessi interest
760 pieno tra full in
761 Ricorda questo server Remember this server
762 scadenza maturity
763 Estingui Pay off
764 La cassa è tornata positiva Cash is back above zero
769 neutro neutral
770 Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating. The margin counts once there are at least {0} closed months with revenue (now {1}): until then it is 0, so the first takings do not sink the rating.
771 Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese. The score {0} is already worth {1}: the rating is updated at the next monthly calculation, at the start of the month.
772 Simulazione Simulation
773 trimestri sale quarters it rises
774 un margine di almeno {0} a margin of at least {0}
775 una leva non oltre {0} leverage no higher than {0}
776 una leva non oltre {0} (rimborsando {1}) leverage no higher than {0} (by repaying {1})
778 Per il gradino {0} serve un punteggio di {1}: {2}. To reach {0} you need a score of {1}: {2}.
779 In bancarotta non si possono chiedere prestiti Loans cannot be requested while bankrupt
780 Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni. Available credit {0} of {1}. Rate of a new loan: {2} fixed (base {3} + rating {4} {5}) for {6} years.
781 Verifica connessione Test connection
782 Versione Version
783 Versione del gioco Game version
784 viaggio medio average trip
@@ -254,5 +254,28 @@ public partial class AutoPilot : Node
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
await Shot("15_cronaca", 30);
_game.CloseChronicle();
// F6, scheda dell'industria (immagine 07): un'industria di trasformazione vicino alla linea,
// con catena produttiva, forza lavoro e crescita
var processing = World.Industries.Values
.Where(i => !i.Closed && i.Level > 0 && World.Data.Industries.FirstOrDefault(d => d.Id == i.Type)?.Recipe.Inputs.Count > 0)
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).FirstOrDefault() ?? industry;
_game.OpenIndustry(processing.Id);
await Until(() => World.IndustryCards.TryGetValue(processing.Id, out var c) && c.Sheet is not null, "scheda completa dell'industria", 30);
_game.ScrollPanel(0);
await Shot("19_scheda_industria", 40);
// F6, schermata di connessione (immagine 09) sopra la partita: sessione di prova sul server
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
Session.Send(new Save { Name = "Collaudo" });
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
var connect = new ConnectScreen(World.Data, remember: false);
_game.AddChild(connect);
await Frame();
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
await Shot("20_connessione", 30);
connect.QueueFree();
}
}
+22 -37
View File
@@ -8,7 +8,7 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client;
/// <summary>
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
/// </summary>
public partial class Main : Node
@@ -56,12 +56,20 @@ public partial class Main : Node
AddChild(screen);
}
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
private void ShowMenu(string status = "")
{
var menu = new MenuScreen();
menu.LocalGame += StartLocal;
menu.ConnectToServer += ShowConnect;
menu.LanguageChanged += code =>
if (_data is null)
{
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
var label = UiTheme.Text(status, 16, Palette.Danger);
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
Swap(label);
return;
}
var screen = new ConnectScreen(_data);
screen.PlayRequested += ShowGame;
screen.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
@@ -70,32 +78,11 @@ public partial class Main : Node
TranslationServer.SetLocale(code);
ShowMenu();
};
Swap(menu);
if (status.Length > 0) menu.SetStatus(status);
}
private void ShowConnect()
{
var screen = new ConnectScreen();
screen.Back += () => ShowMenu();
screen.ConnectRequested += async (uri, token, label) =>
{
if (_data is null) return;
screen.SetStatus(T("Collegamento in corso…"), busy: true);
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var session = await GameSession.ConnectAsync(_data, uri, token, label, cts.Token);
ShowGame(session);
}
catch (Exception e)
{
screen.SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", busy: false);
}
};
Swap(screen);
if (status.Length > 0) screen.SetStatus(status, error: true);
}
/// <summary>Collaudo: server locale da zero e subito in partita, senza la schermata di connessione.</summary>
private async void StartLocal()
{
if (_data is null) return;
@@ -105,13 +92,11 @@ public partial class Main : Node
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
return;
}
if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…"));
var launcher = new LocalServerLauncher();
try
{
string dataDir = ProjectSettings.GlobalizePath(_autopilot is null ? "user://server" : "user://autopilot-server");
// il collaudo parte sempre da una partita nuova
if (_autopilot is not null && Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
string dataDir = ProjectSettings.GlobalizePath("user://autopilot-server");
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
int port = await launcher.StartAsync(server, dataDir, TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
@@ -141,10 +126,10 @@ public partial class Main : Node
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest && _session is not null)
{
_session.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
_session = null;
}
if (what != NotificationWMCloseRequest) return;
// anche la sessione di prova della schermata di connessione chiude il suo server locale
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
_session = null;
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
}
}
@@ -11,20 +11,35 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
/// Scheda dell'industria a tutto schermo (immagine di riferimento 07, sezione 11): in alto nome,
/// livello, proprietà, stazione che la serve, valore stimato e l'anello dell'efficienza con il
/// fattore che la limita; sotto tre schede (materie prime in ingresso, forza lavoro, produzione), il
/// grafo della catena produttiva con fornitori, città dei pendolari e clienti, e la scheda «Impianti
/// e crescita» con condizione, punteggio trimestrale e soglie, comandi del proprietario e storico dei
/// fermi. Tutti i numeri arrivano dal server nella scheda (IndustryCard, blocco 1: ADR 0021); il
/// pannello li chiede una volta al secondo e li mostra com'è.
/// </summary>
public partial class IndustryPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly OptionButton _chooser = new() { CustomMinimumSize = new Vector2(320, 44), FitToLongestItem = false };
private readonly List<int> _ids = [];
private readonly VBoxContainer _header = PanelKit.Column(8);
private readonly Label _title = UiTheme.TitleLabel("", 44);
private readonly Label _subtitle = UiTheme.Text("", 15, Palette.TextSecondary);
private readonly Label _ownerLine = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _valuation = UiTheme.Text("", 26, Palette.AmberLight, bold: true);
private readonly EfficiencyRing _ring = new();
private readonly Label _limit = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly VBoxContainer _notices = PanelKit.Column(6);
private readonly ScrollContainer _scroll = new() { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly VBoxContainer _inputs = PanelKit.Column(8);
private readonly VBoxContainer _workforce = PanelKit.Column(8);
private readonly VBoxContainer _production = PanelKit.Column(8);
private readonly ChainGraph _graph = new();
private readonly VBoxContainer _chainFooter = PanelKit.Column(8);
private readonly VBoxContainer _plants = PanelKit.Column(8);
private readonly VBoxContainer _controls = PanelKit.Column(8);
private readonly VBoxContainer _details = PanelKit.Column(6);
private readonly VBoxContainer _history = PanelKit.Column(4);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<Button> _budgetButtons = [];
private SpinBox? _partsOrder;
@@ -33,25 +48,106 @@ public partial class IndustryPanel : VBoxContainer
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
/// <summary>«Torna alla mappa».</summary>
public event Action? CloseRequested;
/// <summary>«Crea una linea verso questa industria»: strumento binari centrato sull'industria.</summary>
public event Action<int>? PlanLineRequested;
public IndustryPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_list);
AddChild(PanelKit.Separator());
AddChild(_header);
AddChild(_controls);
AddChild(_details);
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
// barra di navigazione: ritorno alla mappa e scelta dell'industria
var nav = PanelKit.Row(12);
var back = new Button { Text = "‹ " + T("Mappa"), CustomMinimumSize = new Vector2(120, 44) };
back.Pressed += () => CloseRequested?.Invoke();
nav.AddChild(back);
nav.AddChild(_chooser);
_chooser.ItemSelected += i => Select(_ids[(int)i]);
var hint = UiTheme.Text(T("Scheda dell'industria"), 13, Palette.TextSecondary);
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
nav.AddChild(hint);
AddChild(nav);
// intestazione: nome, livello, proprietà, valore ed efficienza
var header = PanelKit.Row(24);
var titles = PanelKit.Column(2);
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_title.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
titles.AddChild(_title);
titles.AddChild(_subtitle);
_ownerLine.AutowrapMode = TextServer.AutowrapMode.WordSmart;
titles.AddChild(_ownerLine);
header.AddChild(titles);
var value = PanelKit.Column(0);
value.SizeFlagsVertical = SizeFlags.ShrinkCenter;
var valueCaption = UiTheme.Text(T("Valore stimato"), 13, Palette.TextSecondary);
valueCaption.HorizontalAlignment = HorizontalAlignment.Right;
_valuation.HorizontalAlignment = HorizontalAlignment.Right;
value.AddChild(valueCaption);
value.AddChild(_valuation);
header.AddChild(value);
var ring = PanelKit.Column(2);
ring.AddChild(_ring);
_limit.HorizontalAlignment = HorizontalAlignment.Center;
_limit.CustomMinimumSize = new Vector2(150, 0);
_limit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
ring.AddChild(_limit);
header.AddChild(ring);
AddChild(header);
AddChild(_notices);
// corpo scorrevole: tre schede, poi catena produttiva e impianti
AddChild(_scroll);
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
_scroll.AddChild(margin);
var body = PanelKit.Column(18);
margin.AddChild(body);
var cards = PanelKit.Row(18);
cards.AddChild(Card(T("Materie prime in ingresso"), _inputs, 1));
cards.AddChild(Card(T("Forza lavoro"), _workforce, 1));
cards.AddChild(Card(T("Produzione"), _production, 1));
body.AddChild(cards);
var lower = PanelKit.Row(18);
var chain = PanelKit.Column(10);
var legend = PanelKit.Row(16);
foreach (var (text, color) in new[] { (T("merci su linea"), Palette.Amber), (T("lavoratori"), Palette.Workers), (T("personale"), Palette.Staff), (T("non collegato"), Palette.TextSecondary) })
legend.AddChild(UiTheme.Text("— " + text, 12, color));
chain.AddChild(legend);
_graph.IndustryClicked += Select;
chain.AddChild(_graph);
chain.AddChild(_chainFooter);
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
var plants = PanelKit.Column(10);
plants.AddChild(_plants);
plants.AddChild(_controls);
plants.AddChild(_history);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_list.ItemSelected += i => Select(_ids[(int)i]);
plants.AddChild(_status);
lower.AddChild(Card(T("Impianti e crescita"), plants, 1));
body.AddChild(lower);
RefreshList();
}
/// <summary>Scheda con titolo e contenuto, larga in proporzione al rapporto dato.</summary>
private static PanelContainer Card(string title, Control content, float ratio)
{
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 22));
var col = PanelKit.Column(12);
col.AddChild(UiTheme.Text(title, 19, bold: true));
col.AddChild(content);
card.AddChild(col);
return card;
}
/// <summary>Industria mostrata (−1 se nessuna).</summary>
public int Industry => _industry;
@@ -60,11 +156,19 @@ public partial class IndustryPanel : VBoxContainer
if (id == _industry) return;
_industry = id;
_status.Text = "";
_scroll.ScrollVertical = 0;
SyncSelection();
Request();
Refresh();
}
/// <summary>Scorre il corpo della scheda (0 in cima, 1 in fondo).</summary>
public void ScrollTo(double fraction)
{
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
private void Request()
{
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
@@ -98,10 +202,17 @@ public partial class IndustryPanel : VBoxContainer
if (w.EntityVersion != _entityVersion) RefreshList();
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
foreach (var c in _header.GetChildren()) c.QueueFree();
foreach (var c in _details.GetChildren()) c.QueueFree();
foreach (var box in new[] { _notices, _inputs, _workforce, _production, _chainFooter, _plants, _history })
foreach (var c in box.GetChildren()) c.QueueFree();
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
{
_title.Text = T("Industrie");
_subtitle.Text = T("Scegli un'industria nell'elenco in alto.");
_ownerLine.Text = "";
_valuation.Text = "";
_limit.Text = "";
_ring.Set(0, Palette.Amber);
_graph.Visible = false;
BuildControls(null);
return;
}
@@ -109,12 +220,24 @@ public partial class IndustryPanel : VBoxContainer
BuildHeader(w, ind, card);
BuildControls(ind);
UpdateControls(ind, card);
BuildDetails(w, ind, card);
var sheet = card?.Sheet;
if (card is null || sheet is null)
{
_graph.Visible = false;
foreach (var box in new[] { _inputs, _workforce, _production, _plants })
box.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
BuildInputs(w, sheet);
BuildWorkforce(w, sheet);
BuildProduction(w, card, sheet);
BuildChain(w, ind, card, sheet);
BuildPlants(w, ind, card, sheet);
}
// ------------------------------------------------------------------ elenco
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
/// <summary>Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
private void RefreshList()
{
var w = _session.World;
@@ -126,7 +249,7 @@ public partial class IndustryPanel : VBoxContainer
if (!same)
{
_ids.Clear();
_list.Clear();
_chooser.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
@@ -137,13 +260,12 @@ public partial class IndustryPanel : VBoxContainer
if (!same)
{
_ids.Add(ind.Id);
_list.AddItem(text);
_chooser.AddItem(text, n);
}
else if (_list.GetItemText(n) != text)
else if (_chooser.GetItemText(n) != text)
{
_list.SetItemText(n, text);
_chooser.SetItemText(n, text);
}
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
}
if (!same) SyncSelection();
}
@@ -151,175 +273,341 @@ public partial class IndustryPanel : VBoxContainer
private void SyncSelection()
{
int index = _ids.IndexOf(_industry);
if (index < 0)
{
_list.DeselectAll();
return;
}
if (!_list.IsSelected(index)) _list.Select(index);
_list.EnsureCurrentIsVisible();
if (index >= 0 && _chooser.Selected != index) _chooser.Select(index);
if (index < 0) _chooser.Select(-1);
}
// ------------------------------------------------------------------ scheda
// ------------------------------------------------------------------ intestazione
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
int me = w.Summary?.CompanyId ?? 0;
var title = UiTheme.TitleLabel(ind.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_header.AddChild(title);
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
var sheet = card?.Sheet;
_title.Text = ind.Name;
string level = sheet is null ? $"{T("Livello")} {ind.Level}" : $"{T("Livello")} {sheet.Level} {T("di")} {sheet.MaxLevel}";
_subtitle.Text = $"{TypeName(w, ind.Type)} · {level}";
string owner = ind.Owner == me ? T("la tua compagnia") : ind.Owner < 0 ? T("proprietari privati") : Fmt.Company(w, ind.Owner);
string served = "";
if (sheet is not null)
{
var names = sheet.ServingStations.Select(s => w.Stations.TryGetValue(s, out var st) ? st.Name : $"#{s}").Take(3).ToList();
served = names.Count == 0
? " · " + T("nessuna stazione la serve")
: $" · {T("servita dalla stazione")} {string.Join(", ", names)}" +
(sheet.ServingLine >= 0 && w.Lines.TryGetValue(sheet.ServingLine, out var line) ? $" ({T("linea")} {line.Name})" : "");
}
_ownerLine.Text = $"{T("Proprietà")}: {owner}{served}";
_valuation.Text = card?.Valuation.ToString() ?? "—";
float e = sheet?.Efficiency ?? ind.Efficiency;
var limit = sheet is null ? IndustryLimit.None : (IndustryLimit)sheet.Limit;
_ring.Set(e, limit is IndustryLimit.None ? Palette.Ok : e < 0.35f ? Palette.Danger : Palette.Amber);
_limit.Text = sheet is null ? T("Efficienza") : $"{T("Efficienza")} · {LimitText(limit)}";
long today = Fmt.Today(w);
if (ind.StoppedUntilDay >= today)
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
_notices.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
else if (ind.PendingWork != 0)
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
_notices.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
if (ind.PartsShort)
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
var stats = PanelKit.Row(8);
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
_header.AddChild(stats);
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
_header.AddChild(bar);
var m = w.Data.Balance.IndustryMaintenance;
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
_notices.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
}
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
// ------------------------------------------------------------------ tre schede
private void BuildInputs(ClientWorld w, IndustrySheetInfo s)
{
if (s.Inputs.Count == 0)
{
_inputs.AddChild(Wrapped(T("Non consuma materie prime: estrae, coltiva o raccoglie da sé."), 13, Palette.TextSecondary));
}
foreach (var f in s.Inputs)
{
string unit = Unit(w, f.Good);
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
_inputs.AddChild(UiTheme.Text($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, unit, supplier: true));
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
_inputs.AddChild(PanelKit.Separator());
}
if (s.Inputs.Count > 0)
_inputs.AddChild(PanelKit.Pair($"{T("Copertura degli ingressi")} ({s.CoverageWindowDays} {T("giorni")})", ColoredValue(Fmt.Pct(s.CovInput, 0), CoverageColor(s.CovInput))));
}
private void BuildWorkforce(ClientWorld w, IndustrySheetInfo s)
{
WorkforceBlock(w, s.Workers, s.CovWorkers, s.CoverageWindowDays, staff: false);
_workforce.AddChild(PanelKit.Separator());
WorkforceBlock(w, s.Staff, s.CovStaff, s.CoverageWindowDays, staff: true);
var limit = (IndustryLimit)s.Limit;
if (limit is IndustryLimit.Workers or IndustryLimit.Staff)
{
var wf = limit == IndustryLimit.Staff ? s.Staff : s.Workers;
string who = limit == IndustryLimit.Staff ? T("il personale qualificato") : T("i lavoratori");
_workforce.AddChild(UiTheme.Notice($"{T("Collo di bottiglia")}: {who}. {T("Mancano")} {wf.Missing} {T("persone: portale in treno dalle città vicine.")}"));
}
}
private void WorkforceBlock(ClientWorld w, WorkforceInfo f, float coverage30, int window, bool staff)
{
var color = staff ? Palette.Staff : Palette.Workers;
if (f.Jobs <= 0)
{
_workforce.AddChild(UiTheme.Text(staff ? T("Nessun posto per il personale") : T("Nessun posto per i lavoratori"), 13, Palette.TextSecondary));
return;
}
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
_workforce.AddChild(UiTheme.Text($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("al lavoro ora")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
if (f.Missing > 0)
{
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
_workforce.AddChild(Wrapped($"{T("Mancano")} {f.Missing}" + (reason.Length > 0 ? " · " + reason : ""), 12, Palette.Amber));
}
foreach (var src in f.Sources)
{
string town = w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}";
string via = src.Walking ? T("a piedi") : src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var line) ? line.Name : Fmt.Company(w, src.Carrier);
string time = src.Walking || src.Minutes <= 0 ? "" : $" · {Fmt.Number(src.Minutes, 0)} min";
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
}
if (f.SourceCount > f.Sources.Count)
_workforce.AddChild(UiTheme.Text($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
}
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
{
foreach (var f in s.Outputs)
{
string unit = Unit(w, f.Good);
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
_production.AddChild(UiTheme.Text($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, unit, supplier: false));
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
_production.AddChild(PanelKit.Separator());
}
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
_production.AddChild(PanelKit.Pair(T("Prezzo medio realizzato"), PanelKit.Value(s.AveragePrice < 0 ? "—" : Fmt.PricePrecise(s.AveragePrice))));
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
}
// ------------------------------------------------------------------ catena produttiva
private void BuildChain(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
{
var left = new List<ChainNode>();
foreach (var f in s.Inputs)
foreach (var p in f.Partners.Take(2))
left.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.Number(p.MonthlyUnits, 0)} {Unit(w, f.Good)}/{T("mese")}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
foreach (var (wf, staff) in new[] { (s.Workers, false), (s.Staff, true) })
foreach (var src in wf.Sources.Take(staff ? 1 : 2))
left.Add(new ChainNode(w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}",
$"{src.Headcount} {(staff ? T("tecnici") : T("lavoratori"))}", staff ? ChainEdge.Staff : ChainEdge.Workers));
var right = new List<ChainNode>();
foreach (var f in s.Outputs)
foreach (var p in f.Partners.Take(3))
right.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.PricePrecise(p.Price)}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
string outputs = string.Join(", ", s.Outputs.Select(f => GoodName(w, f.Good)));
_graph.Set(left, new ChainNode(ind.Name, $"{T("Livello")} {s.Level} · {outputs}", ChainEdge.Goods), right);
_graph.Visible = true;
// azioni della catena: linea verso l'industria e offerta di acquisto
var actions = PanelKit.Row(10);
var plan = UiTheme.Primary(T("Crea una linea verso questa industria"));
plan.CustomMinimumSize = new Vector2(0, 44);
int id = ind.Id;
plan.Pressed += () => PlanLineRequested?.Invoke(id);
actions.AddChild(plan);
int me = w.Summary?.CompanyId ?? 0;
if (ind.Owner != me)
{
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
buy.Pressed += () => _session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), Result);
actions.AddChild(buy);
}
_chainFooter.AddChild(actions);
if (ind.Owner == me)
_chainFooter.AddChild(UiTheme.Text(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
else if (!s.ForSale)
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
else if (!s.BuyUnlocked)
_chainFooter.AddChild(UiTheme.Text($"{T("Disponibile al livello")} «{Fmt.Tier(w, s.BuyTier)}» ({T("avanzamento")} {Fmt.Progress(s.BuyProgress)})", 12, Palette.TextSecondary));
else
_chainFooter.AddChild(UiTheme.Text($"{T("Prezzo chiesto dai proprietari")}: {card.Valuation}", 12, Palette.TextSecondary));
}
// ------------------------------------------------------------------ impianti e crescita
private void BuildPlants(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
{
var condColor = MaintenancePanel.ConditionColor((int)ind.Condition);
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
_plants.AddChild(UiTheme.Text($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
if (s.ReserveFraction >= 0)
_plants.AddChild(PanelKit.Pair(T("Giacimento residuo"), ColoredValue(Fmt.Pct(s.ReserveFraction, 0), s.Depletion < 1 ? Palette.Amber : Palette.Text)));
if (s.EventCapacity < 1) _plants.AddChild(PanelKit.Pair(T("Capacità ridotta da un evento"), ColoredValue("×" + Fmt.Number(s.EventCapacity, 2), Palette.Amber)));
// crescita trimestrale: punteggio in corso, soglie, componenti
_plants.AddChild(PanelKit.Separator());
_plants.AddChild(FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}"));
var bar = new ScoreBar();
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
_plants.AddChild(bar);
_plants.AddChild(UiTheme.Text($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
var g = w.Data.Balance.Growth;
_plants.AddChild(UiTheme.Text($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
if (!s.Served)
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
else if (s.Level >= s.MaxLevel)
_plants.AddChild(UiTheme.Text(T("Livello massimo raggiunto"), 12, Palette.Ok));
int me = w.Summary?.CompanyId ?? 0;
if (ind.Owner == me)
{
_plants.AddChild(PanelKit.Separator());
_plants.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_plants.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_plants.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
}
_history.AddChild(PanelKit.Separator());
_history.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _history.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var stop in Enumerable.Reverse(card.Stops).Take(6))
_history.AddChild(UiTheme.Text($"{Fmt.Date(w, stop.Day)} · {StopName(stop.Kind)} · {stop.Days} {T("giorni")}", 13, stop.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary));
}
/// <summary>Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
private void BuildControls(IndustryInfo? ind)
{
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
int me = _session.World.Summary?.CompanyId ?? 0;
var key = ind is null || ind.Owner != me ? (-1, -1) : (ind.Id, ind.Owner);
if (key == _controlsKey) return;
_controlsKey = key;
foreach (var c in _controls.GetChildren()) c.QueueFree();
_budgetButtons.Clear();
_partsOrder = null;
if (ind is null) return;
if (ind is null || ind.Owner != me) return;
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
int id = ind.Id;
if (ind.Owner == me)
_controls.AddChild(PanelKit.Separator());
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
else if (ind.Owner < 0)
{
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
var price = PanelKit.Value("—");
price.Name = "Price";
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
var buy = UiTheme.Primary(T("Acquista"));
buy.Pressed += () =>
{
if (_session.World.IndustryCards.TryGetValue(id, out var c))
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
else
Request();
};
_controls.AddChild(buy);
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
}
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
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);
}
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)
// ------------------------------------------------------------------ pezzi
private static HBoxContainer FlowHeader(string name, string value, Color? color = null)
{
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);
}
var row = PanelKit.Row(8);
var l = UiTheme.Text(name, 15, color, bold: true);
l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
row.AddChild(l);
row.AddChild(UiTheme.Text(value, 14, bold: true));
return row;
}
private static ProgressBar Bar(float fraction, Color color)
{
var bar = new ProgressBar { MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
return bar;
}
private static Control PartnerLine(ClientWorld w, ChainPartnerInfo p, string unit, bool supplier)
{
string link = p.Line >= 0 && w.Lines.TryGetValue(p.Line, out var line)
? $"{T("linea")} {line.Name}"
: $"{T("non collegata")} · {Fmt.Number(p.DistanceKm, 1)} km";
string amount = (ChainPartnerKind)p.Kind == ChainPartnerKind.Hub ? "" : $" · {Fmt.Number(p.MonthlyUnits, 0)} {unit}/{T("mese")}";
string text = $"{(supplier ? "←" : "→")} {PartnerName(w, p)}{amount} · {Fmt.PricePrecise(p.Price)} · {link}";
return Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
}
private static string PartnerName(ClientWorld w, ChainPartnerInfo p) => (ChainPartnerKind)p.Kind switch
{
ChainPartnerKind.Industry => w.Industries.TryGetValue(p.Target, out var i) ? i.Name : $"#{p.Target}",
ChainPartnerKind.Hub => w.Hubs.TryGetValue(p.Target, out var h) ? h.Name : $"#{p.Target}",
_ => w.Towns.TryGetValue(p.Target, out var t) ? t.Name : $"#{p.Target}",
};
private static int PartnerIndustry(ChainPartnerInfo p) => (ChainPartnerKind)p.Kind == ChainPartnerKind.Industry ? p.Target : -1;
private static bool English => TranslationServer.GetLocale().StartsWith("en");
private static string GoodName(ClientWorld w, int good) =>
good >= 0 && good < w.Data.Goods.Count ? (English ? w.Data.Goods[good].NameEn : w.Data.Goods[good].NameIt) : $"#{good}";
private static string Unit(ClientWorld w, int good) => good >= 0 && good < w.Data.Goods.Count ? w.Data.Goods[good].Unit : "";
private static string TypeName(ClientWorld w, string type)
{
var def = w.Data.Industries.FirstOrDefault(d => d.Id == type);
return def is null ? type : English ? def.NameEn : def.NameIt;
}
private static Color CoverageColor(float coverage) => coverage >= 0.9f ? Palette.Ok : coverage >= 0.5f ? Palette.Amber : Palette.Danger;
private static Control StockRow(string caption, int have, int target, Color color)
{
var row = PanelKit.Row(8);
@@ -335,6 +623,21 @@ public partial class IndustryPanel : VBoxContainer
// ------------------------------------------------------------------ testi
/// <summary>Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.</summary>
public static string LimitText(IndustryLimit limit) => limit switch
{
IndustryLimit.None => T("a piena capacità"),
IndustryLimit.Inputs => T("limitata dalle materie prime"),
IndustryLimit.Workers => T("limitata dai lavoratori"),
IndustryLimit.Staff => T("limitata dal personale"),
IndustryLimit.Profit => T("limitata dalla redditività"),
IndustryLimit.Condition => T("limitata dagli impianti"),
IndustryLimit.Depletion => T("limitata dal giacimento"),
IndustryLimit.Event => T("limitata da un evento"),
IndustryLimit.Stopped => T("ferma"),
_ => T("inattiva"),
};
public static string StopName(byte kind) => kind switch
{
1 => T("Guasto"),
@@ -0,0 +1,185 @@
using Godot;
using RailEnterprise.Client.App;
namespace RailEnterprise.Client.Panels;
/// <summary>Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.</summary>
public partial class EfficiencyRing : Control
{
private float _value;
private Color _color = Palette.Amber;
public EfficiencyRing() => CustomMinimumSize = new Vector2(112, 112);
public void Set(float value, Color color)
{
_value = Math.Clamp(value, 0, 1);
_color = color;
QueueRedraw();
}
public override void _Draw()
{
var c = Size / 2;
float r = Math.Min(Size.X, Size.Y) / 2 - 8;
DrawArc(c, r, 0, Mathf.Tau, 64, Palette.Inner, 10, true);
if (_value > 0) DrawArc(c, r, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * _value, 64, _color, 10, true);
string text = Fmt.Pct(_value, 0);
var font = UiTheme.BodyBold;
const int size = 24;
var s = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
DrawString(font, new Vector2(c.X - s.X / 2, c.Y + s.Y / 4), text, HorizontalAlignment.Left, -1, size, Palette.Text);
}
}
/// <summary>
/// Barra del punteggio di crescita: il riempimento è il punteggio del trimestre in corso, le tacche
/// sono le soglie di declassamento (rossa) e di promozione (verde), la lineetta l'ultimo trimestre.
/// </summary>
public partial class ScoreBar : Control
{
private float _score, _last = -1, _down, _up;
public ScoreBar() => CustomMinimumSize = new Vector2(0, 26);
public void Set(float score, float last, float down, float up)
{
(_score, _last, _down, _up) = (Math.Clamp(score, 0, 1), last, down, up);
QueueRedraw();
}
public override void _Draw()
{
float h = 12, y = 7, w = Size.X;
DrawRect(new Rect2(0, y, w, h), Palette.Inner);
var fill = _score >= _up ? Palette.Ok : _score < _down ? Palette.Danger : Palette.Amber;
DrawRect(new Rect2(0, y, w * _score, h), fill);
DrawLine(new Vector2(w * _down, 2), new Vector2(w * _down, y + h + 5), Palette.Danger, 2);
DrawLine(new Vector2(w * _up, 2), new Vector2(w * _up, y + h + 5), Palette.Ok, 2);
if (_last >= 0) DrawLine(new Vector2(w * Math.Clamp(_last, 0, 1), y - 3), new Vector2(w * Math.Clamp(_last, 0, 1), y + h + 3), Palette.Text, 2);
}
}
/// <summary>Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).</summary>
public enum ChainEdge
{
/// <summary>Merci su una linea della compagnia: linea piena ambra.</summary>
Goods,
/// <summary>Lavoratori pendolari: tratteggio blu.</summary>
Workers,
/// <summary>Personale qualificato: puntinato azzurro.</summary>
Staff,
/// <summary>Partner possibile ma non collegato: tratteggio grigio.</summary>
Unlinked,
}
/// <summary>Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).</summary>
public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
/// <summary>
/// Grafo della catena produttiva: fornitori e città dei pendolari a sinistra, l'industria al centro,
/// clienti a destra. I nodi delle industrie si aprono con un clic.
/// </summary>
public partial class ChainGraph : Control
{
private const float NodeW = 210, NodeH = 50, Gap = 10;
private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
private List<ChainNode> _left = [], _right = [];
private ChainNode? _center;
public event Action<int>? IndustryClicked;
public ChainGraph()
{
CustomMinimumSize = new Vector2(0, 260);
MouseFilter = MouseFilterEnum.Stop;
}
public void Set(List<ChainNode> left, ChainNode center, List<ChainNode> right)
{
(_left, _center, _right) = (left, center, right);
int rows = Math.Max(3, Math.Max(left.Count, right.Count));
CustomMinimumSize = new Vector2(0, rows * (NodeH + Gap) + 10);
QueueRedraw();
}
public override void _Draw()
{
_hits.Clear();
if (_center is null) return;
float w = Size.X, h = Size.Y;
float nodeW = Math.Min(NodeW, (w - 80) / 3);
var centerRect = new Rect2(w / 2 - nodeW / 2, h / 2 - NodeH * 0.7f, nodeW, NodeH * 1.4f);
var leftRects = Column(_left, 0, nodeW, h);
var rightRects = Column(_right, w - nodeW, nodeW, h);
for (int i = 0; i < _left.Count; i++)
Edge(new Vector2(leftRects[i].End.X, leftRects[i].GetCenter().Y), new Vector2(centerRect.Position.X, centerRect.GetCenter().Y), _left[i].Edge);
for (int i = 0; i < _right.Count; i++)
Edge(new Vector2(centerRect.End.X, centerRect.GetCenter().Y), new Vector2(rightRects[i].Position.X, rightRects[i].GetCenter().Y), _right[i].Edge);
for (int i = 0; i < _left.Count; i++) Node(leftRects[i], _left[i], false);
for (int i = 0; i < _right.Count; i++) Node(rightRects[i], _right[i], false);
Node(centerRect, _center, true);
}
private static List<Rect2> Column(List<ChainNode> nodes, float x, float width, float height)
{
float total = nodes.Count * NodeH + Math.Max(0, nodes.Count - 1) * Gap;
float y = (height - total) / 2;
var rects = new List<Rect2>(nodes.Count);
foreach (var _ in nodes)
{
rects.Add(new Rect2(x, y, width, NodeH));
y += NodeH + Gap;
}
return rects;
}
private void Edge(Vector2 from, Vector2 to, ChainEdge edge)
{
switch (edge)
{
case ChainEdge.Goods:
DrawLine(from, to, Palette.Amber, 3, true);
break;
case ChainEdge.Workers:
DrawDashedLine(from, to, Palette.Workers, 2.5f, 10);
break;
case ChainEdge.Staff:
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
break;
default:
DrawDashedLine(from, to, Palette.Border, 2, 8);
break;
}
}
private void Node(Rect2 rect, ChainNode node, bool center)
{
var border = center ? Palette.Amber : node.Edge switch
{
ChainEdge.Goods => Palette.AmberDark,
ChainEdge.Workers => Palette.Workers,
ChainEdge.Staff => Palette.Staff,
_ => Palette.Border,
};
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
var font = UiTheme.BodyBold;
float width = rect.Size.X - 16;
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
center ? Palette.AmberLight : Palette.Text);
DrawString(UiTheme.Body, rect.Position + new Vector2(8, center ? 48 : 39), node.Subtitle, HorizontalAlignment.Left, width, 12, Palette.TextSecondary);
if (node.Industry >= 0) _hits.Add((rect, node));
}
public override void _GuiInput(InputEvent e)
{
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
foreach (var (rect, node) in _hits)
{
if (!rect.HasPoint(click.Position)) continue;
IndustryClicked?.Invoke(node.Industry);
AcceptEvent();
return;
}
}
}
@@ -1,23 +1,66 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
/// Ricorda indirizzo e token in user://settings.cfg.
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione, sistema, tempo di
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
private readonly GameData _data;
private readonly bool _remember;
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
private readonly Button _probe = new() { Text = T("Verifica connessione"), CustomMinimumSize = new Vector2(0, 40) };
private readonly VBoxContainer _remoteFields = new();
private readonly Button _localCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
private readonly GridContainer _stateRows = new() { Columns = 2 };
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly List<string> _saveIds = [];
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private GameSession? _session;
private bool _busy, _local;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
private Action<IMessage>? _awaitingWelcome;
private double _waiting;
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
public ConnectScreen(GameData data, bool remember = true)
{
_data = data;
_remember = remember;
}
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
public override void _Ready()
{
@@ -27,67 +70,539 @@ public partial class ConnectScreen : Control
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var panel = new PanelContainer { CustomMinimumSize = new Vector2(480, 0) };
center.AddChild(panel);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
panel.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Collegati a un server"), 40));
col.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
col.AddChild(_address);
col.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
col.AddChild(_token);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 10);
_connect.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_connect.Pressed += Submit;
row.AddChild(_connect);
var back = new Button { Text = T("Indietro") };
back.Pressed += () => Back?.Invoke();
row.AddChild(back);
col.AddChild(row);
var split = new HBoxContainer();
split.SetAnchorsPreset(LayoutPreset.FullRect);
split.AddThemeConstantOverride("separation", 0);
AddChild(split);
// sinistra: mappa decorativa con il titolo
var left = new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 1.1f, ClipContents = true };
var backdrop = new ConnectBackdrop();
backdrop.SetAnchorsPreset(LayoutPreset.FullRect);
left.AddChild(backdrop);
// titolo in basso a sinistra, sopra il velo della mappa
var brand = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
brand.AnchorLeft = 0;
brand.AnchorRight = 1;
brand.AnchorTop = 1;
brand.AnchorBottom = 1;
brand.OffsetLeft = 56;
brand.OffsetRight = -56;
brand.OffsetTop = -280;
brand.OffsetBottom = -56;
brand.AddThemeConstantOverride("separation", 6);
brand.AddChild(UiTheme.TitleLabel("RAIL ENTERPRISE", 76, Palette.AmberLight));
brand.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 20, Palette.Text));
brand.AddChild(UiTheme.Text($"{T("Versione del gioco")} {ClientVersion}", 13, Palette.TextSecondary));
left.AddChild(brand);
split.AddChild(left);
// destra: dove gira il motore
var right = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 0.9f };
right.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 40));
split.AddChild(right);
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
right.AddChild(scroll);
var col = PanelKit.Column(14);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.SizeFlagsVertical = SizeFlags.ExpandFill;
scroll.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Dove gira il motore di gioco?"), 38));
var lead = UiTheme.Text(T("Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso."), 14, Palette.TextSecondary);
lead.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(lead);
var modes = PanelKit.Row(12);
var group = new ButtonGroup();
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
_localCard.Pressed += () => SetMode(local: true, start: true);
_remoteCard.Pressed += () => SetMode(local: false, start: false);
modes.AddChild(_localCard);
modes.AddChild(_remoteCard);
col.AddChild(modes);
// indirizzo e token del server in rete
_remoteFields.AddThemeConstantOverride("separation", 8);
var fields = PanelKit.Row(10);
var addressCol = PanelKit.Column(4);
addressCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
addressCol.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
addressCol.AddChild(_address);
var tokenCol = PanelKit.Column(4);
tokenCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tokenCol.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
tokenCol.AddChild(_token);
fields.AddChild(addressCol);
fields.AddChild(tokenCol);
_remoteFields.AddChild(fields);
var probeRow = PanelKit.Row(10);
_rememberBox.SizeFlagsHorizontal = SizeFlags.ExpandFill;
probeRow.AddChild(_rememberBox);
_probe.Pressed += SubmitRemote;
probeRow.AddChild(_probe);
_remoteFields.AddChild(probeRow);
_token.TextSubmitted += _ => SubmitRemote();
col.AddChild(_remoteFields);
// stato del server
var state = new PanelContainer();
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
var stateCol = PanelKit.Column(10);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateRows.AddThemeConstantOverride("h_separation", 24);
_stateRows.AddThemeConstantOverride("v_separation", 6);
stateCol.AddChild(_stateRows);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_saves.ItemActivated += _ => Resume();
col.AddChild(_saves);
var actions = PanelKit.Row(10);
_resume.CustomMinimumSize = new Vector2(0, 48);
_resume.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_resume.Pressed += Resume;
actions.AddChild(_resume);
_newGame.CustomMinimumSize = new Vector2(0, 48);
_newGame.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_newGame.Pressed += NewGameOnServer;
actions.AddChild(_newGame);
col.AddChild(actions);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
col.AddChild(UiTheme.Notice(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).")));
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
// piede: lingua, uscita, avviso sulla cifratura
var foot = PanelKit.Row(8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
foot.AddChild(b);
}
_token.TextSubmitted += _ => Submit();
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
quit.Pressed += () => GetTree().Quit();
foot.AddChild(quit);
col.AddChild(foot);
var notice = UiTheme.Text(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://)."), 12, Palette.TextSecondary);
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(notice);
bool remote = false;
if (_remember)
{
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
}
}
SetMode(local: !remote, start: false);
ShowState();
}
public void SetStatus(string text, bool busy)
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
{
_status.Text = text;
_connect.Disabled = busy;
card.ButtonGroup = group;
card.AddThemeStyleboxOverride("normal", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
var col = PanelKit.Column(6);
col.MouseFilter = MouseFilterEnum.Ignore;
var t = UiTheme.Text(title, 17, Palette.AmberLight, bold: true);
var d = UiTheme.Text(text, 12, Palette.TextSecondary);
d.AutowrapMode = TextServer.AutowrapMode.WordSmart;
t.MouseFilter = d.MouseFilter = MouseFilterEnum.Ignore;
col.AddChild(t);
col.AddChild(d);
margin.AddChild(col);
card.AddChild(margin);
}
private void Submit()
private static string ClientVersion =>
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// ------------------------------------------------------------------ modalità e sessione di prova
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
ShowState();
}
/// <summary>Avvia il server locale figlio del gioco e apre la sessione di prova.</summary>
private async Task StartLocal()
{
if (_busy) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
return;
}
await Release();
_busy = true;
SetStatus(T("Avvio del server locale…"));
ShowState();
var launcher = new LocalServerLauncher();
try
{
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
Attach(session);
}
catch (Exception e)
{
launcher.Dispose();
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void SubmitRemote()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), false);
SetStatus(T("Indica l'indirizzo del server"), error: true);
return;
}
string url = address.Contains("://") ? address : $"ws://{address}";
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
SetStatus(T("Indirizzo non valido"), false);
SetStatus(T("Indirizzo non valido"), error: true);
return;
}
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", address);
cfg.SetValue("server", "token", _token.Text);
cfg.Save(SettingsPath);
ConnectRequested?.Invoke(uri, _token.Text, uri.Host);
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", _rememberBox.ButtonPressed ? address : "");
cfg.SetValue("server", "token", _rememberBox.ButtonPressed ? _token.Text : "");
cfg.Save(SettingsPath);
}
_ = ProbeRemote(uri, _token.Text);
}
/// <summary>Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).</summary>
public async Task ProbeRemote(Uri uri, string token)
{
if (_busy) return;
SetMode(local: false, start: false);
await Release();
_busy = true;
SetStatus(T("Collegamento in corso…"));
ShowState();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
SetStatus("");
}
catch (Exception e)
{
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void Attach(GameSession session)
{
_session = session;
_shownSaves = null;
_sinceSaves = double.MaxValue;
_session.MessageApplied += OnMessage;
}
/// <summary>Chiude la sessione di prova (e il server locale, se è suo).</summary>
private async Task Release()
{
var s = _session;
_session = null;
_shownSaves = null;
_awaitingWelcome = null;
if (s is null) return;
s.MessageApplied -= OnMessage;
await s.DisposeAsync();
}
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
return s;
}
public override void _ExitTree()
{
if (_session is not null) _ = Release();
}
private void OnMessage(IMessage m) => _awaitingWelcome?.Invoke(m);
public override void _Process(double delta)
{
if (_session is null) return;
_session.Poll();
if (!_session.IsOpen)
{
SetStatus(T("Il server ha chiuso la connessione"), error: true);
_ = Release();
ShowState();
return;
}
_sinceSaves += delta;
if (_awaitingWelcome is not null && (_waiting += delta) > WelcomeTimeoutS)
{
_awaitingWelcome = null;
SetStatus(T("Il server non ha risposto"), error: true);
}
if (_sinceSaves >= SavesRefreshS && _awaitingWelcome is null)
{
_sinceSaves = 0;
_session.Send(new ListSaves());
}
if (!ReferenceEquals(_session.World.Saves, _shownSaves)) ShowSaves();
ShowState();
}
// ------------------------------------------------------------------ azioni
private void Resume()
{
if (_session is null || _awaitingWelcome is not null) return;
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
if (index <= 0 || index > _saveIds.Count)
{
Play();
return;
}
string id = _saveIds[index - 1];
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
}
private void NewGameOnServer()
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
}
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
private void AwaitWelcome()
{
_awaitingWelcome = m =>
{
if (m is Welcome)
{
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
{
// caricamento o creazione rifiutati: il server risponde con un avviso
_awaitingWelcome = null;
SetStatus(note.Event.Text, error: true);
}
};
_waiting = 0;
}
private void Play()
{
var s = TakeSession();
if (s is not null) PlayRequested?.Invoke(s);
}
// ------------------------------------------------------------------ stato
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
private void ShowState()
{
var info = _session?.World.Server;
var summary = _session?.World.Summary;
string title;
Color dot;
if (_busy)
{
title = _local ? T("Avvio del server locale…") : T("Collegamento in corso…");
dot = Palette.Amber;
}
else if (_session is not null)
{
title = $"{T("Collegato a")} {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var rows = new List<(string, string)>
{
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds)),
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
};
if (_stateRows.GetChildCount() != rows.Count * 2)
{
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
foreach (var (caption, _) in rows)
{
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
}
}
for (int i = 0; i < rows.Count; i++)
{
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
}
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
_resume.Disabled = !ready;
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
}
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
_saves.Clear();
_saveIds.Clear();
string company = w.Summary?.CompanyName ?? "";
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs))
{
_saveIds.Add(s.SaveId);
string kind = s.Autosave ? $" ({T("automatico")})" : "";
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
}
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
}
private static string Uptime(long seconds)
{
if (seconds < 3600) return $"{Math.Max(1, seconds / 60)} min";
if (seconds < 86_400) return $"{seconds / 3600} h {seconds % 3600 / 60} min";
return $"{seconds / 86_400} {T("giorni")} {seconds % 86_400 / 3600} h";
}
private static string Ago(double seconds)
{
if (seconds < 90) return T("adesso");
if (seconds < 3600) return $"{(int)(seconds / 60)} {T("minuti fa")}";
if (seconds < 86_400) return $"{(int)(seconds / 3600)} {T("ore fa")}";
return $"{(int)(seconds / 86_400)} {T("giorni fa")}";
}
}
/// <summary>
/// Mappa decorativa della schermata iniziale: pianura, un fiume, una linea a doppio binario con
/// stazioni e i tetti dei paesi, disegnati in codice con la palette della mappa (immagine 05) e
/// velati verso il basso per il titolo. Solo grafica: nessun dato di gioco.
/// </summary>
public partial class ConnectBackdrop : Control
{
public override void _Draw()
{
var size = Size;
DrawRect(new Rect2(Vector2.Zero, size), Palette.Plain);
// colline e boschi a macchie, posizioni fisse in frazioni della superficie
foreach (var (x, y, r, c) in new[] { (0.15f, 0.2f, 0.16f, Palette.Hill), (0.7f, 0.15f, 0.2f, Palette.Highland), (0.85f, 0.55f, 0.14f, Palette.Undergrowth),
(0.3f, 0.6f, 0.12f, Palette.Undergrowth), (0.55f, 0.35f, 0.07f, Palette.Canopy), (0.1f, 0.45f, 0.06f, Palette.Canopy), (0.62f, 0.72f, 0.05f, Palette.Canopy) })
DrawCircle(new Vector2(x * size.X, y * size.Y), r * Math.Max(size.X, size.Y), c);
// fiume
var river = new Vector2[] { new(0.62f, 0f), new(0.58f, 0.18f), new(0.66f, 0.36f), new(0.6f, 0.55f), new(0.7f, 0.78f), new(0.66f, 1f) };
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Banks, 30, true);
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Water, 20, true);
// linea ferroviaria: massicciata, traversine, rotaie
var rail = new Vector2[] { new(-0.05f, 0.42f), new(0.25f, 0.38f), new(0.48f, 0.44f), new(0.75f, 0.4f), new(1.05f, 0.3f) };
var pts = rail.Select(p => p * size).ToArray();
DrawPolyline(pts, Palette.Ballast, 16, true);
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
var dir = (b - a).Normalized();
var n = new Vector2(-dir.Y, dir.X) * 7;
for (float t = 0; t < a.DistanceTo(b); t += 9)
{
var p = a + dir * t;
DrawLine(p - n, p + n, Palette.Sleepers, 3);
}
}
foreach (float off in new[] { -3.5f, 3.5f })
DrawPolyline(pts.Select((p, i) => p + Normal(pts, i) * off).ToArray(), Palette.Rails, 1.5f, true);
// stazioni e paesi
foreach (var (x, y) in new[] { (0.25f, 0.38f), (0.75f, 0.4f) })
{
var c = new Vector2(x * size.X, y * size.Y);
DrawRect(new Rect2(c - new Vector2(22, 26), new Vector2(44, 14)), Palette.Panel);
for (int k = 0; k < 9; k++)
{
var roof = c + new Vector2((k % 3 - 1) * 26 + (k * 7 % 5), 28 + k / 3 * 20);
DrawRect(new Rect2(roof, new Vector2(16, 12)), k % 4 == 0 ? Palette.IndustrialRoof : Palette.TileRoof);
}
}
// velo verso il basso per leggere il titolo
var veil = new Color[] { Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.92f), Palette.WithAlpha(Palette.AppBackground, 0.92f) };
DrawPolygon([new Vector2(0, size.Y * 0.35f), new Vector2(size.X, size.Y * 0.35f), new Vector2(size.X, size.Y), new Vector2(0, size.Y)], veil);
}
private static Vector2 Normal(Vector2[] pts, int i)
{
var dir = (pts[Math.Min(i + 1, pts.Length - 1)] - pts[Math.Max(i - 1, 0)]).Normalized();
return new Vector2(-dir.Y, dir.X);
}
public override void _Notification(int what)
{
if (what == NotificationResized) QueueRedraw();
}
}
@@ -98,7 +98,7 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
/// <summary>Apre la scheda dell'industria a tutto schermo (immagine 07) sull'industria indicata.</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
@@ -142,6 +142,17 @@ public partial class GameScreen : Node
}
}
/// <summary>Dalla scheda dell'industria: strumento binari con la mappa centrata sull'industria da collegare.</summary>
private void PlanLineToIndustry(int industry)
{
_toolbar.Select(Tool.Track);
if (_session.World.Industries.TryGetValue(industry, out var ind))
{
_map.CenterOn(MapScale.V(ind.Position));
_map.SetZoom(0.3f);
}
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
@@ -161,6 +172,11 @@ public partial class GameScreen : Node
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
if (_industryPanel is not null)
{
_industryPanel.ScrollTo(fraction);
return;
}
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
@@ -411,7 +427,7 @@ public partial class GameScreen : Node
_climb = null;
_finance = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance;
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance or Tool.Industries;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
@@ -465,7 +481,11 @@ public partial class GameScreen : Node
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
_industryPanel = new IndustryPanel(_session);
_industryPanel.CloseRequested += () => _toolbar.Select(Tool.None);
_industryPanel.PlanLineRequested += PlanLineToIndustry;
_full.AddChild(_industryPanel);
panel = NewInfoPanel();
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
@@ -791,7 +811,8 @@ public partial class GameScreen : Node
_chronicleScreen = screen;
}
private void CloseChronicle()
/// <summary>Chiude la Cronaca se è aperta.</summary>
public void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
@@ -1,56 +0,0 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
public partial class MenuScreen : Control
{
public event Action? LocalGame;
public event Action? ConnectToServer;
public event Action<string>? LanguageChanged;
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
public override void _Ready()
{
// 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);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var col = new VBoxContainer { CustomMinimumSize = new Vector2(440, 0) };
col.AddThemeConstantOverride("separation", 14);
center.AddChild(col);
col.AddChild(UiTheme.TitleLabel("Rail Enterprise", 96));
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
var local = UiTheme.Primary(T("Partita locale"));
local.CustomMinimumSize = new Vector2(0, 48);
local.Pressed += () => LocalGame?.Invoke();
col.AddChild(local);
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
remote.Pressed += () => ConnectToServer?.Invoke();
col.AddChild(remote);
var lang = new HBoxContainer();
lang.AddThemeConstantOverride("separation", 8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
lang.AddChild(b);
}
col.AddChild(lang);
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
quit.Pressed += () => GetTree().Quit();
col.AddChild(quit);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
}
public void SetStatus(string text) => _status.Text = text;
}
@@ -1 +0,0 @@
uid://b5eyw35w2vo7l
+2 -1
View File
@@ -67,7 +67,8 @@
"initialStockDays": 10,
"footprintCells": { "small": 2, "medium": 3, "large": 4 },
"depletionStartFraction": 0.20,
"startingCash": 2000000
"startingCash": 2000000,
"outlook": { "partnersPerGood": 3, "workforceSources": 4 }
},
"growth": {
"quarterDays": 90,
+3 -3
View File
@@ -92,7 +92,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
## 6. Economia e contabilità
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio. `ClimbOutlook` (F6, ADR 0018) è l'analisi in sola lettura per «La tua scalata»: livelli con gli sblocchi dai dati (`Tiers.NewUnlocks`), requisiti del prossimo livello con l'avanzamento (media delle tre frazioni, usata anche dal Mercato globale), stato patrimoniale per voce che somma al patrimonio netto del motore, conto economico, prestiti, storico del patrimonio dalla Cronaca. `FinanceOutlook` (F6, ADR 0019) è l'analisi in sola lettura per il pannello «Finanze»: conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni chiusi) che somma all'utile operativo del motore, spiegazione del rating (misure, componenti, soglie, cosa serve per salire), prestiti con rata e scadenza, fido, giorni di cassa negativa sul limite della difficoltà.
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio. `ClimbOutlook` (F6, ADR 0018) è l'analisi in sola lettura per «La tua scalata»: livelli con gli sblocchi dai dati (`Tiers.NewUnlocks`), requisiti del prossimo livello con l'avanzamento (media delle tre frazioni, usata anche dal Mercato globale), stato patrimoniale per voce che somma al patrimonio netto del motore, conto economico, prestiti, storico del patrimonio dalla Cronaca. `FinanceOutlook` (F6, ADR 0019) è l'analisi in sola lettura per il pannello «Finanze»: conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni chiusi) che somma all'utile operativo del motore, spiegazione del rating (misure, componenti, soglie, cosa serve per salire), prestiti con rata e scadenza, fido, giorni di cassa negativa sul limite della difficoltà. `IndustryOutlook` (F6, ADR 0021) è l'analisi in sola lettura per la scheda dell'industria: fattori dell'efficienza e quello che la limita, ingressi e uscite al mese con giorni di scorta o di magazzino, fornitori e clienti con prezzo e linea che li collega, forza lavoro dai contratti dei pendolari, punteggio di crescita del trimestre (`IndustryMath.GrowthScore`, la stessa formula del motore) con le soglie, sblocco dell'acquisto.
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno; `LedgerEntries` ne fissa l'ordine e le sezioni (ricavi, costi, investimenti e finanziamenti) e `Company.OperatingProfit` è la somma di ricavi e costi (ADR 0019). Un trasferimento può usare voci diverse per chi paga e chi incassa (dividendi pagati e incassati).
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, magazzini delle compagnie nelle stazioni, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
- Compravendita in proprio (F6, ADR 0016): `TradingCommandHandlers` esegue `BuyGoods`, `SellGoods` e `ShipGoods` con il prezzo locale marginale di `Systems/TradingMath` (unità per unità, controparti ordinate per prezzo). La merce comprata sta in `Station.Stock`; quella spedita viaggia in pacchetti con `Packet.Owned`, senza tariffa né consumatore, ed entra nel magazzino della stazione d'arrivo. Gli scambi con le industrie passano dal registro sulla voce «Commercio», quelli con gli hub contano come importazione ed esportazione; `StationSystem` addebita ogni mese la giacenza dei magazzini.
@@ -124,10 +124,10 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
## 9. Client
- Progetto Godot 4.7 .NET in `client/RailEnterprise.Client` (fuori dalla soluzione), compilato con `Godot.NET.Sdk`; referenzia Core e Protocol (net8.0). I file dati e gli schemi si copiano in `res://data` a ogni build.
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
- `Main` → `ConnectScreen` (immagine 09: server locale o in rete, stato dal blocco `ServerInfo` del `Welcome`, partite salvate, riprendi o nuova partita su una sessione di prova che poi diventa la partita) → `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`; scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`, e la scheda dell'industria (`IndustryPanel`, immagine 07: ingressi, forza lavoro, produzione, grafo della catena `ChainGraph`, impianti e crescita, dati da `IndustryOutlook` nel blocco 1 di `IndustryCard`); scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
## 10. Prestazioni
+14 -2
View File
@@ -51,7 +51,7 @@ offset tipo campo
```
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64, dataHash: u64 }
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }; blocco 1 (F6): server: ServerInfo
| Reject { code: u16, reason: string }
```
@@ -59,6 +59,13 @@ Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, diffi
- `dataHash` ≠ 0 deve coincidere con l'hash dei dati del server.
- Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4 server pieno, 5 nessuna partita.
- `Welcome` può arrivare di nuovo durante la sessione (nuova partita o caricamento): il client azzera la copia del mondo.
- Blocco 1 del `Welcome` (F6, ADR 0021): stato del server per la schermata di connessione (immagine 09), calcolato
all'invio del `Welcome`.
`ServerInfo { version: string (versione del server), os: string (sistema operativo), container: bool (in Docker),
uptimeSeconds: i64 (da quando il processo è attivo), tickMs: f32 (passo del ciclo di gioco: 1000 / tickMs tick al
secondo), sessions: i32 (client collegati, compreso chi riceve il messaggio), maxSessions: i32, local: bool (server
figlio del gioco) }`. La latenza non viaggia: il client la misura con `Ping`/`Pong`.
`WorldSummary { seed: u64, sizeKm: i32, startYear: i32, tick: i64, date: string, companyId: i32, companyName: string,
regionId: string, widthCells: i32, heightCells: i32, cellSizeM: f64, chunkCells: i32, speed: u8, terrainHash: u64,
@@ -153,7 +160,7 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
| 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) |
| 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); blocco 1 (F6): `sheet: IndustrySheetInfo`, la scheda dell'immagine 07 calcolata dal Core (`IndustryOutlook`) per la compagnia della sessione (ADR 0021) |
| 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) |
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool`; blocco 1: `warehouses: [WarehouseInfo]` (magazzini della compagnia, solo se ne ha; ADR 0016); blocco 2: `goodEvents: [WorldEventInfo]` (eventi del mondo sulla domanda di un bene, mostrati come «evento in corso»; ADR 0017). I due blocchi sono indipendenti: `flags` bit 0 e bit 1, in quest'ordine (su richiesta, F6; ADR 0015) |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
@@ -204,6 +211,11 @@ Record (ognuno chiude con `flags`):
- `FinanceLineInfo { kind: u8 (LedgerEntry), section: u8 (0 ricavi, 1 costi, 2 investimenti e finanziamenti) }`, `IncomeColumnInfo { kind: u8 (0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso), year: i32, month: u8 (1–12, 0 per gli anni), values: [AmountInfo] (solo le voci diverse da zero, kind = LedgerEntry, con segno), profit: Money (utile operativo del motore), cashFlow: Money }`, `RatingThresholdInfo { rating: string, minScore, loanRate: f32 }`, `FinanceLoanInfo { loan: i32, principal, remaining: Money, annualRate: f32 (fisso), monthsLeft: i32, payment, nextInterest: Money, maturityDay: i64 }`
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
- `WarehouseInfo { station, capacity, incoming: i32 (merce propria in viaggio verso la stazione), goods: [WarehouseGoodInfo] }` (stazioni vive della compagnia)
- `IndustrySheetInfo { level, maxLevel: u8, efficiency: f32, limit: u8 (fattore più basso sotto 1: 0 nessuno, 1 materie prime, 2 lavoratori, 3 personale, 4 redditività, 5 impianti, 6 giacimento, 7 evento, 8 ferma, 9 inattiva), covInput, covWorkers, covStaff: f32 (coperture medie mobili), coverageWindowDays: i32 (finestra delle coperture), profitFactor, depletion, eventCapacity: f32, reserveFraction: f32 (−1 senza giacimento), storageDays: i32, inputs: [IndustryFlowInfo], outputs: [IndustryFlowInfo], workers: WorkforceInfo, staff: WorkforceInfo, averagePrice: f64 (centesimi; −1 se non calcolabile), annualProfit: Money (utile annuo stimato dalle medie mobili), lastScore, shipped, coverage, profit, score: f32 (punteggio di crescita del trimestre in corso e componenti), upgradeThreshold, downgradeThreshold: f32, upgradeQuarters, quartersAbove: u8, quarterDay, quarterDays: i32, served: bool (servita da un vettore: solo allora cambia livello), servingStations: [i32], servingLine: i32 (−1 nessuna), forSale, buyUnlocked: bool, buyTier: u8, buyProgress: f32 }`
- `IndustryFlowInfo { good: i32, fullMonth: f32 (a piena capacità, unità al mese), currentMonth: f32 (all'efficienza di oggi), stock, storage: i32, days: f32 (ingressi: giorni di scorta; uscite: giorni al magazzino pieno; −1 senza consumo o produzione), limiting: bool (l'ingresso che limita), partners: [ChainPartnerInfo] }`
- `ChainPartnerInfo { kind: u8 (0 industria, 1 hub, 2 città), target: i32, monthlyUnits: f32 (produzione o fabbisogno mensile del partner), price: f64 (centesimi: prezzo globale, locale o dell'hub), line: i32 (linea della compagnia con treni che serve entrambi; −1 non collegato), distanceKm: f32 }`: fornitori per gli ingressi, clienti per le uscite, prima i collegati poi i più vicini, al massimo `industry.outlook.partnersPerGood`
- `WorkforceInfo { jobs: i32, present, onSite, coverage: f32, missing: i32, reason: u8 (come `EmploymentRow`), reasonLine: i32, averageMinutes: f32 (−1 senza pendolari in treno), sourceCount: i32, sources: [WorkforceSourceInfo] }` (al massimo `industry.outlook.workforceSources` provenienze)
- `WorkforceSourceInfo { town, headcount: i32, coverage: f32, line: i32, carrier: i32, minutes: f32, walking: bool }`
- `WarehouseGoodInfo { good, units: i32 (in magazzino), buyPrice: f64 (centesimi, prossima unità; −1 nessun venditore), buyUnits: i32, sellPrice: f64 (−1 nessun compratore), sellUnits: i32 }` (beni in magazzino o scambiabili nel bacino)
## 6. Flusso e interest management
+34 -3
View File
@@ -141,18 +141,49 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
- client: pannello «Finanze» a tutto schermo (`FinancePanel`): conto economico con «Mesi» e «Anni», rating con misure e «per salire…», soglie e tassi, prestiti con rata, interessi, scadenza, «Rimborsa» ed «Estingui», richiesta con fido e tasso, barra dei giorni di cassa negativa solo con lo scoperto; frasi intere con segnaposto in `strings.csv`; schermata `18_finanze` nel pilota automatico (non provata qui: manca l'editor);
- IA invariate: usano gli stessi comandi di prestito; accettazione F5 (un'IA al livello 3 in 15 anni) e F4 (35 / 20 guasti senza la linea, 75 / 2 con la linea) invariate;
- test (`Economy/FinanceTests.cs`, 19, più il quadro via WebSocket in `ServerTests` e il round-trip di `FinanceReport`): tasso per rating e fisso, fido dal livello e rifiuti, interessi e quota capitale sul registro, rimborso parziale e totale, rating dalle due misure e leva infinita, spiegazione che porta al gradino sopra e rimborso possibile con la cassa, punteggio che basta già (senza infiniti), margine neutro ai primi incassi, finestra di 12 mesi, conto economico che somma all'utile, stipendi dei depositi, dazi, magazzini, dividendi incassati nell'utile, avvisi e bancarotta ai giorni di ogni preset (lento), rientro e oscillazioni senza notizie, quota dei trasporti senza dividendi, salvataggio versione 7 e migrazione dalla 6, determinismo con gli invarianti, proiezione. 194 test (175 senza i lenti).
- Restano della F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot.
- **Scheda dell'industria e schermata di connessione (issue #42, ADR 0021)**:
- `IndustryOutlook` (Core, sola lettura): la scheda dell'immagine 07 è calcolata con le stesse formule del motore. Contiene:
- i fattori dell'efficienza e il fattore che la limita (`IndustryLimit`);
- per ogni ingresso e uscita: quantità al mese a piena capacità e attuale, scorta, capienza, giorni di scorta o al magazzino pieno;
- fornitori e clienti (industrie, hub, città) con fabbisogno o produzione mensile, prezzo (globale, locale o dell'hub), distanza e la linea della compagnia che li collega;
- forza lavoro dai contratti dei pendolari: posti, presenti, al lavoro, mancanti, motivo, provenienze, viaggio medio;
- crescita: punteggio del trimestre in corso con le componenti, soglie, trimestri sopra soglia, servita o no;
- prezzo medio realizzato, utile annuo stimato, stazioni e linea che la servono, sblocco dell'acquisto con l'avanzamento.
`IndustryMath.GrowthScore` è ora l'unica formula del punteggio (anche per `IndustrySystem.Quarter`, hash invariati). Parametri di presentazione in `balance.json → industry.outlook` (`partnersPerGood` 3, `workforceSources` 4).
- protocollo:
- blocco 1 di `IndustryCard`: `IndustrySheetInfo` con `IndustryFlowInfo`, `ChainPartnerInfo`, `WorkforceInfo`, `WorkforceSourceInfo`;
- blocco 1 del `Welcome`: `ServerInfo` con versione, sistema, Docker, tempo di attività, passo del ciclo, client collegati e massimi, locale;
- `ClientWorld.Server` e `ClientWorld.Saves` (risposta a `ListSaves` e `Save`).
Server: scheda per qualunque industria richiesta, calcolata per la compagnia della sessione.
- client:
- scheda dell'industria a tutto schermo come l'immagine 07 (`IndustryPanel`):
- selettore dell'industria, intestazione con livello su massimo, proprietà, stazione e linea, valore stimato, anello dell'efficienza con il fattore che la limita;
- schede «Materie prime in ingresso», «Forza lavoro» con il collo di bottiglia, «Produzione»;
- grafo «Catena produttiva» (`ChainGraph`: merci su linea, lavoratori, personale, non collegato; i nodi delle industrie si aprono), «Crea una linea verso questa industria» e «Fai un'offerta di acquisto» o il livello che la sblocca con l'avanzamento;
- «Impianti e crescita» con condizione, resa, rischio di fermo, barra del punteggio con le soglie, comandi del proprietario e storico dei fermi;
- schermata iniziale e di connessione come l'immagine 09 (`ConnectScreen`, al posto di `MenuScreen`):
- mappa decorativa con il titolo e «Dove gira il motore di gioco?»;
- «Gioca in locale» e «Connetti a un server» con indirizzo, token e «Ricorda questo server»;
- stato del server: versione, sistema, attivo da, tick al secondo, latenza, client collegati;
- «Partite salvate sul server», «Connetti e riprendi» (`Load` e attesa del `Welcome`), «Nuova partita sul server»;
- testi in `strings.csv`; schermate `19_scheda_industria` e `20_connessione` in coda al pilota automatico (non provate qui: manca l'editor).
- test:
- `Economy/IndustryOutlookTests.cs`, 5: scheda dell'acciaieria servita (fornitore collegato, clienti al prezzo locale e all'hub, stazione e linea, crescita, sblocco, hash invariato), forza lavoro dai contratti, fattore limitante per ogni causa, pesi del punteggio, round-trip nella `IndustryCard` e carta vecchia senza scheda;
- `ServerTests`: scheda via WebSocket attesa come risposta nuova, `ServerInfo` nel `Welcome`, elenco dei salvataggi dopo `Save`;
- campioni del protocollo con i blocchi nuovi.
200 test (181 senza i lenti).
- Restano della F6: ere e obsolescenza, tooltip «perché», tutorial, audio, bilanciamento con i bot.
## Prossimo passo
- F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
- F6: ere e obsolescenza, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
## Limiti noti
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 e «La tua scalata» alla 08 (F6, non ancora provati in Godot: qui manca l'editor); Industria e la schermata di connessione vanno allineati in F6.
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06, la scheda dell'industria alla 07, «La tua scalata» alla 08 e la schermata di connessione alla 09 (F6, non ancora provati in Godot: qui manca l'editor). Della 07 mancano le quantità consegnate su ogni collegamento della catena (il motore non le registra: si mostrano produzione o fabbisogno del partner, prezzo e linea) e quantità diverse per ingresso (il consumo segue la ricetta); lo stato del server nella 09 è quello del collegamento (ADR 0021).
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
@@ -0,0 +1,103 @@
# ADR 0021 — Scheda dell'industria e schermata di connessione (F6)
Stato: accettato (F6, issue #42).
## Contesto
Le immagini di riferimento 07 (industria) e 09 (connessione) sono vincolanti. Per entrambe il client
aveva soltanto una prima versione:
- un pannello laterale con l'elenco delle industrie e i comandi del proprietario (F5);
- un menu più un modulo «indirizzo e token» costruito quando l'immagine 09 non c'era ancora.
L'immagine 07 chiede dati che il client non riceveva:
- la catena produttiva con fornitori e clienti;
- le coperture di materie prime, lavoratori e personale sulla finestra di 30 giorni;
- produzione e magazzino in giorni;
- il fattore che limita l'efficienza;
- il punteggio di crescita trimestrale con le soglie;
- la stazione e la linea che servono l'industria;
- lo stato dello sblocco «acquisto di industrie».
L'immagine 09 chiede lo stato del server: versione, sistema, tempo di attività, tick, latenza e client
collegati. Chiede anche le partite salvate sul server.
Il client non contiene logica di gioco e il formato dei salvataggi non deve cambiare.
## Decisione
### Scheda dell'industria: calcolo nel Core, su richiesta
1. `Core/Economy/IndustryOutlook.Build(world, industry, company)` è una funzione pura: legge il mondo e
non lo cambia, e il test verifica che l'hash di stato resti uguale. Calcola, con le stesse formule
del motore:
- i fattori dell'efficienza (`Factors`: redditività, impianti, giacimento, evento, fermo) e il
fattore che la limita (`IndustryLimit`), cioè il più basso sotto 1 nell'ordine dell'enumerazione;
un'industria chiusa o al livello 0 è «inattiva», una ferma è «ferma»;
- per ogni ingresso e uscita: quantità al mese a piena capacità e all'efficienza di oggi, scorta,
capienza, giorni di scorta (ingressi) o giorni al magazzino pieno (uscite), più i partner:
- fornitori: industrie che producono il bene, al prezzo globale, e hub che lo importano, al
prezzo di vendita dell'hub;
- clienti: industrie che consumano il bene, al prezzo locale (`Market.LocalPrice`), hub
d'esportazione al prezzo d'acquisto dell'hub, e città con domanda del bene, al prezzo globale;
- la linea che collega: la linea della compagnia, con treni, il cui bacino tocca sia l'industria
sia il partner;
- l'ordine: prima i collegati, poi per distanza;
- la forza lavoro: posti, presenti, al lavoro, copertura, mancanti, motivo e provenienze, dai
contratti dei pendolari (`World.Commutes`) raggruppati per città, linea e vettore;
- la crescita: il punteggio del trimestre in corso e le sue componenti. `IndustryMath.GrowthScore`
è ora l'unica formula: la usa anche `IndustrySystem.Quarter`, con aritmetica identica (test di
determinismo invariati). Calcola anche le soglie, i trimestri sopra soglia e se un vettore serve
l'industria (solo allora il livello cambia);
- prezzo medio realizzato ≈ `RevenueEma × QuarterDays / QuarterShipped`, utile annuo dalle medie
mobili, stazioni che servono l'industria e avanzamento verso il livello che sblocca l'acquisto
(`ClimbOutlook`).
2. I nuovi parametri di presentazione stanno in `balance.json → industry.outlook`:
- `partnersPerGood` (3): partner per bene;
- `workforceSources` (4): provenienze dei pendolari.
Il validatore li vuole entrambi ≥ 1.
3. Il server manda la scheda nel blocco 1 di `IndustryCard` (`IndustrySheetInfo`, PROTOCOL.md §5). La
manda per ogni industria richiesta, per la compagnia della sessione: la scheda si apre su qualunque
industria, non solo sulle proprie. Un client vecchio ignora il blocco; un server vecchio non lo
manda, e il client mostra «Scheda in arrivo».
4. Il client mostra la scheda a tutto schermo, come «Mercato» e «La tua scalata». Il pannello laterale
delle industrie non c'è più: un selettore in alto sceglie l'industria. I comandi del proprietario
restano quelli della F5:
- budget, ricambi extra, «Fermo programmato», «Ammoderna»;
- per le industrie dei privati, «Fai un'offerta di acquisto» al prezzo di stima, attivo solo con lo
sblocco.
«Crea una linea verso questa industria» apre lo strumento binari centrato sull'industria.
### Schermata di connessione: stato nel `Welcome`, salvataggi con `ListSaves`
5. Il `Welcome` ha un blocco 1 `ServerInfo`: versione, sistema, Docker sì/no, tempo di attività, passo
del ciclo, sessioni collegate e massime, locale sì/no. La latenza la misura il client con il ping.
6. La schermata iniziale e quella di connessione diventano una sola (immagine 09); `MenuScreen` è
rimossa. A sinistra c'è una mappa decorativa disegnata in codice con la palette della mappa; a
destra le due strade:
- «Gioca in locale» avvia il server figlio;
- «Connetti a un server» usa indirizzo e token, con «Ricorda questo server».
Entrambe aprono una sessione di prova che mostra lo stato e l'elenco «Partite salvate sul server»
(`ListSaves` ogni 5 s).
«Connetti e riprendi» entra nella partita in corso, oppure manda `Load` del salvataggio scelto e
aspetta il nuovo `Welcome`. «Nuova partita sul server» manda `NewGame` con la difficoltà della
partita. In entrambi i casi la sessione di prova diventa la partita.
7. Il collaudo (`--autopilot`) aggiunge in coda due schermate senza rinumerare le altre:
- `19_scheda_industria`: un'industria di trasformazione vicino alla linea;
- `20_connessione`: la schermata sopra la partita, con una sessione di prova sul server locale
dopo un salvataggio.
## Conseguenze
- Nessuno stato nuovo nel mondo e nessun cambio del formato dei salvataggi. La scheda è calcolata
quando la si chiede, a costo proporzionale al numero di industrie, città e linee.
- Il motore non registra i flussi reali per collegamento. La catena mostra perciò, per ogni partner:
la sua produzione o il suo fabbisogno mensile, il prezzo e la linea che lo collega. Non mostra le
tonnellate effettivamente consegnate su quel collegamento, come invece fa l'immagine 07.
- Il consumo di materie prime segue la ricetta: tutti gli ingressi hanno la stessa frazione «attuale /
piena». La differenza tra ingressi la danno i giorni di scorta e l'ingresso che limita.
- La «linea che collega» è solo una linea ferroviaria della compagnia con treni. Il trasporto locale
su strada e le linee delle altre compagnie non compaiono nella catena; restano nei numeri.
- Lo stato del server è quello del momento del `Welcome`: «client collegati» non si aggiorna finché la
sessione resta aperta.
@@ -243,6 +243,17 @@ public sealed class IndustryBalance
public required Dictionary<string, int> FootprintCells { get; init; }
public required double DepletionStartFraction { get; init; }
public required long StartingCash { get; init; }
/// <summary>Scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
public required IndustryOutlookBalance Outlook { get; init; }
}
/// <summary>Parametri della scheda dell'industria (IndustryOutlook, ADR 0021).</summary>
public sealed class IndustryOutlookBalance
{
/// <summary>Fornitori o clienti elencati per ogni bene della catena produttiva (prima i collegati, poi i più vicini).</summary>
public required int PartnersPerGood { get; init; }
/// <summary>Provenienze dei lavoratori (e del personale) elencate nella scheda, dalle più numerose.</summary>
public required int WorkforceSources { get; init; }
}
public sealed class GrowthBalance
@@ -186,6 +186,8 @@ public static class DataValidator
if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1])
Err("balance.json", "map.industries.initialLevels deve essere [min, max]");
RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors);
if (b.Industry.Outlook.PartnersPerGood < 1) Err("balance.json", "industry.outlook.partnersPerGood deve essere almeno 1");
if (b.Industry.Outlook.WorkforceSources < 1) Err("balance.json", "industry.outlook.workforceSources deve essere almeno 1");
RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors);
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
@@ -0,0 +1,515 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Core.Economy;
/// <summary>
/// Fattore che limita l'efficienza dell'industria (e = min(copertura input, lavoratori, personale) ×
/// pf × mc × giacimento × eventi, guida 6.3): il più basso sotto 1, nell'ordine dell'enum a parità.
/// </summary>
public enum IndustryLimit : byte
{
/// <summary>Nessun fattore sotto 1: l'industria lavora a piena capacità.</summary>
None = 0,
Inputs = 1,
Workers = 2,
Staff = 3,
/// <summary>Fattore di profitto (margine negativo).</summary>
Profit = 4,
/// <summary>Condizione degli impianti sotto la soglia del rendimento pieno.</summary>
Condition = 5,
/// <summary>Giacimento sotto la soglia di esaurimento.</summary>
Depletion = 6,
/// <summary>Evento del mondo sulla capacità (incidente).</summary>
Event = 7,
/// <summary>Fermo in corso (guasto, incidente, revisione, ammodernamento).</summary>
Stopped = 8,
/// <summary>Livello 0 (dormiente) o industria chiusa.</summary>
Dormant = 9,
}
/// <summary>Tipo di nodo della catena produttiva.</summary>
public enum ChainPartnerKind : byte { Industry = 0, Hub = 1, Town = 2 }
/// <summary>
/// Fornitore o cliente di un bene nella catena produttiva: unità al mese (produzione attuale del
/// fornitore, fabbisogno a piena capacità del cliente, capacità mensile dell'hub, domanda della
/// città), prezzo (centesimi per unità: prezzo globale per chi vende al mercato, prezzo locale
/// dell'ADR 0004 per l'industria che compra, prezzo dell'hub con il dazio), linea della compagnia che
/// collega i due (None se nessuna) e distanza in linea d'aria.
/// </summary>
public readonly record struct ChainPartner(ChainPartnerKind Kind, int Target, double MonthlyUnits, double Price, LineId Line, double DistanceKm);
/// <summary>
/// Un input o un output dell'industria al livello attuale: quantità al mese a piena efficienza e al
/// ritmo attuale, scorta e capienza del magazzino, giorni di scorta (input, al ritmo dei presenti) o
/// giorni prima che il magazzino si riempia (output, al ritmo attuale; oltre si perde la merce);
/// −1 se il ritmo è nullo. Partner: fornitori (input) o clienti (output).
/// </summary>
public sealed class IndustryFlow
{
public required int Good { get; init; }
public required double FullMonth { get; init; }
public required double CurrentMonth { get; init; }
public required int Stock { get; init; }
public required int Storage { get; init; }
public required double Days { get; init; }
/// <summary>Input che limita l'efficienza (quello con meno giorni di scorta quando il limite sono gli input).</summary>
public required bool Limiting { get; init; }
public required List<ChainPartner> Partners { get; init; }
}
/// <summary>Provenienza dei lavoratori (o del personale): città, linea del primo tratto, vettore, minuti di viaggio.</summary>
public readonly record struct WorkforceSource(TownId Town, int Headcount, double Coverage, LineId Line, CompanyId Carrier, double Minutes, bool Walking);
/// <summary>Lavoratori o personale qualificato dell'industria.</summary>
public sealed class WorkforceOutlook
{
public required int Jobs { get; init; }
public required double Present { get; init; }
/// <summary>Quota coperta da chi vive in sede (alloggi dell'industria).</summary>
public required double OnSite { get; init; }
/// <summary>Copertura media su coverageWindowDays (entra nell'efficienza).</summary>
public required double Coverage { get; init; }
/// <summary>Posti scoperti oggi (posti − presenti, arrotondato).</summary>
public required int Missing { get; init; }
public required UncoveredReason Reason { get; init; }
public required LineId ReasonLine { get; init; }
/// <summary>Viaggio medio in treno (minuti, pesato sulle persone); −1 senza pendolari in treno.</summary>
public required double AverageMinutes { get; init; }
/// <summary>Provenienze più numerose (al massimo industry.outlook.workforceSources).</summary>
public required List<WorkforceSource> Sources { get; init; }
/// <summary>Provenienze in tutto (anche quelle non elencate).</summary>
public required int SourceCount { get; init; }
}
/// <summary>Crescita trimestrale (guida 6.3): punteggio del trimestre in corso, soglie e trimestri.</summary>
public sealed class GrowthOutlook
{
public required double LastScore { get; init; }
public required GrowthScoreParts Current { get; init; }
public required double UpgradeThreshold { get; init; }
public required double DowngradeThreshold { get; init; }
public required int UpgradeQuarters { get; init; }
public required int QuartersAbove { get; init; }
/// <summary>Giorni del trimestre già contati e lunghezza del trimestre.</summary>
public required int QuarterDay { get; init; }
public required int QuarterDays { get; init; }
/// <summary>Servita da un vettore nel trimestre: solo allora il livello cambia (ADR 0004).</summary>
public required bool Served { get; init; }
public required int MaxLevel { get; init; }
}
/// <summary>Scheda dell'industria per la compagnia della sessione (immagine di riferimento 07, ADR 0021).</summary>
public sealed class IndustryOutlookReport
{
public required IndustryId Industry { get; init; }
public required int Level { get; init; }
public required int MaxLevel { get; init; }
public required double Efficiency { get; init; }
public required IndustryLimit Limit { get; init; }
public required double CovInput { get; init; }
public required double CovWorkers { get; init; }
public required double CovStaff { get; init; }
public required int CoverageWindowDays { get; init; }
public required double ProfitFactor { get; init; }
public required double ConditionMultiplier { get; init; }
public required double Depletion { get; init; }
public required double EventCapacity { get; init; }
/// <summary>Riserva residua del giacimento (0–1); −1 se l'industria non è esauribile.</summary>
public required double ReserveFraction { get; init; }
public required int StorageDays { get; init; }
public required List<IndustryFlow> Inputs { get; init; }
public required List<IndustryFlow> Outputs { get; init; }
public required WorkforceOutlook Workers { get; init; }
public required WorkforceOutlook Staff { get; init; }
/// <summary>Ricavo medio per unità del prodotto (centesimi); −1 se non stimabile (nessuna vendita o più prodotti).</summary>
public required double AveragePrice { get; init; }
public required Money AnnualProfit { get; init; }
public required GrowthOutlook Growth { get; init; }
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria con una linea con treni.</summary>
public required List<StationId> ServingStations { get; init; }
/// <summary>Linea della compagnia della sessione che serve l'industria (id più basso), None se nessuna.</summary>
public required LineId ServingLine { get; init; }
/// <summary>Dei privati e attiva: si può comprare (dal livello che sblocca l'acquisto).</summary>
public required bool ForSale { get; init; }
public required bool BuyUnlocked { get; init; }
public required int BuyTier { get; init; }
/// <summary>Avanzamento verso il livello che sblocca l'acquisto (ADR 0018); 1 se sbloccato.</summary>
public required double BuyProgress { get; init; }
}
/// <summary>
/// Scheda dell'industria (ADR 0021): legge il mondo e non scrive nulla, come MarketOutlook e
/// ClimbOutlook. Catena produttiva con fornitori e clienti per bene, coperture, forza lavoro con le
/// provenienze, produzione e magazzino, fattore limitante, crescita trimestrale e acquisto.
/// </summary>
public static class IndustryOutlook
{
public static IndustryOutlookReport Build(World w, Industry ind, CompanyId company)
{
var data = w.Data;
var ib = data.Balance.Industry;
var g = data.Balance.Growth;
int dpm = w.Calendar.DaysPerMonth;
long today = w.Clock.Day;
var recipe = ind.Def.Recipe;
var factors = Factors(w, ind);
var links = new LineLinks(w, company);
var mine = links.Serving(ind);
// ritmo dei presenti senza la copertura degli input (giorni di scorta) e ritmo effettivo
double cyclesFull = ind.Closed ? 0 : ind.CyclesPerDayAtFullCapacity(dpm);
double labour = factors.Stopped || ind.Closed
? 0
: Math.Min(ind.CovWorkers, ind.CovStaff) * factors.ProfitFactor * factors.ConditionMultiplier * factors.Depletion * factors.EventCapacity;
double efficiency = ind.Closed ? 0 : ind.Efficiency;
int limiting = -1;
if (factors.Limit == IndustryLimit.Inputs)
{
double least = double.MaxValue;
for (int i = 0; i < recipe.Inputs.Count; i++)
{
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
double days = perDay > 0 ? ind.InputStock[i] / perDay : double.MaxValue;
if (limiting < 0 || days < least)
{
least = days;
limiting = i;
}
}
}
var inputs = new List<IndustryFlow>(recipe.Inputs.Count);
for (int i = 0; i < recipe.Inputs.Count; i++)
{
int good = recipe.Inputs[i].GoodIndex;
double full = cyclesFull * recipe.Inputs[i].PerCycle * dpm;
double perDay = cyclesFull * recipe.Inputs[i].PerCycle * labour;
inputs.Add(new IndustryFlow
{
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.InputStock[i],
Storage = IndustryMath.InputCapacity(ind, i, dpm), Days = perDay > 0 ? ind.InputStock[i] / perDay : -1,
Limiting = i == limiting, Partners = Suppliers(w, ind, good, links, mine),
});
}
var outputs = new List<IndustryFlow>(recipe.Outputs.Count);
for (int o = 0; o < recipe.Outputs.Count; o++)
{
int good = recipe.Outputs[o].GoodIndex;
double full = cyclesFull * recipe.Outputs[o].PerCycle * dpm;
double perDay = full * efficiency / dpm;
int storage = IndustryMath.OutputCapacity(ind, o, dpm);
outputs.Add(new IndustryFlow
{
Good = good, FullMonth = full, CurrentMonth = full * efficiency, Stock = ind.OutputStock[o], Storage = storage,
Days = perDay > 0 ? Math.Max(0, storage - ind.OutputStock[o]) / perDay : -1,
Limiting = false, Partners = Customers(w, ind, good, links, mine),
});
}
// ricavo medio per unità: ricavi medi giornalieri / unità spedite al giorno nel trimestre (un solo prodotto)
double averagePrice = -1;
if (recipe.Outputs.Count == 1 && ind.QuarterShipped > 0 && ind.QuarterDays > 0)
averagePrice = ind.RevenueEma * ind.QuarterDays / ind.QuarterShipped;
var buyTier = data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.BuyIndustry);
var owner = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
bool buyUnlocked = owner is not null && Tiers.Unlocks(w, owner).BuyIndustry;
double buyProgress = buyUnlocked ? 1 : owner is not null && buyTier is not null ? ClimbOutlook.Requirements(w, owner, buyTier).Progress : 0;
return new IndustryOutlookReport
{
Industry = ind.Id,
Level = ind.Level,
MaxLevel = g.MaxLevel,
Efficiency = efficiency,
Limit = factors.Limit,
CovInput = ind.CovInput,
CovWorkers = ind.CovWorkers,
CovStaff = ind.CovStaff,
CoverageWindowDays = ib.CoverageWindowDays,
ProfitFactor = factors.ProfitFactor,
ConditionMultiplier = factors.ConditionMultiplier,
Depletion = factors.Depletion,
EventCapacity = factors.EventCapacity,
ReserveFraction = factors.ReserveFraction,
StorageDays = ind.Def.StorageDays,
Inputs = inputs,
Outputs = outputs,
Workers = Workforce(w, ind, PaxClass.Worker),
Staff = Workforce(w, ind, PaxClass.Staff),
AveragePrice = averagePrice,
AnnualProfit = Money.FromCentsRounded(IndustryMath.AnnualProfit(w, ind)),
Growth = new GrowthOutlook
{
LastScore = ind.LastScore,
Current = IndustryMath.GrowthScore(ind, g),
UpgradeThreshold = g.UpgradeThreshold,
DowngradeThreshold = g.DowngradeThreshold,
UpgradeQuarters = g.UpgradeQuarters,
QuartersAbove = ind.QuartersAboveUpgrade,
QuarterDay = ind.QuarterDays,
QuarterDays = g.QuarterDays,
Served = ind.ServedWithin(today, g.QuarterDays),
MaxLevel = g.MaxLevel,
},
ServingStations = ServingStations(w, ind),
ServingLine = mine.Count > 0 ? mine[0].Id : LineId.None,
ForSale = !ind.Owner.IsValid && !ind.Closed && ind.Level > 0,
BuyUnlocked = buyUnlocked,
BuyTier = buyTier?.Level ?? 0,
BuyProgress = buyProgress,
};
}
/// <summary>Fattori dell'efficienza dell'industria e quello che la limita.</summary>
public readonly record struct EfficiencyFactors(
double ProfitFactor, double ConditionMultiplier, double Depletion, double EventCapacity, double ReserveFraction, bool Stopped, IndustryLimit Limit);
/// <summary>
/// Fattori dell'efficienza come li usa la produzione (IndustrySystem): coperture medie, fattore di
/// profitto, condizione degli impianti, giacimento, eventi; il limite è il fattore più basso sotto 1
/// (a parità nell'ordine di <see cref="IndustryLimit"/>), Fermo se l'industria è ferma, Dormiente al
/// livello 0 o chiusa.
/// </summary>
public static EfficiencyFactors Factors(World w, Industry ind)
{
var data = w.Data;
double pf = IndustryMath.ProfitFactor(ind, data.Balance.Industry);
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
double depletion = 1;
double reserve = -1;
if (ind.Def.Depletable && ind.Site.IsValid)
{
reserve = w.Sites[ind.Site.Value].ReserveFraction;
double start = data.Balance.Industry.DepletionStartFraction;
if (reserve < start) depletion = Math.Max(0, reserve) / start;
}
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
bool stopped = ind.IsStopped(w.Clock.Day);
IndustryLimit limit;
if (ind.Closed || ind.Level <= 0) limit = IndustryLimit.Dormant;
else if (stopped) limit = IndustryLimit.Stopped;
else
{
limit = IndustryLimit.None;
double least = 1;
void Consider(IndustryLimit kind, double value)
{
if (value < least)
{
least = value;
limit = kind;
}
}
if (ind.Def.Recipe.Inputs.Count > 0) Consider(IndustryLimit.Inputs, ind.CovInput);
if (ind.JobsWorkers > 0) Consider(IndustryLimit.Workers, ind.CovWorkers);
if (ind.JobsStaff > 0) Consider(IndustryLimit.Staff, ind.CovStaff);
Consider(IndustryLimit.Profit, pf);
Consider(IndustryLimit.Condition, mc);
Consider(IndustryLimit.Depletion, depletion);
Consider(IndustryLimit.Event, capacity);
}
return new EfficiencyFactors(pf, mc, depletion, capacity, reserve, stopped, limit);
}
/// <summary>Lavoratori o personale: presenti, quota in sede, posti scoperti con il motivo e provenienze per città e linea.</summary>
public static WorkforceOutlook Workforce(World w, Industry ind, PaxClass cls)
{
var ib = w.Data.Balance.Industry;
bool staff = cls == PaxClass.Staff;
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
var me = WorkplaceRef.Of(ind.Id);
// contratti raggruppati per città, primo tratto, vettore e modo (a piedi o in treno), nell'ordine dei contratti
var groups = new List<(TownId Town, LineId Line, CompanyId Carrier, bool Walking, int Headcount, double CoverageSum, double MinutesSum)>();
double railPeople = 0, railMinutes = 0;
foreach (var c in w.Commutes)
{
if (c.Workplace != me || c.Category != cls || c.Headcount <= 0) continue;
var line = c.Route.Count > 0 ? c.Route[0] : LineId.None;
int at = groups.FindIndex(x => x.Town == c.Town && x.Line == line && x.Carrier == c.Carrier && x.Walking == c.Walking);
if (at < 0)
{
groups.Add((c.Town, line, c.Carrier, c.Walking, 0, 0, 0));
at = groups.Count - 1;
}
var gr = groups[at];
groups[at] = gr with
{
Headcount = gr.Headcount + c.Headcount,
CoverageSum = gr.CoverageSum + c.Coverage * c.Headcount,
MinutesSum = gr.MinutesSum + c.ExpectedMinutes * c.Headcount,
};
if (!c.Walking)
{
railPeople += c.Headcount;
railMinutes += c.ExpectedMinutes * c.Headcount;
}
}
var sources = groups
.Select(x => new WorkforceSource(x.Town, x.Headcount, x.CoverageSum / x.Headcount, x.Line, x.Carrier, x.MinutesSum / x.Headcount, x.Walking))
.OrderByDescending(s => s.Headcount).ThenBy(s => s.Town.Value).ThenBy(s => s.Line.Value).ThenBy(s => s.Carrier.Value).ThenBy(s => s.Walking)
.Take(ib.Outlook.WorkforceSources).ToList();
return new WorkforceOutlook
{
Jobs = jobs,
Present = present,
OnSite = EmploymentSystem.OnSite(jobs, staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare),
Coverage = staff ? ind.CovStaff : ind.CovWorkers,
Missing = (int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)),
Reason = staff ? ind.StaffReason : ind.WorkersReason,
ReasonLine = staff ? ind.StaffReasonLine : ind.WorkersReasonLine,
AverageMinutes = railPeople > 0 ? railMinutes / railPeople : -1,
Sources = sources,
SourceCount = groups.Count,
};
}
/// <summary>
/// Fornitori di un input: industrie attive che producono il bene (unità al mese al ritmo attuale,
/// prezzo globale: le industrie vendono al mercato, ADR 0004) e hub (capacità mensile, prezzo
/// d'importazione). Prima i collegati da una linea della compagnia, poi i più vicini.
/// </summary>
private static List<ChainPartner> Suppliers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var all = new List<ChainPartner>();
foreach (var other in w.Industries)
{
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
int o = other.OutputIndexOf(good);
if (o < 0) continue;
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Outputs[o].PerCycle * dpm * other.Efficiency;
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, pg, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
}
foreach (var h in w.Hubs)
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.SellPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
return Pick(w, all);
}
/// <summary>
/// Clienti di un output: industrie attive che lo consumano (fabbisogno al mese a piena capacità,
/// prezzo locale dell'ADR 0004 come «Dove conviene vendere»), hub (prezzo d'esportazione) e città con
/// domanda del bene (domanda al mese, prezzo globale). Prima i collegati, poi i più vicini.
/// </summary>
private static List<ChainPartner> Customers(World w, Industry ind, int good, LineLinks links, List<Line> mine)
{
int dpm = w.Calendar.DaysPerMonth;
double pg = w.Market.GlobalPrice[good];
var lp = w.Data.Balance.LocalPrice;
var all = new List<ChainPartner>();
foreach (var other in w.Industries)
{
if (other.Id == ind.Id || other.Closed || other.Level <= 0) continue;
int i = other.InputIndexOf(good);
if (i < 0) continue;
double month = other.CyclesPerDayAtFullCapacity(dpm) * other.Def.Recipe.Inputs[i].PerCycle * dpm;
double price = Market.LocalPrice(pg, IndustryMath.InputCapacity(other, i, dpm), other.InputStock[i], lp);
all.Add(new ChainPartner(ChainPartnerKind.Industry, other.Id.Value, month, price, links.Link(mine, ChainPartnerKind.Industry, other.Id.Value), Km(ind.Position, other.Position)));
}
foreach (var h in w.Hubs)
all.Add(new ChainPartner(ChainPartnerKind.Hub, h.Id.Value, h.MonthlyCapacity, h.BuyPrice(pg), links.Link(mine, ChainPartnerKind.Hub, h.Id.Value), Km(ind.Position, h.Position)));
foreach (var t in w.Towns)
{
if (t.DemandToday.Length <= good || t.DemandToday[good] <= 0) continue;
all.Add(new ChainPartner(ChainPartnerKind.Town, t.Id.Value, t.DemandToday[good] * dpm, pg, links.Link(mine, ChainPartnerKind.Town, t.Id.Value), Km(ind.Position, t.Position)));
}
return Pick(w, all);
}
/// <summary>Prima i collegati (per linea), poi i più vicini; a parità tipo e id; al massimo partnersPerGood.</summary>
private static List<ChainPartner> Pick(World w, List<ChainPartner> all) =>
all.OrderBy(p => p.Line.IsValid ? 0 : 1).ThenBy(p => p.DistanceKm).ThenBy(p => p.Kind).ThenBy(p => p.Target)
.Take(w.Data.Balance.Industry.Outlook.PartnersPerGood).ToList();
private static double Km(Vec2 a, Vec2 b) => Vec2.Distance(a, b) / 1000;
/// <summary>Stazioni vive (di qualunque compagnia) con l'industria nel bacino e fermata di una linea con treni.</summary>
public static List<StationId> ServingStations(World w, Industry ind)
{
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (!t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
}
var served = new bool[w.Network.Stations.Count];
foreach (var l in w.Lines)
{
if (l.Removed || !lineHasTrain[l.Id.Value]) continue;
foreach (var stop in l.Stops)
{
int s = stop.Station.Value;
if (s >= 0 && s < served.Length) served[s] = true;
}
}
var result = new List<StationId>();
foreach (var s in w.Network.Stations)
{
if (served[s.Id.Value] && w.Network.IsAlive(s) && s.Industries.Contains(ind.Id)) result.Add(s.Id);
}
return result;
}
/// <summary>
/// Linee della compagnia con almeno un treno e ciò che raggiungono: industrie, hub e città nel
/// bacino delle loro fermate (stazioni vive). Una linea collega due nodi se li raggiunge entrambi.
/// </summary>
private sealed class LineLinks
{
private readonly List<(Line Line, HashSet<int> Industries, HashSet<int> Hubs, HashSet<int> Towns)> _lines = [];
public LineLinks(World w, CompanyId company)
{
if (!company.IsValid) return;
var lineHasTrain = new bool[w.Lines.Count];
foreach (var t in w.Trains)
{
if (t.Owner == company && !t.Removed && t.Line.IsValid && t.Line.Value < lineHasTrain.Length) lineHasTrain[t.Line.Value] = true;
}
foreach (var l in w.Lines)
{
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
var industries = new HashSet<int>();
var hubs = new HashSet<int>();
var towns = new HashSet<int>();
foreach (var stop in l.Stops)
{
int s = stop.Station.Value;
if (s < 0 || s >= w.Network.Stations.Count) continue;
var station = w.Network.Stations[s];
if (!w.Network.IsAlive(station)) continue;
foreach (var i in station.Industries) industries.Add(i.Value);
foreach (var h in station.Hubs) hubs.Add(h.Value);
foreach (var t in station.Towns) towns.Add(t.Value);
}
_lines.Add((l, industries, hubs, towns));
}
}
/// <summary>Linee che raggiungono l'industria, per id crescente.</summary>
public List<Line> Serving(Industry ind) => _lines.Where(x => x.Industries.Contains(ind.Id.Value)).Select(x => x.Line).ToList();
/// <summary>Prima linea (id più basso) tra quelle dell'industria che raggiunge anche il nodo indicato.</summary>
public LineId Link(List<Line> serving, ChainPartnerKind kind, int target)
{
foreach (var line in serving)
{
var entry = _lines.First(x => ReferenceEquals(x.Line, line));
var set = kind switch
{
ChainPartnerKind.Industry => entry.Industries,
ChainPartnerKind.Hub => entry.Hubs,
_ => entry.Towns,
};
if (set.Contains(target)) return line.Id;
}
return LineId.None;
}
}
}
@@ -4,6 +4,9 @@ using RailEnterprise.Core.Economy;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>Componenti del punteggio di crescita trimestrale (quota trasportata, copertura, redditività) e punteggio.</summary>
public readonly record struct GrowthScoreParts(double Shipped, double Coverage, double Profit, double Score);
/// <summary>Formule dell'industria condivise da più sistemi (guida 6.3 e 11).</summary>
public static class IndustryMath
{
@@ -20,6 +23,20 @@ public static class IndustryMath
return m.EfficiencyAt20 + (1.0 - m.EfficiencyAt20) * t;
}
/// <summary>
/// Punteggio di crescita del trimestre (guida 6.3) dalle statistiche accumulate finora:
/// 0,5·quota trasportata + 0,3·copertura media + 0,2·redditività, con i pesi di balance.json.
/// Lo usa la crescita trimestrale e, a trimestre in corso, la scheda dell'industria.
/// </summary>
public static GrowthScoreParts GrowthScore(Industry ind, GrowthBalance g)
{
double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
return new GrowthScoreParts(shipped, coverage, profit, score);
}
/// <summary>Capienza del magazzino di un output (unità) al livello corrente.</summary>
public static int OutputCapacity(Industry ind, int outputIndex, int daysPerMonth)
{
@@ -138,10 +138,7 @@ public sealed class IndustrySystem : ISimSystem
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
double score = IndustryMath.GrowthScore(ind, g).Score;
ind.LastScore = score;
ind.QuarterProduced = 0;
ind.QuarterShipped = 0;
@@ -56,6 +56,12 @@ public sealed class ClientWorld(GameData data)
/// <summary>Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».</summary>
public FinanceReport? Finance { get; private set; }
/// <summary>Stato del server dall'ultimo Welcome (F6, ADR 0021): versione, sistema, attività, tick, sessioni.</summary>
public ServerInfo? Server { get; private set; }
/// <summary>Ultimo elenco dei salvataggi del server (risposta a ListSaves e a Save); resta valido anche dopo un nuovo Welcome.</summary>
public SaveList? Saves { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
@@ -148,6 +154,10 @@ public sealed class ClientWorld(GameData data)
Finance = m;
DetailVersion++;
return true;
case SaveList m:
Saves = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -172,6 +182,7 @@ public sealed class ClientWorld(GameData data)
Finance = null;
Alerts.Clear();
Summary = m.Summary;
Server = m.Server;
SessionId = m.SessionId;
Tick = m.Summary.Tick;
Speed = m.Summary.Speed;
@@ -161,6 +161,8 @@ public sealed class IndustryCard : IMessage
public Money Cash { get; init; }
public float BreakdownChancePerYear { get; init; }
public List<IndustryStopInfo> Stops { get; init; } = [];
/// <summary>Blocco 1 (F6, ADR 0021): scheda dell'immagine 07 per la compagnia della sessione; null se assente.</summary>
public IndustrySheetInfo? Sheet { get; init; }
public void Write(ref SpanWriter w)
{
@@ -169,7 +171,8 @@ public sealed class IndustryCard : IMessage
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);
w.Flags((byte)(Sheet is not null ? 1 : 0));
Sheet?.Write(ref w);
}
public static IndustryCard Read(ref SpanReader r)
@@ -181,9 +184,18 @@ public sealed class IndustryCard : IMessage
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();
byte flags = r.Flags();
if ((flags & 1) != 0) m = m.With(IndustrySheetInfo.Read(ref r));
return m;
}
private IndustryCard With(IndustrySheetInfo sheet) => new()
{
Industry = Industry, Margin = Margin, ConditionMultiplier = ConditionMultiplier, WearPerDay = WearPerDay, RecoveryPerDay = RecoveryPerDay,
MaintenanceCostPerDay = MaintenanceCostPerDay, MaintenanceSpentYear = MaintenanceSpentYear, PartsTarget = PartsTarget, PartsPerMonth = PartsPerMonth,
PartsOrdered = PartsOrdered, MachineryRequired = MachineryRequired, UpgradeCost = UpgradeCost, Valuation = Valuation, Cash = Cash,
BreakdownChancePerYear = BreakdownChancePerYear, Stops = Stops, Sheet = sheet,
};
}
/// <summary>Primato della Cronaca finale (descrizione e valore già formattati in italiano).</summary>
@@ -0,0 +1,269 @@
using RailEnterprise.Core.Common;
namespace RailEnterprise.Protocol.Messages;
// Blocchi della fase F6 (ADR 0021): scheda dell'industria dell'immagine di riferimento 07 (blocco 1 di
// IndustryCard, calcolato dal server con IndustryOutlook) e stato del server per la schermata di
// connessione dell'immagine 09 (blocco 1 di Welcome). Il client li mostra come arrivano.
/// <summary>
/// Fornitore o cliente nella catena produttiva. Kind: 0 industria, 1 hub, 2 città (ChainPartnerKind);
/// unità al mese, prezzo in centesimi per unità, linea della compagnia che collega (−1 nessuna), km in linea d'aria.
/// </summary>
public sealed class ChainPartnerInfo
{
public byte Kind { get; init; }
public int Target { get; init; }
public float MonthlyUnits { get; init; }
public double Price { get; init; }
public int Line { get; init; } = -1;
public float DistanceKm { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.I32(Target); w.F32(MonthlyUnits); w.F64(Price); w.I32(Line); w.F32(DistanceKm);
w.Flags(0);
}
public static ChainPartnerInfo Read(ref SpanReader r)
{
var m = new ChainPartnerInfo { Kind = r.U8(), Target = r.I32(), MonthlyUnits = r.F32(), Price = r.F64(), Line = r.I32(), DistanceKm = r.F32() };
r.Flags();
return m;
}
}
/// <summary>
/// Input o output dell'industria: al mese a piena efficienza (fabbisogno o capacità) e al ritmo attuale,
/// scorta, capienza, giorni (di scorta per un input, prima del magazzino pieno per un output; −1 senza
/// ritmo), input limitante, fornitori o clienti.
/// </summary>
public sealed class IndustryFlowInfo
{
public int Good { get; init; }
public float FullMonth { get; init; }
public float CurrentMonth { get; init; }
public int Stock { get; init; }
public int Storage { get; init; }
public float Days { get; init; } = -1;
public bool Limiting { get; init; }
public List<ChainPartnerInfo> Partners { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Good); w.F32(FullMonth); w.F32(CurrentMonth); w.I32(Stock); w.I32(Storage); w.F32(Days); w.Bool(Limiting);
w.Count(Partners.Count);
foreach (var p in Partners) p.Write(ref w);
w.Flags(0);
}
public static IndustryFlowInfo Read(ref SpanReader r)
{
var m = new IndustryFlowInfo { Good = r.I32(), FullMonth = r.F32(), CurrentMonth = r.F32(), Stock = r.I32(), Storage = r.I32(), Days = r.F32(), Limiting = r.Bool() };
for (int n = r.Count(), i = 0; i < n; i++) m.Partners.Add(ChainPartnerInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Provenienza dei lavoratori o del personale: città, persone, copertura, linea del primo tratto (−1 a piedi), vettore, minuti.</summary>
public sealed class WorkforceSourceInfo
{
public int Town { get; init; }
public int Headcount { get; init; }
public float Coverage { get; init; }
public int Line { get; init; } = -1;
public int Carrier { get; init; } = -1;
public float Minutes { get; init; }
public bool Walking { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Town); w.I32(Headcount); w.F32(Coverage); w.I32(Line); w.I32(Carrier); w.F32(Minutes); w.Bool(Walking);
w.Flags(0);
}
public static WorkforceSourceInfo Read(ref SpanReader r)
{
var m = new WorkforceSourceInfo { Town = r.I32(), Headcount = r.I32(), Coverage = r.F32(), Line = r.I32(), Carrier = r.I32(), Minutes = r.F32(), Walking = r.Bool() };
r.Flags();
return m;
}
}
/// <summary>
/// Lavoratori o personale: posti, presenti, quota in sede, copertura media, posti scoperti, motivo
/// (UncoveredReason) e linea del motivo, viaggio medio in treno (−1 senza), provenienze elencate e in tutto.
/// </summary>
public sealed class WorkforceInfo
{
public int Jobs { get; init; }
public float Present { get; init; }
public float OnSite { get; init; }
public float Coverage { get; init; }
public int Missing { get; init; }
public byte Reason { get; init; }
public int ReasonLine { get; init; } = -1;
public float AverageMinutes { get; init; } = -1;
public int SourceCount { get; init; }
public List<WorkforceSourceInfo> Sources { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Jobs); w.F32(Present); w.F32(OnSite); w.F32(Coverage); w.I32(Missing); w.U8(Reason); w.I32(ReasonLine); w.F32(AverageMinutes); w.I32(SourceCount);
w.Count(Sources.Count);
foreach (var s in Sources) s.Write(ref w);
w.Flags(0);
}
public static WorkforceInfo Read(ref SpanReader r)
{
var m = new WorkforceInfo
{
Jobs = r.I32(), Present = r.F32(), OnSite = r.F32(), Coverage = r.F32(), Missing = r.I32(), Reason = r.U8(), ReasonLine = r.I32(),
AverageMinutes = r.F32(), SourceCount = r.I32(),
};
for (int n = r.Count(), i = 0; i < n; i++) m.Sources.Add(WorkforceSourceInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>
/// Blocco 1 di IndustryCard (F6, ADR 0021): scheda dell'immagine 07 calcolata da IndustryOutlook per la
/// compagnia della sessione. Limit come IndustryLimit del Core (0 nessuno, 1 input, 2 lavoratori,
/// 3 personale, 4 profitto, 5 impianti, 6 giacimento, 7 evento, 8 fermo, 9 dormiente).
/// </summary>
public sealed class IndustrySheetInfo
{
public byte Level { get; init; }
public byte MaxLevel { get; init; }
public float Efficiency { get; init; }
public byte Limit { get; init; }
public float CovInput { get; init; }
public float CovWorkers { get; init; }
public float CovStaff { get; init; }
public int CoverageWindowDays { get; init; }
public float ProfitFactor { get; init; }
public float Depletion { get; init; }
public float EventCapacity { get; init; }
/// <summary>Riserva residua del giacimento (0–1), −1 se non esauribile.</summary>
public float ReserveFraction { get; init; } = -1;
public int StorageDays { get; init; }
public List<IndustryFlowInfo> Inputs { get; init; } = [];
public List<IndustryFlowInfo> Outputs { get; init; } = [];
public WorkforceInfo Workers { get; init; } = new();
public WorkforceInfo Staff { get; init; } = new();
/// <summary>Ricavo medio per unità del prodotto (centesimi), −1 se non stimabile.</summary>
public double AveragePrice { get; init; } = -1;
public Money AnnualProfit { get; init; }
/// <summary>Crescita trimestrale: ultimo punteggio, componenti e punteggio del trimestre in corso, soglie, trimestri.</summary>
public float LastScore { get; init; }
public float Shipped { get; init; }
public float Coverage { get; init; }
public float Profit { get; init; }
public float Score { get; init; }
public float UpgradeThreshold { get; init; }
public float DowngradeThreshold { get; init; }
public byte UpgradeQuarters { get; init; }
public byte QuartersAbove { get; init; }
public int QuarterDay { get; init; }
public int QuarterDays { get; init; }
public bool Served { get; init; }
/// <summary>Stazioni (di qualunque compagnia) che servono l'industria; linea della compagnia della sessione (−1 nessuna).</summary>
public List<int> ServingStations { get; init; } = [];
public int ServingLine { get; init; } = -1;
/// <summary>Acquisto: dei privati e attiva, sbloccato dal livello, livello che lo sblocca e avanzamento verso di esso.</summary>
public bool ForSale { get; init; }
public bool BuyUnlocked { get; init; }
public byte BuyTier { get; init; }
public float BuyProgress { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Level); w.U8(MaxLevel); w.F32(Efficiency); w.U8(Limit); w.F32(CovInput); w.F32(CovWorkers); w.F32(CovStaff); w.I32(CoverageWindowDays);
w.F32(ProfitFactor); w.F32(Depletion); w.F32(EventCapacity); w.F32(ReserveFraction); w.I32(StorageDays);
w.Count(Inputs.Count);
foreach (var f in Inputs) f.Write(ref w);
w.Count(Outputs.Count);
foreach (var f in Outputs) f.Write(ref w);
Workers.Write(ref w);
Staff.Write(ref w);
w.F64(AveragePrice); w.Money(AnnualProfit);
w.F32(LastScore); w.F32(Shipped); w.F32(Coverage); w.F32(Profit); w.F32(Score); w.F32(UpgradeThreshold); w.F32(DowngradeThreshold);
w.U8(UpgradeQuarters); w.U8(QuartersAbove); w.I32(QuarterDay); w.I32(QuarterDays); w.Bool(Served);
w.Count(ServingStations.Count);
foreach (int s in ServingStations) w.I32(s);
w.I32(ServingLine); w.Bool(ForSale); w.Bool(BuyUnlocked); w.U8(BuyTier); w.F32(BuyProgress);
w.Flags(0);
}
public static IndustrySheetInfo Read(ref SpanReader r)
{
byte level = r.U8(), maxLevel = r.U8();
float efficiency = r.F32();
byte limit = r.U8();
float covInput = r.F32(), covWorkers = r.F32(), covStaff = r.F32();
int window = r.I32();
float pf = r.F32(), depletion = r.F32(), eventCapacity = r.F32(), reserve = r.F32();
int storageDays = r.I32();
var inputs = new List<IndustryFlowInfo>();
for (int n = r.Count(), i = 0; i < n; i++) inputs.Add(IndustryFlowInfo.Read(ref r));
var outputs = new List<IndustryFlowInfo>();
for (int n = r.Count(), i = 0; i < n; i++) outputs.Add(IndustryFlowInfo.Read(ref r));
var workers = WorkforceInfo.Read(ref r);
var staff = WorkforceInfo.Read(ref r);
double averagePrice = r.F64();
var profit = r.Money();
float last = r.F32(), shipped = r.F32(), coverage = r.F32(), profitShare = r.F32(), score = r.F32(), up = r.F32(), down = r.F32();
byte upQuarters = r.U8(), above = r.U8();
int quarterDay = r.I32(), quarterDays = r.I32();
bool served = r.Bool();
var stations = new List<int>();
for (int n = r.Count(), i = 0; i < n; i++) stations.Add(r.I32());
var m = new IndustrySheetInfo
{
Level = level, MaxLevel = maxLevel, Efficiency = efficiency, Limit = limit, CovInput = covInput, CovWorkers = covWorkers, CovStaff = covStaff,
CoverageWindowDays = window, ProfitFactor = pf, Depletion = depletion, EventCapacity = eventCapacity, ReserveFraction = reserve, StorageDays = storageDays,
Inputs = inputs, Outputs = outputs, Workers = workers, Staff = staff, AveragePrice = averagePrice, AnnualProfit = profit,
LastScore = last, Shipped = shipped, Coverage = coverage, Profit = profitShare, Score = score, UpgradeThreshold = up, DowngradeThreshold = down,
UpgradeQuarters = upQuarters, QuartersAbove = above, QuarterDay = quarterDay, QuarterDays = quarterDays, Served = served, ServingStations = stations,
ServingLine = r.I32(), ForSale = r.Bool(), BuyUnlocked = r.Bool(), BuyTier = r.U8(), BuyProgress = r.F32(),
};
r.Flags();
return m;
}
}
/// <summary>
/// Blocco 1 di Welcome (F6, ADR 0021): stato del server per la schermata di connessione (immagine 09):
/// versione del gioco, sistema operativo, container, secondi di attività, durata del tick (ms), sessioni
/// collegate e massime, server locale (figlio del client).
/// </summary>
public sealed class ServerInfo
{
public string Version { get; init; } = "";
public string Os { get; init; } = "";
public bool Container { get; init; }
public long UptimeSeconds { get; init; }
public float TickMs { get; init; }
public int Sessions { get; init; }
public int MaxSessions { get; init; }
public bool Local { get; init; }
public void Write(ref SpanWriter w)
{
w.String(Version); w.String(Os); w.Bool(Container); w.I64(UptimeSeconds); w.F32(TickMs); w.I32(Sessions); w.I32(MaxSessions); w.Bool(Local);
w.Flags(0);
}
public static ServerInfo Read(ref SpanReader r)
{
var m = new ServerInfo
{
Version = r.String(), Os = r.String(), Container = r.Bool(), UptimeSeconds = r.I64(), TickMs = r.F32(), Sessions = r.I32(), MaxSessions = r.I32(), Local = r.Bool(),
};
r.Flags();
return m;
}
}
@@ -13,6 +13,8 @@ public sealed class Welcome : IMessage
public required WorldSummary Summary { get; init; }
public ulong DataHash { get; init; }
public string Difficulty { get; init; } = "";
/// <summary>Blocco 1 (F6, ADR 0021): stato del server per la schermata di connessione; null se assente.</summary>
public ServerInfo? Server { get; init; }
public void Write(ref SpanWriter w)
{
@@ -20,14 +22,19 @@ public sealed class Welcome : IMessage
Summary.Write(ref w);
w.U64(DataHash);
w.String(Difficulty);
w.Flags(0);
w.Flags((byte)(Server is not null ? 1 : 0));
Server?.Write(ref w);
}
public static Welcome Read(ref SpanReader r)
{
var m = new Welcome { SessionId = r.U64(), Summary = WorldSummary.Read(ref r), DataHash = r.U64(), Difficulty = r.String() };
r.Flags();
return m;
ulong session = r.U64();
var summary = WorldSummary.Read(ref r);
ulong hash = r.U64();
string difficulty = r.String();
byte flags = r.Flags();
var server = (flags & 1) != 0 ? ServerInfo.Read(ref r) : null;
return new Welcome { SessionId = session, Summary = summary, DataHash = hash, Difficulty = difficulty, Server = server };
}
}
+16 -1
View File
@@ -198,6 +198,21 @@ public sealed class GameHost : IDisposable
Summary = Projection.Summary(_world, _world.Companies[s.Company.Value], _speed),
DataHash = _data.Hash,
Difficulty = _world.Difficulty.Id,
Server = ServerStatus(),
};
/// <summary>Stato del server per la schermata di connessione (blocco 1 del Welcome, ADR 0021).</summary>
private ServerInfo ServerStatus() => new()
{
Version = GameVersion,
Os = System.Runtime.InteropServices.RuntimeInformation.OSDescription,
// le immagini .NET ufficiali impostano DOTNET_RUNNING_IN_CONTAINER
Container = string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase),
UptimeSeconds = NowMs / 1000,
TickMs = _config.TickMs,
Sessions = _sessions.Values.Count(x => x.Connected),
MaxSessions = _config.MaxSessions,
Local = _config.Local,
};
private void Handle(Session s, IMessage message)
@@ -653,7 +668,7 @@ public sealed class GameHost : IDisposable
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]));
s.Send(Projection.IndustryCard(w, w.Industries[m.Target], s.Company));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
+41 -2
View File
@@ -485,8 +485,8 @@ public static class Projection
};
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public static IndustryCard IndustryCard(World w, Industry ind)
/// <summary>Scheda del proprietario di un'industria (sezione 11) con la scheda dell'immagine 07 per la compagnia (blocco 1, ADR 0021).</summary>
public static IndustryCard IndustryCard(World w, Industry ind, CompanyId company)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
@@ -502,6 +502,45 @@ public static class Projection
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(),
Sheet = IndustrySheet(IndustryOutlook.Build(w, ind, company)),
};
}
/// <summary>Scheda dell'industria dell'immagine 07 (IndustryOutlook, ADR 0021).</summary>
public static IndustrySheetInfo IndustrySheet(IndustryOutlookReport r)
{
static IndustryFlowInfo Flow(IndustryFlow f) => new()
{
Good = f.Good, FullMonth = (float)f.FullMonth, CurrentMonth = (float)f.CurrentMonth, Stock = f.Stock, Storage = f.Storage, Days = (float)f.Days,
Limiting = f.Limiting,
Partners = f.Partners.Select(p => new ChainPartnerInfo
{
Kind = (byte)p.Kind, Target = p.Target, MonthlyUnits = (float)p.MonthlyUnits, Price = p.Price, Line = p.Line.Value, DistanceKm = (float)p.DistanceKm,
}).ToList(),
};
static WorkforceInfo Work(WorkforceOutlook o) => new()
{
Jobs = o.Jobs, Present = (float)o.Present, OnSite = (float)o.OnSite, Coverage = (float)o.Coverage, Missing = o.Missing, Reason = (byte)o.Reason,
ReasonLine = o.ReasonLine.Value, AverageMinutes = (float)o.AverageMinutes, SourceCount = o.SourceCount,
Sources = o.Sources.Select(x => new WorkforceSourceInfo
{
Town = x.Town.Value, Headcount = x.Headcount, Coverage = (float)x.Coverage, Line = x.Line.Value, Carrier = x.Carrier.Value, Minutes = (float)x.Minutes, Walking = x.Walking,
}).ToList(),
};
var g = r.Growth;
return new IndustrySheetInfo
{
Level = (byte)Math.Clamp(r.Level, 0, 255), MaxLevel = (byte)Math.Clamp(r.MaxLevel, 0, 255), Efficiency = (float)r.Efficiency, Limit = (byte)r.Limit,
CovInput = (float)r.CovInput, CovWorkers = (float)r.CovWorkers, CovStaff = (float)r.CovStaff, CoverageWindowDays = r.CoverageWindowDays,
ProfitFactor = (float)r.ProfitFactor, Depletion = (float)r.Depletion, EventCapacity = (float)r.EventCapacity, ReserveFraction = (float)r.ReserveFraction,
StorageDays = r.StorageDays, Inputs = r.Inputs.Select(Flow).ToList(), Outputs = r.Outputs.Select(Flow).ToList(),
Workers = Work(r.Workers), Staff = Work(r.Staff), AveragePrice = r.AveragePrice, AnnualProfit = r.AnnualProfit,
LastScore = (float)g.LastScore, Shipped = (float)g.Current.Shipped, Coverage = (float)g.Current.Coverage, Profit = (float)g.Current.Profit,
Score = (float)g.Current.Score, UpgradeThreshold = (float)g.UpgradeThreshold, DowngradeThreshold = (float)g.DowngradeThreshold,
UpgradeQuarters = (byte)Math.Clamp(g.UpgradeQuarters, 0, 255), QuartersAbove = (byte)Math.Clamp(g.QuartersAbove, 0, 255),
QuarterDay = g.QuarterDay, QuarterDays = g.QuarterDays, Served = g.Served,
ServingStations = r.ServingStations.Select(s => s.Value).ToList(), ServingLine = r.ServingLine.Value,
ForSale = r.ForSale, BuyUnlocked = r.BuyUnlocked, BuyTier = (byte)Math.Clamp(r.BuyTier, 0, 255), BuyProgress = (float)r.BuyProgress,
};
}
@@ -0,0 +1,279 @@
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using RailEnterprise.Server;
using RailEnterprise.Tests.Harness;
using RailEnterprise.Tests.Rail;
namespace RailEnterprise.Tests.Economy;
/// <summary>Scheda dell'industria dell'immagine 07 (F6, ADR 0021): catena produttiva, coperture, limite, crescita.</summary>
public static class IndustryOutlookTests
{
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
/// <summary>Valdoria con la rete merci miniere → acciaieria, un treno sulla linea e 40 giorni di servizio.</summary>
private static (RailFixture F, int Line, int MillStation) ServedValdoria()
{
var f = RailFixture.Valdoria();
var (mine, mill, depot) = f.BuildFreightNetwork();
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
f.W.RunDays(40);
return (f, line, mill);
}
[Test(Description = "Scheda dell'acciaieria di Valdoria: input, output, fornitore collegato dalla linea, clienti, stazione che serve; nessun effetto sul mondo")]
public static void SheetOfTheSteelMill()
{
var (f, line, millStation) = ServedValdoria();
var w = f.W;
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
ulong hash = StateHasher.Compute(w);
var r = IndustryOutlook.Build(w, steel, f.Me);
Assert.Equal(hash, StateHasher.Compute(w), "la scheda non cambia il mondo");
int dpm = w.Calendar.DaysPerMonth;
Assert.Equal(steel.Level, r.Level);
Assert.Equal(w.Data.Balance.Growth.MaxLevel, r.MaxLevel);
Assert.Equal(steel.Efficiency, r.Efficiency);
Assert.Equal(steel.Def.StorageDays, r.StorageDays);
Assert.Equal(w.Data.Balance.Industry.CoverageWindowDays, r.CoverageWindowDays);
// input nell'ordine della ricetta: fabbisogno a piena capacità e consumo al ritmo attuale
Assert.Equal(2, r.Inputs.Count);
int ore = GoodIndex(w, "iron_ore");
Assert.Equal(ore, r.Inputs[0].Good);
Assert.Equal(GoodIndex(w, "coal"), r.Inputs[1].Good);
double cyclesMonth = (double)steel.Def.Capacity(steel.Level) / steel.Def.Recipe.Outputs[0].PerCycle;
Assert.Approx(cyclesMonth * 2, r.Inputs[0].FullMonth, 1e-9);
Assert.Approx(cyclesMonth * 1, r.Inputs[1].FullMonth, 1e-9);
Assert.Approx(r.Inputs[0].FullMonth * steel.Efficiency, r.Inputs[0].CurrentMonth, 1e-9);
Assert.Equal(steel.InputStock[0], r.Inputs[0].Stock);
Assert.Equal(IndustryMath.InputCapacity(steel, 0, dpm), r.Inputs[0].Storage);
// output: capacità del livello, produzione al ritmo attuale, magazzino
Assert.Equal(1, r.Outputs.Count);
Assert.Approx(steel.Def.Capacity(steel.Level), r.Outputs[0].FullMonth, 1e-9);
Assert.Approx(r.Outputs[0].FullMonth * steel.Efficiency, r.Outputs[0].CurrentMonth, 1e-9);
Assert.Equal(IndustryMath.OutputCapacity(steel, 0, dpm), r.Outputs[0].Storage);
if (r.Outputs[0].CurrentMonth > 0)
{
double perDay = r.Outputs[0].CurrentMonth / dpm;
Assert.Approx(Math.Max(0, r.Outputs[0].Storage - r.Outputs[0].Stock) / perDay, r.Outputs[0].Days, 1e-9);
}
// il primo fornitore di minerale è la miniera di Rocca Bruna, collegata dalla linea
int perGood = w.Data.Balance.Industry.Outlook.PartnersPerGood;
var suppliers = r.Inputs[0].Partners;
Assert.True(suppliers.Count is > 0 && suppliers.Count <= perGood, $"fornitori {suppliers.Count}");
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
Assert.Equal(ChainPartnerKind.Industry, suppliers[0].Kind);
Assert.Equal(mine.Id.Value, suppliers[0].Target);
Assert.Equal(line, suppliers[0].Line.Value);
Assert.Equal(w.Market.GlobalPrice[ore], suppliers[0].Price);
double mineMonth = mine.CyclesPerDayAtFullCapacity(dpm) * dpm * mine.Efficiency;
Assert.Approx(mineMonth, suppliers[0].MonthlyUnits, 1e-9);
// dopo i collegati, i più vicini
for (int i = 1; i < suppliers.Count; i++)
{
if (suppliers[i - 1].Line.IsValid == suppliers[i].Line.IsValid)
Assert.True(suppliers[i - 1].DistanceKm <= suppliers[i].DistanceKm, "ordinati per distanza");
else Assert.True(suppliers[i - 1].Line.IsValid, "prima i collegati");
}
// clienti dell'acciaio: la fabbrica di attrezzi al prezzo locale dell'ADR 0004 e il porto, non collegati
var customers = r.Outputs[0].Partners;
Assert.True(customers.Count is > 0 && customers.Count <= perGood, $"clienti {customers.Count}");
Assert.True(customers.All(c => !c.Line.IsValid), "nessun cliente collegato");
var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
var toolsEntry = customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Industry && c.Target == tools.Id.Value);
Assert.True(toolsEntry.Kind == ChainPartnerKind.Industry && toolsEntry.Target == tools.Id.Value, "la fabbrica di attrezzi compra acciaio");
int steelGood = GoodIndex(w, "steel");
int slot = tools.InputIndexOf(steelGood);
double local = Market.LocalPrice(w.Market.GlobalPrice[steelGood], IndustryMath.InputCapacity(tools, slot, dpm), tools.InputStock[slot], w.Data.Balance.LocalPrice);
Assert.Equal(local, toolsEntry.Price);
if (customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Hub) is { Kind: ChainPartnerKind.Hub } port)
Assert.Equal(w.Hubs[port.Target].BuyPrice(w.Market.GlobalPrice[steelGood]), port.Price);
// servita dalla stazione dell'acciaieria con la linea della compagnia
Assert.True(r.ServingStations.Contains(new StationId(millStation)), "stazione dell'acciaieria");
Assert.Equal(line, r.ServingLine.Value);
// per un'altra compagnia nessuna linea collega
var other = IndustryOutlook.Build(w, steel, CompanyId.None);
Assert.False(other.ServingLine.IsValid);
Assert.True(other.Inputs[0].Partners.All(p => !p.Line.IsValid), "senza compagnia nessun collegamento");
// crescita: punteggio del trimestre dalla stessa funzione della crescita trimestrale
var g = w.Data.Balance.Growth;
Assert.Equal(IndustryMath.GrowthScore(steel, g), r.Growth.Current);
Assert.Equal(g.UpgradeThreshold, r.Growth.UpgradeThreshold);
Assert.Equal(g.DowngradeThreshold, r.Growth.DowngradeThreshold);
Assert.Equal(steel.QuarterDays, r.Growth.QuarterDay);
Assert.Equal(g.QuarterDays, r.Growth.QuarterDays);
Assert.True(r.Growth.Served, "servita da un vettore");
// acquisto: dei privati, livello e avanzamento dai dati (ADR 0018)
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry);
Assert.True(r.ForSale);
Assert.False(r.BuyUnlocked);
Assert.Equal(tier.Level, r.BuyTier);
Assert.Approx(ClimbOutlook.Requirements(w, w.Player, tier).Progress, r.BuyProgress, 1e-12);
Assert.Approx(IndustryMath.AnnualProfit(w, steel), r.AnnualProfit.Cents, 1);
}
[Test(Description = "Forza lavoro della scheda: presenti, quota in sede, posti scoperti e provenienze dai contratti di pendolarismo")]
public static void WorkforceComesFromTheCommuteContracts()
{
var (f, _, _) = ServedValdoria();
var w = f.W;
var ib = w.Data.Balance.Industry;
foreach (var ind in w.Industries.Where(i => !i.Closed))
{
foreach (var cls in new[] { PaxClass.Worker, PaxClass.Staff })
{
var o = IndustryOutlook.Workforce(w, ind, cls);
bool staff = cls == PaxClass.Staff;
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
Assert.Equal(jobs, o.Jobs);
Assert.Equal(present, o.Present);
Assert.Approx(jobs * (staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare), o.OnSite, 1e-9);
Assert.Equal((int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)), o.Missing);
var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0).ToList();
Assert.True(o.Sources.Count <= ib.Outlook.WorkforceSources && o.Sources.Count <= o.SourceCount, "provenienze entro il limite");
if (o.SourceCount <= ib.Outlook.WorkforceSources)
Assert.Equal(contracts.Sum(c => c.Headcount), o.Sources.Sum(s => s.Headcount));
for (int i = 1; i < o.Sources.Count; i++) Assert.True(o.Sources[i - 1].Headcount >= o.Sources[i].Headcount, "dalle più numerose");
var rail = contracts.Where(c => !c.Walking).ToList();
if (rail.Count == 0) Assert.Equal(-1.0, o.AverageMinutes);
else Assert.Approx(rail.Sum(c => c.ExpectedMinutes * c.Headcount) / rail.Sum(c => c.Headcount), o.AverageMinutes, 1e-9);
}
}
}
[Test(Description = "Il limite dell'efficienza è il fattore più basso sotto 1; fermo e livello 0 hanno la precedenza")]
public static void LimitIsTheLowestFactor()
{
var f = RailFixture.Valdoria();
var w = f.W;
w.RunDays(2);
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
var m = w.Data.Balance.IndustryMaintenance;
steel.CovInput = 1;
steel.CovWorkers = 1;
steel.CovStaff = 1;
steel.RevenueEma = 100;
steel.CostEma = 100;
steel.Condition = 100;
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, steel).Limit);
steel.CovStaff = 0.4;
steel.CovWorkers = 0.6;
Assert.Equal(IndustryLimit.Staff, IndustryOutlook.Factors(w, steel).Limit);
steel.CovInput = 0.3;
Assert.Equal(IndustryLimit.Inputs, IndustryOutlook.Factors(w, steel).Limit);
// impianti sotto il 20 %: mc al minimo, sotto le coperture
steel.CovInput = 0.9;
steel.Condition = 10;
var factors = IndustryOutlook.Factors(w, steel);
Assert.Equal(m.EfficiencyBelow20, factors.ConditionMultiplier);
Assert.Equal(m.EfficiencyBelow20 < 0.4 ? IndustryLimit.Condition : IndustryLimit.Staff, factors.Limit);
// margine negativo: fattore di profitto sotto 1
steel.Condition = 100;
steel.CovStaff = 1;
steel.CovWorkers = 1;
steel.CovInput = 1;
steel.RevenueEma = 0;
steel.CostEma = 100;
Assert.Equal(IndustryLimit.Profit, IndustryOutlook.Factors(w, steel).Limit);
Assert.Equal(IndustryMath.ProfitFactor(steel, w.Data.Balance.Industry), IndustryOutlook.Factors(w, steel).ProfitFactor);
// fermo e livello 0
steel.StoppedUntilDay = w.Clock.Day + 5;
Assert.Equal(IndustryLimit.Stopped, IndustryOutlook.Factors(w, steel).Limit);
steel.StoppedUntilDay = -1;
steel.Level = 0;
Assert.Equal(IndustryLimit.Dormant, IndustryOutlook.Factors(w, steel).Limit);
// senza input (miniera) l'input non è mai il limite; giacimento sotto la soglia
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
mine.CovInput = 0;
mine.CovWorkers = 1;
mine.CovStaff = 1;
mine.RevenueEma = 100;
mine.CostEma = 100;
mine.Condition = 100;
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, mine).Limit);
var site = w.Sites[mine.Site.Value];
site.ReserveTonnes = site.InitialReserveTonnes * w.Data.Balance.Industry.DepletionStartFraction / 2;
var depleted = IndustryOutlook.Factors(w, mine);
Assert.Equal(IndustryLimit.Depletion, depleted.Limit);
Assert.Approx(0.5, depleted.Depletion, 1e-9);
Assert.Approx(site.ReserveFraction, depleted.ReserveFraction, 1e-12);
}
[Test(Description = "Il punteggio di crescita trimestrale pesa quota trasportata, copertura e redditività come in balance.json")]
public static void GrowthScoreUsesTheWeights()
{
var f = RailFixture.Valdoria();
var w = f.W;
var g = w.Data.Balance.Growth;
var ind = w.Industries.First(i => i.Def.Id == "steel_mill");
ind.QuarterProduced = 200;
ind.QuarterShipped = 150;
ind.QuarterCoverageSum = 30;
ind.QuarterDays = 60;
ind.RevenueEma = 300;
ind.CostEma = 100;
var s = IndustryMath.GrowthScore(ind, g);
Assert.Approx(0.75, s.Shipped, 1e-12);
Assert.Approx(0.5, s.Coverage, 1e-12);
Assert.Approx((ind.Margin + 1) / 2, s.Profit, 1e-12);
Assert.Approx(g.WeightShipped * 0.75 + g.WeightCoverage * 0.5 + g.WeightProfit * s.Profit, s.Score, 1e-12);
// spedito oltre il prodotto (scorte vecchie): la quota resta 1
ind.QuarterShipped = 500;
Assert.Equal(1.0, IndustryMath.GrowthScore(ind, g).Shipped);
ind.QuarterProduced = 0;
ind.QuarterDays = 0;
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Shipped);
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Coverage);
}
[Test(Description = "La scheda viaggia nel blocco 1 di IndustryCard e torna identica; senza blocco il lettore la lascia vuota")]
public static void SheetRoundTripsInTheIndustryCard()
{
var (f, line, _) = ServedValdoria();
var w = f.W;
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
var card = Projection.IndustryCard(w, steel, f.Me);
Assert.True(card.Sheet is not null, "scheda nel blocco 1");
var decoded = (IndustryCard)Frame.Decode(Frame.Encode(card));
var sheet = decoded.Sheet!;
Assert.True(Frame.Encode(card).AsSpan().SequenceEqual(Frame.Encode(decoded)), "stessi byte");
Assert.Equal((byte)steel.Level, sheet.Level);
Assert.Equal(2, sheet.Inputs.Count);
Assert.Equal(line, sheet.ServingLine);
Assert.Equal(line, sheet.Inputs[0].Partners[0].Line);
Assert.Equal((float)steel.Efficiency, sheet.Efficiency);
Assert.Equal(card.Valuation, decoded.Valuation);
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
// un messaggio senza blocco (server F5) si legge con la scheda assente
var old = new IndustryCard { Industry = 3, Valuation = new Money(100) };
var back = (IndustryCard)Frame.Decode(Frame.Encode(old));
Assert.True(back.Sheet is null, "nessuna scheda");
Assert.Equal(new Money(100), back.Valuation);
}
}
@@ -35,6 +35,7 @@ public static class ProtocolTests
},
DataHash = 12345,
Difficulty = "imprenditore",
Server = new ServerInfo { Version = "0.6.1", Os = "Linux 6.8", Container = true, UptimeSeconds = 518_400, TickMs = 50, Sessions = 1, MaxSessions = 16, Local = false },
};
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
yield return new Pong { Nonce = 7, ServerTick = 123456 };
@@ -117,6 +118,36 @@ public static class ProtocolTests
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 }],
Sheet = new IndustrySheetInfo
{
Level = 3, MaxLevel = 5, Efficiency = 0.6f, Limit = 3, CovInput = 0.73f, CovWorkers = 0.8f, CovStaff = 0.6f, CoverageWindowDays = 30,
ProfitFactor = 1.05f, Depletion = 1, EventCapacity = 1, ReserveFraction = -1, StorageDays = 30,
Inputs =
[
new IndustryFlowInfo
{
Good = 2, FullMonth = 480, CurrentMonth = 350, Stock = 105, Storage = 480, Days = 9, Limiting = true,
Partners = [new ChainPartnerInfo { Kind = 0, Target = 1, MonthlyUnits = 500, Price = 4_200, Line = 5, DistanceKm = 9.4f }],
},
],
Outputs =
[
new IndustryFlowInfo
{
Good = 4, FullMonth = 500, CurrentMonth = 300, Stock = 40, Storage = 500, Days = 46, Limiting = false,
Partners = [new ChainPartnerInfo { Kind = 1, Target = 0, MonthlyUnits = 4000, Price = 15_600, Line = -1, DistanceKm = 4.2f }],
},
],
Workers = new WorkforceInfo
{
Jobs = 200, Present = 160, OnSite = 60, Coverage = 0.8f, Missing = 40, Reason = 5, ReasonLine = 1, AverageMinutes = 38, SourceCount = 2,
Sources = [new WorkforceSourceInfo { Town = 0, Headcount = 120, Coverage = 0.95f, Line = 1, Carrier = 0, Minutes = 35, Walking = false }],
},
Staff = new WorkforceInfo { Jobs = 20, Present = 12, Missing = 8, Reason = 4, ReasonLine = -1, AverageMinutes = -1 },
AveragePrice = 15_600, AnnualProfit = new Money(41_000_000), LastScore = 0.62f, Shipped = 0.8f, Coverage = 0.6f, Profit = 0.55f, Score = 0.69f,
UpgradeThreshold = 0.75f, DowngradeThreshold = 0.35f, UpgradeQuarters = 2, QuartersAbove = 1, QuarterDay = 45, QuarterDays = 90, Served = true,
ServingStations = [2, 7], ServingLine = 1, ForSale = true, BuyUnlocked = false, BuyTier = 3, BuyProgress = 0.58f,
},
};
yield return new Chronicle
{
@@ -404,6 +404,55 @@ public static class ServerTests
Assert.Equal(Money.FromLire(5_000), after.Loans);
}
[Test(Description = "F6 in rete: la scheda dell'industria arriva su richiesta con la catena produttiva; il Welcome porta lo stato del server e ListSaves l'elenco (ADR 0021)")]
public static void IndustrySheetAndServerStatusOnRequest() => RunIndustrySheet().GetAwaiter().GetResult();
private static async Task RunIndustrySheet()
{
var scenario = ScenarioHelper.Load("valdoria");
var steel = scenario.World.Industries.First(i => i.Def.Id == "steel_mill");
await using var server = ServerFixture.Start(scenario.World);
await using var client = await TestClient.ConnectAsync(server);
var w = client.World;
var data = TestData.Data;
// stato del server nel blocco 1 del Welcome
var info = client.Welcome.Server;
Assert.True(info is not null, "stato del server nel Welcome");
Assert.Equal(server.Host.GameVersion, info!.Version);
Assert.Equal(1f, info.TickMs);
Assert.True(info.Sessions >= 1 && info.Sessions <= info.MaxSessions, $"sessioni {info.Sessions} su {info.MaxSessions}");
Assert.True(info.Local, "server in processo avviato come locale");
Assert.True(info.Os.Length > 0 && info.UptimeSeconds >= 0, "sistema e tempo di attività");
Assert.True(w.Server is not null && w.Server.Version == info.Version, "la copia locale tiene lo stato del server");
// elenco dei salvataggi: risposta a ListSaves, poi a Save con il salvataggio nuovo
await client.Connection.SendAsync(new ListSaves());
var empty = await client.WaitFor(() => w.Saves, "elenco dei salvataggi");
var stale = w.Saves;
await client.Connection.SendAsync(new Save { Name = "Valdoria" });
var saves = await client.WaitFor(() => ReferenceEquals(w.Saves, stale) ? null : w.Saves, "elenco dopo il salvataggio");
Assert.Equal(empty.Saves.Count + 1, saves.Saves.Count);
Assert.True(saves.Saves.Any(x => !x.Autosave && (x.Name.Contains("Valdoria", StringComparison.Ordinal) || x.SaveId.Contains("Valdoria", StringComparison.OrdinalIgnoreCase))), "il salvataggio nuovo è nell'elenco");
// scheda dell'industria: si aspetta la risposta alla richiesta, non una scheda vecchia
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
var old = w.IndustryCards.GetValueOrDefault(steel.Id.Value);
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Industry, Target = steel.Id.Value });
var card = await client.WaitFor(() => w.IndustryCards.TryGetValue(steel.Id.Value, out var c) && !ReferenceEquals(c, old) ? c : null, "scheda dell'industria");
var sheet = card.Sheet;
Assert.True(sheet is not null, "scheda nel blocco 1");
Assert.Equal(steel.Def.Recipe.Inputs.Count, sheet!.Inputs.Count);
Assert.Equal(steel.Def.Recipe.Outputs.Count, sheet.Outputs.Count);
Assert.Equal(data.Goods.First(g => g.Id == "iron_ore").Index, sheet.Inputs[0].Good);
Assert.True(sheet.Inputs[0].Partners.Count > 0 && sheet.Inputs[0].Partners.All(p => p.Line == -1), "fornitori, nessuno collegato");
Assert.Equal(data.Balance.Growth.MaxLevel, (int)sheet.MaxLevel);
Assert.Equal(-1, sheet.ServingLine);
Assert.True(sheet.ForSale && !sheet.BuyUnlocked, "in vendita, acquisto non ancora sbloccato");
Assert.Equal(data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry).Level, (int)sheet.BuyTier);
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
}
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();