diff --git a/client/RailEnterprise.Client/assets/i18n/strings.csv b/client/RailEnterprise.Client/assets/i18n/strings.csv index 99eff90..a689ca5 100644 --- a/client/RailEnterprise.Client/assets/i18n/strings.csv +++ b/client/RailEnterprise.Client/assets/i18n/strings.csv @@ -1,9 +1,12 @@ 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 Alto,,High Ambra,,Amber Amministrazione controllata,,Receivership @@ -20,23 +23,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,10 +343,18 @@ 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 +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 degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans. dei ricavi,,of revenue @@ -346,28 +363,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 +411,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 +545,55 @@ 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 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 +641,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 +658,19 @@ 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 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 +698,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 +723,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 +752,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 +764,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,52 +773,106 @@ 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. -Avanti,,Next -Salta passo,,Skip step -Chiudi tutorial,,Close tutorial -Tutorial,,Tutorial -Riduci o espandi il riquadro del tutorial,,Collapse or expand the tutorial box -Passo {0} di {1},,Step {0} of {1} -Fine,,Finish -Fatto,,Done -Il tutorial si riapre con F1 o dal menu,,Reopen the tutorial with F1 or from the menu -Mostra il tutorial,,Show the tutorial -Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1,,Step-by-step guide to your first line: close it whenever you like and reopen it with F1 -Partita locale con il tutorial dal primo passo,,Local game with the tutorial from the first step -Benvenuto in Rail Enterprise,,Welcome to Rail Enterprise -"Guidi una compagnia ferroviaria: costruisci binari e stazioni, trasporti merci e pendolari e fai crescere il patrimonio fino a dominare il mercato. Questo tutorial ti accompagna nella prima linea; puoi saltare un passo o chiuderlo quando vuoi.",,"You run a railway company: build track and stations, carry goods and commuters and grow your net worth until you dominate the market. This tutorial walks you through your first line; you can skip a step or close it whenever you like." -Muovi la mappa,,Move the map -Trascina con il tasto destro (o usa WASD e le frecce) per spostarti e gira la rotella per lo zoom. Cerca una città e un'industria vicine: saranno le due stazioni della prima linea.,,Drag with the right mouse button (or use WASD and the arrow keys) to move and turn the wheel to zoom. Look for a town and an industry close to each other: they will be the two stations of your first line. -Il tempo,,Time -"In alto scegli la velocità del gioco: II mette in pausa, 1× – 8× accelerano. Anche la barra spaziatrice mette in pausa e riprende. Cambia la velocità per proseguire.",,"At the top you choose the game speed: II pauses, 1× – 8× speed it up. The space bar also pauses and resumes. Change the speed to continue." -Costruisci due stazioni,,Build two stations -Apri lo strumento Stazione e fai clic sulla mappa vicino a un'industria e poi vicino a una città. Il cerchio è il bacino di utenza: le merci e i passeggeri arrivano solo da lì.,,Open the Station tool and click the map near an industry and then near a town. The circle is the catchment area: goods and passengers only come from inside it. -Costruisci un deposito,,Build a depot -"Con lo strumento Deposito posa un deposito vicino a una delle stazioni. Nel deposito si comprano i veicoli, si compongono i treni e si fanno le manutenzioni.",,"With the Depot tool place a depot near one of the stations. In the depot you buy vehicles, compose trains and carry out maintenance." -Lo strumento Binari,,The Track tool -Apri lo strumento Binari: scegli la classe del binario e se ammettere ponti e gallerie.,,Open the Track tool: choose the track class and whether to allow bridges and tunnels. -Guarda il profilo e le opere,,Look at the profile and the structures -"Fai clic sulla prima stazione e muovi il mouse verso la seconda: il profilo mostra il terreno e la quota del binario. Sotto compaiono rilevati, trincee, ponti e gallerie con lunghezza, pendenza, costo e giorni di cantiere. Se attraversi un fiume vedrai il ponte.",,"Click the first station and move the mouse towards the second: the profile shows the terrain and the height of the track. Below it you see embankments, cuttings, bridges and tunnels with length, gradient, cost and days of work. If you cross a river you will see the bridge." -Costruisci il binario,,Build the track -"Aggiungi punti con altri clic per evitare salite ripide, poi premi Costruisci (o Invio). Il costo viene addebitato subito e il cantiere parte.",,"Add points with more clicks to avoid steep climbs, then press Build (or Enter). The cost is charged at once and construction starts." -Collega il deposito,,Connect the depot -"Il deposito deve essere raccordato alla linea: traccia un breve binario dal deposito alla stazione più vicina. Se è già collegato, premi Salta passo.",,"The depot must be connected to the line: lay a short track from the depot to the nearest station. If it is already connected, press Skip step." -Attendi i cantieri,,Wait for construction -I cantieri richiedono giorni di gioco: accelera il tempo e osserva il tratteggio dei lavori che diventa binario.,,Construction takes game days: speed up time and watch the dashed works turn into track. -Compra una locomotiva,,Buy a locomotive -"Apri Treni, scegli il deposito e una locomotiva dal catalogo, poi premi Compra veicoli.",,"Open Trains, choose the depot and a locomotive from the catalogue, then press Buy vehicles." -Compra i carri,,Buy the wagons -Ora compra qualche carro per la merce dell'industria (o carrozze per i pendolari): ogni carro accetta solo alcune merci.,,Now buy a few wagons for the industry's goods (or coaches for commuters): each wagon only accepts certain goods. -Componi il treno,,Compose the train -"Seleziona nell'elenco del deposito la locomotiva e i carri, nell'ordine in cui li vuoi, dai un nome al treno e premi Componi.",,"In the depot list select the locomotive and the wagons in the order you want, name the train and press Compose." -Crea una linea,,Create a line -Apri Linee e fai clic sulle due stazioni in ordine: sono le fermate. Scegli nome e colore e premi Crea linea.,,Open Lines and click the two stations in order: they are the stops. Choose a name and a colour and press Create line. -Assegna il treno alla linea,,Assign the train to the line -"Torna in Treni, seleziona il treno, scegli la linea e premi Assegna: il treno esce dal deposito e comincia il servizio.",,"Go back to Trains, select the train, choose the line and press Assign: the train leaves the depot and starts service." -Il Mercato globale,,The Global market -"Apri il Mercato: prezzi, offerta e domanda di ogni bene, la previsione e dove conviene vendere. Ti dice quali linee rendono di più.",,"Open the Market: prices, supply and demand of every good, the forecast and where it pays to sell. It tells you which lines earn the most." -Le Finanze,,Finances -"Apri le Finanze: conto economico per voce, rating e prestiti. Un prestito ben speso costruisce linee; troppi debiti abbassano il rating e alzano il tasso.",,"Open Finances: income statement by item, rating and loans. A well-spent loan builds lines; too much debt lowers the rating and raises the rate." -"Apri la Scalata (o fai clic sul livello in alto): i livelli della compagnia, che cosa sbloccano e che cosa manca per salire.",,"Open the Climb (or click the tier at the top): the company tiers, what they unlock and what is missing to move up." -Qualche consiglio,,A few tips -Collega industrie che producono a chi consuma la loro merce e porta i lavoratori dalle città alle industrie. Tieni d'occhio le Officine: un treno trascurato si guasta. Controlla cassa e rating prima di indebitarti. Buon viaggio! Puoi riaprire il tutorial con F1.,,Connect producing industries to those that consume their goods and bring workers from towns to industries. Keep an eye on the Workshops: a neglected train breaks down. Check cash and rating before borrowing. Have a good journey! You can reopen the tutorial with F1. +Avanti,,Next +Salta passo,,Skip step +Chiudi tutorial,,Close tutorial +Tutorial,,Tutorial +Riduci o espandi il riquadro del tutorial,,Collapse or expand the tutorial box +Passo {0} di {1},,Step {0} of {1} +Fine,,Finish +Fatto,,Done +Il tutorial si riapre con F1 o dalla schermata iniziale,,Reopen the tutorial with F1 or from the start screen +Mostra il tutorial,,Show the tutorial +Tutorial non disponibile: {0},,Tutorial not available: {0} +Avvio della partita di prova del tutorial…,,Starting the tutorial practice game… +Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1,,Step-by-step guide to your first line: close it whenever you like and reopen it with F1 +"Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è",,"New practice local game with the tutorial from the first step: your own local game stays as it is" +Benvenuto in Rail Enterprise,,Welcome to Rail Enterprise +"Guidi una compagnia ferroviaria: costruisci binari e stazioni, trasporti merci e pendolari e fai crescere il patrimonio fino a dominare il mercato. Questo tutorial ti accompagna nella prima linea; puoi saltare un passo o chiuderlo quando vuoi.",,"You run a railway company: build track and stations, carry goods and commuters and grow your net worth until you dominate the market. This tutorial walks you through your first line; you can skip a step or close it whenever you like." +Muovi la mappa,,Move the map +Trascina con il tasto destro (o usa WASD e le frecce) per spostarti e gira la rotella per lo zoom. Cerca una città e un'industria vicine: saranno le due stazioni della prima linea.,,Drag with the right mouse button (or use WASD and the arrow keys) to move and turn the wheel to zoom. Look for a town and an industry close to each other: they will be the two stations of your first line. +Il tempo,,Time +"In alto scegli la velocità del gioco: II mette in pausa, 1× – 8× accelerano. Anche la barra spaziatrice mette in pausa e riprende. Cambia la velocità per proseguire.",,"At the top you choose the game speed: II pauses, 1× – 8× speed it up. The space bar also pauses and resumes. Change the speed to continue." +Costruisci due stazioni,,Build two stations +Apri lo strumento Stazione e fai clic sulla mappa vicino a un'industria e poi vicino a una città. Il cerchio è il bacino di utenza: le merci e i passeggeri arrivano solo da lì.,,Open the Station tool and click the map near an industry and then near a town. The circle is the catchment area: goods and passengers only come from inside it. +Costruisci un deposito,,Build a depot +"Con lo strumento Deposito posa un deposito vicino a una delle stazioni. Nel deposito si comprano i veicoli, si compongono i treni e si fanno le manutenzioni.",,"With the Depot tool place a depot near one of the stations. In the depot you buy vehicles, compose trains and carry out maintenance." +Lo strumento Binari,,The Track tool +Apri lo strumento Binari: scegli la classe del binario e se ammettere ponti e gallerie.,,Open the Track tool: choose the track class and whether to allow bridges and tunnels. +Guarda il profilo e le opere,,Look at the profile and the structures +"Fai clic sulla prima stazione e muovi il mouse verso la seconda: il profilo mostra il terreno e la quota del binario. Sotto compaiono rilevati, trincee, ponti e gallerie con lunghezza, pendenza, costo e giorni di cantiere. Se attraversi un fiume vedrai il ponte.",,"Click the first station and move the mouse towards the second: the profile shows the terrain and the height of the track. Below it you see embankments, cuttings, bridges and tunnels with length, gradient, cost and days of work. If you cross a river you will see the bridge." +Costruisci il binario,,Build the track +"Aggiungi punti con altri clic per evitare salite ripide, poi premi Costruisci (o Invio). Il costo viene addebitato subito e il cantiere parte.",,"Add points with more clicks to avoid steep climbs, then press Build (or Enter). The cost is charged at once and construction starts." +Collega il deposito,,Connect the depot +"Il deposito deve essere raccordato alla linea: traccia un breve binario dal deposito alla stazione più vicina. Se è già collegato, premi Salta passo.",,"The depot must be connected to the line: lay a short track from the depot to the nearest station. If it is already connected, press Skip step." +Attendi i cantieri,,Wait for construction +I cantieri richiedono giorni di gioco: accelera il tempo e osserva il tratteggio dei lavori che diventa binario.,,Construction takes game days: speed up time and watch the dashed works turn into track. +Compra una locomotiva,,Buy a locomotive +"Apri Treni, scegli il deposito e una locomotiva dal catalogo, poi premi Compra veicoli.",,"Open Trains, choose the depot and a locomotive from the catalogue, then press Buy vehicles." +Compra i carri,,Buy the wagons +Ora compra qualche carro per la merce dell'industria (o carrozze per i pendolari): ogni carro accetta solo alcune merci.,,Now buy a few wagons for the industry's goods (or coaches for commuters): each wagon only accepts certain goods. +Componi il treno,,Compose the train +"Seleziona nell'elenco del deposito la locomotiva e i carri, nell'ordine in cui li vuoi, dai un nome al treno e premi Componi.",,"In the depot list select the locomotive and the wagons in the order you want, name the train and press Compose." +Crea una linea,,Create a line +Apri Linee e fai clic sulle due stazioni in ordine: sono le fermate. Scegli nome e colore e premi Crea linea.,,Open Lines and click the two stations in order: they are the stops. Choose a name and a colour and press Create line. +Assegna il treno alla linea,,Assign the train to the line +"Torna in Treni, seleziona il treno, scegli la linea e premi Assegna: il treno esce dal deposito e comincia il servizio.",,"Go back to Trains, select the train, choose the line and press Assign: the train leaves the depot and starts service." +Il Mercato globale,,The Global market +"Apri il Mercato: prezzi, offerta e domanda di ogni bene, la previsione e dove conviene vendere. Ti dice quali linee rendono di più.",,"Open the Market: prices, supply and demand of every good, the forecast and where it pays to sell. It tells you which lines earn the most." +Le Finanze,,Finances +"Apri le Finanze: conto economico per voce, rating e prestiti. Un prestito ben speso costruisce linee; troppi debiti abbassano il rating e alzano il tasso.",,"Open Finances: income statement by item, rating and loans. A well-spent loan builds lines; too much debt lowers the rating and raises the rate." +"Apri la Scalata (o fai clic sul livello in alto): i livelli della compagnia, che cosa sbloccano e che cosa manca per salire.",,"Open the Climb (or click the tier at the top): the company tiers, what they unlock and what is missing to move up." +Qualche consiglio,,A few tips +Collega industrie che producono a chi consuma la loro merce e porta i lavoratori dalle città alle industrie. Tieni d'occhio le Officine: un treno trascurato si guasta. Controlla cassa e rating prima di indebitarti. Buon viaggio! Puoi riaprire il tutorial con F1.,,Connect producing industries to those that consume their goods and bring workers from towns to industries. Keep an eye on the Workshops: a neglected train breaks down. Check cash and rating before borrowing. Have a good journey! You can reopen the tutorial with F1. +Verifica connessione,,Test connection +Versione,,Version +Versione del gioco,,Game version +viaggio medio,,average trip +Sostituire la partita?,,Replace the game? +Sostituisci la partita,,Replace the game +Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with the save «{1}» for every connected client ({2}). Anything not saved will be lost. +Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso.,,The server will replace the current game ({0}) with a new game for every connected client ({1}). Anything not saved will be lost. +Server raggiungibile,,Server reachable +Server locale spento: «Connetti e riprendi» lo avvia,,Local server off: «Connect and resume» starts it +protocollo,,protocol +in sede,,on site +Prezzo di vendita,,Selling price +Offerta inviata…,,Offer sent… +Industria inattiva: non è in vendita finché non riprende a produrre.,,Inactive industry: not for sale until it starts producing again. +L'industria è ferma: riprova a fermo finito.,,The industry is stopped: try again when the stop is over. +C'è già un lavoro in programma.,,Work is already scheduled. +Rinnovo della flotta,,Fleet renewal +Rinnova i veicoli superati,,Renew superseded vehicles +Rinnova,,Renew +Era,,Era +Prossima era,,Next era +Valore della flotta,,Fleet value +Nessun veicolo superato,,No superseded vehicles +Quadro della flotta in arrivo dal server…,,Fleet overview coming from the server… +Cassa insufficiente.,,Not enough cash. +In produzione fino al {0}.,,In production until {0}. +"Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite.",,"Renewal: {0} superseded vehicles, net cost {1} after resale." +Seleziona i veicoli da vendere,,Select the vehicles to sell +Superato dal {0}.,,Superseded since {0}. +"Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4}).",,"Superseded since {0}: successor {1} ({2} kW, {3} km/h, {4})." +da rinnovare,,to renew +e altri {0} veicoli superati,,and {0} more superseded vehicles +fuori produzione,,out of production +manutenzione ×{0:0.##},,maintenance ×{0:0.##} +rivendita {0},,resale {0} +"successore {0} ({1} kW, {2} km/h, {3})",,"successor {0} ({1} kW, {2} km/h, {3})" +superato,,superseded +superato dal {0},,superseded since {0} +valore {0},,value {0} +"{0}: {1} veicoli da rinnovare, spesa netta {2}",,"{0}: {1} vehicles to renew, net cost {2}" +rinnovo prenotato,,renewal booked +Rinnovo già prenotato.,,Renewal already booked. +Audio,,Audio +Volume generale,,Master volume +Musica,,Music +Ambiente,,Ambience +Effetti,,Effects +Interfaccia,,Interface +Muto,,Mute +Il tasto M attiva e toglie il muto durante la partita.,,The M key toggles mute during the game. +Audio (M: muto),,Audio (M: mute) diff --git a/client/RailEnterprise.Client/scripts/App/AutoPilot.cs b/client/RailEnterprise.Client/scripts/App/AutoPilot.cs index 7394a92..3b4f3a2 100644 --- a/client/RailEnterprise.Client/scripts/App/AutoPilot.cs +++ b/client/RailEnterprise.Client/scripts/App/AutoPilot.cs @@ -209,13 +209,14 @@ public partial class AutoPilot : Node var anchor = MapScale.V(near); var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0) .OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First(); + // dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di + // un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo + // (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom _game.OpenIndustry(industry.Id); await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30); - // al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa + // al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation)); GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}"); - _game.Map.CenterOn(MapScale.V(industry.Position)); - _game.Map.SetZoom(0.3f); await Shot("12_industria", 40); _game.ScrollPanel(1); await Shot("12b_industria_scorte", 20); @@ -254,5 +255,33 @@ 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"); + // livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la + // schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa + _game.CloseTools(); + var layer = new CanvasLayer { Layer = 10 }; + _game.AddChild(layer); + var connect = new ConnectScreen(World.Data, remember: false, autoStart: false); + layer.AddChild(connect); + await Frame(); + await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token); + await Until(() => connect.Loaded, "stato del server e salvataggi", 30); + await Shot("20_connessione", 30); + layer.QueueFree(); } } diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs b/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs new file mode 100644 index 0000000..29814ba --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs @@ -0,0 +1,643 @@ +using Godot; +using RailEnterprise.Client.Map; +using RailEnterprise.Client.Net; +using RailEnterprise.Core.Data; +using RailEnterprise.Core.Map; +using RailEnterprise.Core.Rail; +using RailEnterprise.Protocol; +using RailEnterprise.Protocol.Messages; + +namespace RailEnterprise.Client.Audio; + +/// +/// Regia dell'audio, figlia di Main per tutta la vita del client: bus e volumi, effetti +/// dell'interfaccia (clic di ogni pulsante, esito dei comandi), notifiche, cantieri completati, +/// treni in moto vicini al centro della telecamera (rotolamento, motore, sbuffi), ambiente dal +/// terreno sotto la telecamera e musica per era. Non decide nulla del gioco: reagisce a ciò che il +/// client riceve (esiti, notifiche, DailyDigest, moti dei treni) e alla vista. +/// I suoni si sintetizzano all'avvio su un altro thread (, ); +/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ). +/// +public partial class AudioManager : Node +{ + /// Unica istanza (nulla prima dell'avvio del client). + public static AudioManager? Instance { get; private set; } + + /// Volumi e muto attuali (anche con l'audio disattivato, per il pannello). + public AudioSettings Settings { get; private set; } = new(); + + /// Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra). + public event Action? SettingsChanged; + + private readonly bool _enabled; + private Task? _bankTask; + private bool _loaded; + + // suoni singoli + private AudioStreamWav? _click, _confirm, _error, _build, _chuff; + private readonly Callable _clickCallable; + private readonly AudioStreamWav?[] _notify = new AudioStreamWav?[3]; + private AudioStreamWav[] _birds = []; + private AudioStreamWav? _diesel, _hum; + + // riproduttori polifonici per bus e nomi dei bus già pronti (niente StringName per chiamata) + private readonly StringName _busUi = AudioBuses.Ui, _busSfx = AudioBuses.Sfx, _busAmbience = AudioBuses.Ambience; + private AudioStreamPlaybackPolyphonic? _ui, _sfx, _ambience; + + // ambiente: vento, acqua, mare, città + private const int AmbienceLoops = 4; + private static readonly float[] AmbienceLevel = [0.55f, 0.6f, 0.6f, 0.5f]; + private readonly AudioStreamPlayer[] _ambiencePlayers = new AudioStreamPlayer[AmbienceLoops]; + private readonly float[] _ambienceGain = new float[AmbienceLoops]; + private readonly float[] _ambienceTarget = new float[AmbienceLoops]; + private float _birdsChance; + private float _sinceAmbience = 1, _birdTimer = 3; + + // treni + private sealed class TrainChannel + { + public int Train = -1; + public Traction Traction; + public float Gain, Target, ChuffTimer; + public bool Kept; + public required AudioStreamPlayer Rumble { get; init; } + public required AudioStreamPlayer Engine { get; init; } + } + + private readonly TrainChannel[] _channels = new TrainChannel[AudioMix.TrainChannels]; + private readonly int[] _nearIds = new int[AudioMix.TrainChannels]; + private readonly float[] _nearDistances = new float[AudioMix.TrainChannels]; + + /// + /// Età massima (ms) dell'ultimo moto di un treno perché suoni: il server manda i moti dei treni + /// in marcia ogni 100 ms; un moto più vecchio è di un treno fermo in stazione (durante la sosta + /// non arrivano moti) o uscito dalla zona sottoscritta, e non va più ascoltato. + /// + private const long StaleMotionMs = 500; + + // musica: due riproduttori per la dissolvenza incrociata + private const float MusicLevel = 0.6f; + private const float FadeSeconds = 3f; + private readonly AudioStreamPlayer[] _music = new AudioStreamPlayer[2]; + private readonly float[] _musicGain = new float[2]; + private int _activeMusic; + private int _musicEra = -1; + private readonly Dictionary _themes = []; + private readonly HashSet _failedThemes = []; + private Task? _composing; + private int _composingEra; + private string[] _eraIds = ["steam"]; + private int[] _eraFroms = [0]; + + // partita in corso + private GameSession? _session; + private MapView? _map; + private Dictionary _vehicles = []; + private SynthRng _rng = new(0xA0D10); + private ulong _lastUiMs, _lastNotifyMs; + private bool _settingsDirty; + + // pannello delle impostazioni + private CanvasLayer? _overlay; + private AudioSettingsPanel? _panel; + + /// Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto. + public AudioManager(bool enabled) + { + _enabled = enabled; + Name = "AudioManager"; + _clickCallable = Callable.From(PlayClick); + } + + public AudioManager() : this(true) + { + } + + public override void _Ready() + { + Instance = this; + AudioBuses.Ensure(); + Settings = AudioSettings.Load(); + ApplySettings(); + if (!_enabled) return; + _bankTask = Task.Run(SoundBank.Create); + GetTree().NodeAdded += OnNodeAdded; + } + + public override void _ExitTree() + { + if (Instance == this) Instance = null; + Unbind(); + // chiusura della finestra con un volume appena cambiato: si salva comunque + SaveSettings(); + } + + /// Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale. + public void SetEras(IReadOnlyList eras) + { + if (eras.Count == 0) return; + _eraIds = new string[eras.Count]; + _eraFroms = new int[eras.Count]; + for (int i = 0; i < eras.Count; i++) + { + _eraIds[i] = eras[i].Id; + _eraFroms[i] = eras[i].From; + } + } + + // ------------------------------------------------------------------ impostazioni + + private void ApplySettings() + { + Settings.Apply(); + // senza audio (collaudo, server senza schermo) il Master resta muto, senza toccare il file + if (!_enabled) AudioServer.SetBusMute(0, true); + } + + /// Cambia il volume di un bus (indice in ) e lo applica subito. + public void SetVolume(int bus, float value) + { + Settings.Volumes[bus] = Math.Clamp(value, 0, 1); + _settingsDirty = true; + ApplySettings(); + SettingsChanged?.Invoke(); + } + + public void SetMuted(bool muted) + { + Settings.Muted = muted; + _settingsDirty = true; + ApplySettings(); + SettingsChanged?.Invoke(); + } + + public void ToggleMute() + { + SetMuted(!Settings.Muted); + SaveSettings(); + } + + /// Scrive volumi e muto in user://settings.cfg se sono cambiati dall'ultimo salvataggio. + public void SaveSettings() + { + if (!_settingsDirty) return; + _settingsDirty = false; + Settings.Save(); + } + + /// Apre il pannello «Audio» sopra a tutto (menu o partita). + public void ShowSettings() + { + if (_panel is not null && IsInstanceValid(_panel)) return; + if (_overlay is null) + { + _overlay = new CanvasLayer { Layer = 50 }; + AddChild(_overlay); + } + _panel = new AudioSettingsPanel(this); + _panel.TreeExited += () => _panel = null; + _overlay.AddChild(_panel); + } + + public override void _UnhandledKeyInput(InputEvent e) + { + if (e is InputEventKey { Pressed: true, Echo: false, Keycode: Key.M } key && !key.CtrlPressed && !key.AltPressed && !key.MetaPressed) + { + ToggleMute(); + GetViewport().SetInputAsHandled(); + } + } + + // ------------------------------------------------------------------ partita + + /// Collega la partita: messaggi della sessione e vista della mappa. + public void Bind(GameSession session, MapView map) + { + Unbind(); + _session = session; + _map = map; + _vehicles = session.World.Data.Vehicles.ToDictionary(v => v.Id); + SetEras(session.World.Data.Eras.Eras); + session.MessageApplied += OnMessage; + } + + /// + /// Scollega la partita (ritorno al menu): treni e ambiente sfumano. Con «only» scollega solo + /// se è ancora quella sessione (la schermata vecchia esce dall'albero dopo l'arrivo della nuova). + /// + public void Unbind(GameSession? only = null) + { + if (only is not null && !ReferenceEquals(only, _session)) return; + if (_session is not null) _session.MessageApplied -= OnMessage; + _session = null; + _map = null; + } + + private void OnMessage(IMessage message) + { + if (!_loaded) return; + switch (message) + { + case CommandResultMessage r: + PlayUi(r.Ok ? _confirm : _error, r.Ok ? 0.7f : 0.85f); + break; + case Notification n: + Notify(n.Event); + break; + case DailyDigest d: + int me = _session?.World.Summary?.CompanyId ?? -1; + for (int i = 0; i < d.Events.Count; i++) + { + var e = d.Events[i]; + if (e.Kind == ConstructionEventKind && e.Company == me && me >= 0) + { + Play(_sfx, _build, 0.8f, 1, _busSfx); + break; + } + } + break; + } + } + + /// Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo). + private const byte ConstructionEventKind = 5; + + private void Notify(EventInfo e) + { + int me = _session?.World.Summary?.CompanyId ?? -1; + if (e.Company >= 0 && e.Company != me) return; + int level = e.Severity switch { 3 => 2, 2 => 1, _ => 0 }; + ulong now = Time.GetTicksMsec(); + // più notizie insieme: una sola campanella (le critiche suonano sempre) + if (level < 2 && now - _lastNotifyMs < 600) return; + _lastNotifyMs = now; + Play(_ui, _notify[level], level == 2 ? 0.9f : 0.75f, 1, _busUi); + } + + private void OnNodeAdded(Node node) + { + // un pulsante staccato e riattaccato (MarketPanel lo fa a ogni resoconto) è già collegato + if (node is BaseButton button && !button.IsConnected(BaseButton.SignalName.Pressed, _clickCallable)) + button.Connect(BaseButton.SignalName.Pressed, _clickCallable); + } + + private void PlayClick() => PlayUi(_click, 0.6f); + + private void PlayUi(AudioStreamWav? stream, float gain) + { + ulong now = Time.GetTicksMsec(); + if (stream == _click && now - _lastUiMs < 40) return; + _lastUiMs = now; + Play(_ui, stream, gain, 1, _busUi); + } + + private static void Play(AudioStreamPlaybackPolyphonic? playback, AudioStreamWav? stream, float gain, float pitch, StringName bus) + { + if (playback is null || stream is null || gain <= 0.001f) return; + playback.PlayStream(stream, 0, AudioMix.LinearToDb(gain), pitch, AudioServer.PlaybackType.Default, bus); + } + + // ------------------------------------------------------------------ caricamento + + /// Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale. + private sealed class SoundBank + { + public required float[] Click, Confirm, Error, Construction, Chuff, Rumble, Diesel, Hum, Wind, River, Sea, City; + public required float[][] Notify, Birds; + + public static SoundBank Create() => new() + { + Click = Synth.Click(), Confirm = Synth.Confirm(), Error = Synth.Error(), Construction = Synth.BuildComplete(), + Chuff = Synth.Chuff(), Rumble = Synth.RailRumbleLoop(), + Diesel = Synth.DieselDroneLoop(), Hum = Synth.ElectricHumLoop(), Wind = Synth.WindLoop(), River = Synth.RiverLoop(), + Sea = Synth.SeaLoop(), City = Synth.CityLoop(), + Notify = [Synth.Notify(0), Synth.Notify(1), Synth.Notify(2)], + Birds = [Synth.Bird(0), Synth.Bird(1), Synth.Bird(2)], + }; + } + + private static AudioStreamWav Wav(float[] samples, bool loop = false) + { + var w = new AudioStreamWav + { + Format = AudioStreamWav.FormatEnum.Format16Bits, + MixRate = Synth.Rate, + Stereo = false, + Data = AudioMix.ToPcm16(samples), + }; + if (loop) + { + w.LoopMode = AudioStreamWav.LoopModeEnum.Forward; + w.LoopBegin = 0; + w.LoopEnd = samples.Length; + } + return w; + } + + private AudioStreamPlayer Player(string bus, AudioStream? stream = null) + { + var p = new AudioStreamPlayer { Bus = bus, Stream = stream }; + AddChild(p); + return p; + } + + private AudioStreamPlaybackPolyphonic? Polyphonic(string bus, int voices) + { + var p = Player(bus, new AudioStreamPolyphonic { Polyphony = voices }); + p.Play(); + return p.GetStreamPlayback() as AudioStreamPlaybackPolyphonic; + } + + private void Load(SoundBank bank) + { + _click = Wav(bank.Click); + _confirm = Wav(bank.Confirm); + _error = Wav(bank.Error); + _build = Wav(bank.Construction); + _chuff = Wav(bank.Chuff); + for (int i = 0; i < _notify.Length; i++) _notify[i] = Wav(bank.Notify[i]); + _birds = bank.Birds.Select(b => Wav(b)).ToArray(); + _diesel = Wav(bank.Diesel, loop: true); + _hum = Wav(bank.Hum, loop: true); + var rumble = Wav(bank.Rumble, loop: true); + + _ui = Polyphonic(AudioBuses.Ui, 8); + _sfx = Polyphonic(AudioBuses.Sfx, 16); + _ambience = Polyphonic(AudioBuses.Ambience, 4); + float[][] loops = [bank.Wind, bank.River, bank.Sea, bank.City]; + for (int i = 0; i < AmbienceLoops; i++) + { + var p = Player(AudioBuses.Ambience, Wav(loops[i], loop: true)); + p.VolumeLinear = 0; + _ambiencePlayers[i] = p; + } + for (int i = 0; i < _channels.Length; i++) + { + var r = Player(AudioBuses.Sfx, rumble); + var e = Player(AudioBuses.Sfx); + r.VolumeLinear = e.VolumeLinear = 0; + _channels[i] = new TrainChannel { Rumble = r, Engine = e }; + } + for (int i = 0; i < _music.Length; i++) _music[i] = Player(AudioBuses.Music); + _loaded = true; + } + + // ------------------------------------------------------------------ ciclo + + public override void _Process(double delta) + { + if (!_enabled) return; + if (!_loaded) + { + if (_bankTask is not { IsCompleted: true }) return; + if (_bankTask.IsCompletedSuccessfully) Load(_bankTask.Result); + else + { + GD.PrintErr($"Audio: sintesi non riuscita: {_bankTask.Exception?.GetBaseException().Message}"); + _bankTask = null; + return; + } + } + float dt = (float)Math.Min(delta, 0.1); + UpdateMusic(dt); + UpdateAmbience(dt); + UpdateTrains(dt); + } + + private int WantedEra() + { + var w = _session?.World; + if (w?.Calendar is null) return 0; + return AudioMix.EraIndex(w.Year, _eraFroms); + } + + private void UpdateMusic(float dt) + { + int want = WantedEra(); + if (_composing is { IsCompleted: true }) + { + if (_composing.IsCompletedSuccessfully) _themes[_composingEra] = Wav(_composing.Result, loop: true); + else + { + _failedThemes.Add(_composingEra); + GD.PrintErr($"Audio: tema dell'era non composto: {_composing.Exception?.GetBaseException().Message}"); + } + _composing = null; + } + if (want != _musicEra) + { + if (_themes.TryGetValue(want, out var theme)) + { + // dissolvenza incrociata: il nuovo tema entra sull'altro riproduttore + _activeMusic = 1 - _activeMusic; + var p = _music[_activeMusic]; + p.Stream = theme; + _musicGain[_activeMusic] = 0; + p.VolumeLinear = 0; + p.Play(); + _musicEra = want; + } + else if (_composing is null && !_failedThemes.Contains(want)) + { + int era = want; + string id = _eraIds[Math.Clamp(era, 0, _eraIds.Length - 1)]; + _composingEra = era; + _composing = Task.Run(() => MusicComposer.Compose(era, id)); + } + } + for (int i = 0; i < _music.Length; i++) + { + float target = i == _activeMusic && _musicEra >= 0 ? 1 : 0; + _musicGain[i] = AudioMix.Approach(_musicGain[i], target, 1 / FadeSeconds, dt); + _music[i].VolumeLinear = _musicGain[i] * MusicLevel; + if (_musicGain[i] <= 0 && i != _activeMusic && _music[i].Playing) _music[i].Stop(); + } + } + + private void UpdateAmbience(float dt) + { + _sinceAmbience += dt; + if (_sinceAmbience >= 0.25f) + { + _sinceAmbience = 0; + var gains = _map is not null && _session?.World.Terrain is { } terrain + ? AudioMix.Ambience(_map.Zoom, SampleTerrain(terrain, _map.VisibleRect())) + : default; + _ambienceTarget[0] = gains.Wind; + _ambienceTarget[1] = gains.Water; + _ambienceTarget[2] = gains.Sea; + _ambienceTarget[3] = gains.City; + _birdsChance = gains.Birds; + } + for (int i = 0; i < AmbienceLoops; i++) + { + _ambienceGain[i] = AudioMix.Approach(_ambienceGain[i], _ambienceTarget[i], 0.5f, dt); + var p = _ambiencePlayers[i]; + p.VolumeLinear = _ambienceGain[i] * AmbienceLevel[i]; + if (_ambienceGain[i] > 0 && !p.Playing) p.Play(_rng.Next01() * 4); + else if (_ambienceGain[i] <= 0 && p.Playing) p.Stop(); + } + if (_birdsChance > 0.05f && _birds.Length > 0) + { + _birdTimer -= dt; + if (_birdTimer <= 0) + { + Play(_ambience, _birds[_rng.Next(_birds.Length)], _birdsChance * 0.45f, _rng.Range(0.9f, 1.15f), _busAmbience); + _birdTimer = _rng.Range(1.5f, 6f) / (0.3f + _birdsChance); + } + } + } + + /// Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina). + private static TerrainMix SampleTerrain(Terrain t, Rect2 view) + { + const int grid = 8; + view = view.Grow(Math.Max(view.Size.X, view.Size.Y) * 0.125f); + int river = 0, lake = 0, sea = 0, town = 0, forest = 0, open = 0, total = 0; + for (int gy = 0; gy < grid; gy++) + { + for (int gx = 0; gx < grid; gx++) + { + double x = view.Position.X + (gx + 0.5) / grid * view.Size.X; + double y = view.Position.Y + (gy + 0.5) / grid * view.Size.Y; + int cx = (int)Math.Floor(x / t.CellSizeM), cy = (int)Math.Floor(y / t.CellSizeM); + if (!t.InBounds(cx, cy)) continue; + int i = t.Index(cx, cy); + total++; + switch ((CellType)t.Types[i]) + { + case CellType.Water when t.RiverWidth[i] > 0: river++; break; + case CellType.Water: lake++; break; + case CellType.Sea: sea++; break; + case CellType.Town or CellType.Industry: town++; break; + case CellType.Forest: forest++; break; + default: open++; break; + } + } + } + if (total == 0) return default; + float k = 1f / total; + return new TerrainMix { River = river * k, Lake = lake * k, Sea = sea * k, Town = town * k, Forest = forest * k, Open = open * k }; + } + + private void UpdateTrains(float dt) + { + var w = _session?.World; + var map = _map; + int count = 0; + Vector2 center = default; + float zoom = 1, radius = 1; + if (w is not null && map is not null && _session is { } session && w.Speed > 0) + { + center = map.Camera.GetScreenCenterPosition(); + zoom = map.Zoom; + radius = map.GetViewportRect().Size.Length() / 2; + long now = (long)Time.GetTicksMsec(); + foreach (var (id, head) in map.Trains.Heads) + { + if (!w.Motions.TryGetValue(id, out var m) || m.State != (byte)TrainState.Moving || m.Speed < 0.5f) continue; + if (!session.MotionReceivedMs.TryGetValue(id, out long at) || now - at > StaleMotionMs) continue; + // oltre il raggio non si sentirebbe: niente canale (eviterebbe Play e Stop a ogni fotogramma) + float distance = head.DistanceTo(center) * zoom; + if (distance >= radius) continue; + count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, distance); + } + } + // i canali restano ai loro treni finché sono tra i più vicini; gli altri sfumano + foreach (var ch in _channels) ch.Kept = ch.Train >= 0 && Contains(_nearIds, count, ch.Train); + for (int k = 0; k < count; k++) + { + int id = _nearIds[k]; + if (HasChannel(id)) continue; + foreach (var ch in _channels) + { + if (ch.Train >= 0 && (ch.Kept || ch.Gain > 0.01f)) continue; + Assign(ch, id, w!); + ch.Kept = true; + break; + } + } + foreach (var ch in _channels) + { + float speed = 0; + if (ch.Kept && w is not null && map is not null && w.Motions.TryGetValue(ch.Train, out var m) && map.Trains.Heads.TryGetValue(ch.Train, out var head)) + { + speed = m.Speed; + ch.Target = AudioMix.TrainGain(head.DistanceTo(center) * zoom, radius, speed, zoom); + } + else ch.Target = 0; + ch.Gain = AudioMix.Approach(ch.Gain, ch.Target, 2.5f, dt); + if (ch.Train < 0) continue; + if (ch.Gain <= 0 && ch.Target <= 0) + { + ch.Train = -1; + ch.Rumble.Stop(); + ch.Engine.Stop(); + continue; + } + if (speed > 0) + { + ch.Rumble.PitchScale = AudioMix.RumblePitch(speed); + ch.Engine.PitchScale = AudioMix.EnginePitch(speed); + } + ch.Rumble.VolumeLinear = ch.Gain * 0.7f; + bool steam = ch.Traction == Traction.Steam; + ch.Engine.VolumeLinear = steam ? 0 : ch.Gain * 0.45f; + if (steam && speed > 0 && ch.Gain > 0.02f) + { + ch.ChuffTimer -= dt; + if (ch.ChuffTimer <= 0) + { + Play(_sfx, _chuff, ch.Gain * 0.9f, _rng.Range(0.92f, 1.08f), _busSfx); + ch.ChuffTimer = Math.Max(ch.ChuffTimer, 0) + AudioMix.ChuffInterval(speed); + } + } + } + } + + private static bool Contains(int[] ids, int count, int id) + { + for (int i = 0; i < count; i++) + { + if (ids[i] == id) return true; + } + return false; + } + + private bool HasChannel(int train) + { + foreach (var ch in _channels) + { + if (ch.Train == train) return true; + } + return false; + } + + private void Assign(TrainChannel ch, int train, Protocol.Client.ClientWorld w) + { + ch.Train = train; + ch.Traction = TractionOf(train, w); + ch.Gain = 0; + ch.ChuffTimer = _rng.Next01() * 0.2f; + ch.Rumble.VolumeLinear = 0; + ch.Rumble.Play(_rng.Next01() * 1.5f); + ch.Engine.VolumeLinear = 0; + if (ch.Traction == Traction.Steam) ch.Engine.Stop(); + else + { + ch.Engine.Stream = ch.Traction == Traction.Diesel ? _diesel : _hum; + ch.Engine.Play(_rng.Next01() * 0.9f); + } + } + + /// Trazione della prima locomotiva del treno (vapore se non si sa). + private Traction TractionOf(int train, Protocol.Client.ClientWorld w) + { + if (!w.Trains.TryGetValue(train, out var info)) return Traction.Steam; + foreach (int vid in info.Vehicles) + { + if (w.Vehicles.TryGetValue(vid, out var v) && _vehicles.TryGetValue(v.Type, out var def) && def.Kind == VehicleKind.Locomotive && def.Traction is { } traction) return traction; + } + return Traction.Steam; + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs b/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs new file mode 100644 index 0000000..6273967 --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/AudioMix.cs @@ -0,0 +1,150 @@ +namespace RailEnterprise.Client.Audio; + +/// Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti). +public struct TerrainMix +{ + public float River; + public float Lake; + public float Sea; + public float Town; + public float Forest; + public float Open; +} + +/// Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli. +public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds); + +/// +/// Miscelazione dell'audio senza dipendenze da Godot: guadagni dell'ambiente dal terreno e dallo +/// zoom, volume e intonazione dei treni dalla distanza sullo schermo e dalla velocità, scelta dei +/// treni più vicini senza allocazioni, ere dall'anno, dissolvenze e conversione in PCM. Le costanti +/// sono di resa sonora del client, non della simulazione. +/// +public static class AudioMix +{ + /// Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme. + public const float FarZoom = 0.02f; + /// Zoom da cui ambiente e treni sono al massimo. + public const float NearZoom = 0.5f; + /// Canali dei treni: al più tanti treni suonano insieme. + public const int TrainChannels = 3; + /// Velocità (m/s) a cui il rotolamento è al massimo. + public const float FullSpeedMs = 25f; + /// Sbuffi al secondo da fermo (al passo) e alla velocità . + public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f; + /// Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti. + public const float ChuffFullSpeedMs = 30f; + + public static float Clamp01(float x) => x < 0 ? 0 : x > 1 ? 1 : x; + + public static float SmoothStep(float x) + { + x = Clamp01(x); + return x * x * (3 - 2 * x); + } + + /// Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom. + public static float Closeness(float zoom) + { + if (zoom <= 0) return 0; + return SmoothStep((MathF.Log(zoom) - MathF.Log(FarZoom)) / (MathF.Log(NearZoom) - MathF.Log(FarZoom))); + } + + /// + /// Ambiente: il vento c'è sempre (più forte da lontano), acqua, mare e città seguono la + /// frazione del terreno visibile e si attenuano allontanandosi; gli uccelli solo da vicino in + /// campagna e nei boschi. + /// + public static AmbienceGains Ambience(float zoom, in TerrainMix t) + { + float close = Closeness(zoom); + float wind = 0.35f + 0.35f * (1 - close) + 0.15f * t.Open; + float water = Clamp01((t.River * 3 + t.Lake * 1.5f) * (0.25f + 0.75f * close)); + float sea = Clamp01(t.Sea * 1.6f * (0.45f + 0.55f * close)); + float city = Clamp01(t.Town * 4 * (0.15f + 0.85f * close)); + float birds = Clamp01((t.Forest + t.Open * 0.6f) * close * close * (1 - t.Town * 2)); + // l'acqua e la città coprono un po' il vento + wind *= 1 - 0.4f * MathF.Max(sea, city); + return new AmbienceGains(Clamp01(wind), water, sea, city, birds); + } + + /// Volume di un treno: vicinanza al centro dello schermo, velocità e zoom. + /// Distanza in pixel dal centro dello schermo. + /// Raggio oltre il quale non si sente (di solito metà della diagonale). + public static float TrainGain(float distancePx, float radiusPx, float speedMs, float zoom) + { + if (radiusPx <= 0) return 0; + float near = 1 - Clamp01(distancePx / radiusPx); + float speed = Clamp01(speedMs / FullSpeedMs); + return near * near * (0.25f + 0.75f * speed) * (0.15f + 0.85f * Closeness(zoom)); + } + + /// Intonazione del rotolamento: più rapido e acuto con la velocità. + public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs); + + /// Intonazione del motore (diesel o elettrico) con la velocità. + public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs); + + /// + /// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare + /// da a fino a , + /// così segue la velocità su tutto l'esercizio normale. È una resa sonora, non il passo reale della + /// ruota: sullo schermo il tempo dei treni corre decine di volte più veloce e gli sbuffi reali + /// sarebbero un ronzio continuo. + /// + public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs)); + + /// + /// Inserisce un candidato nell'elenco ordinato dei più vicini (al più ids.Length): nessuna + /// allocazione, gli elenchi sono preparati una volta sola. Restituisce il nuovo conteggio. + /// + public static int InsertNearest(int[] ids, float[] distances, int count, int id, float distance) + { + int capacity = ids.Length; + if (count == capacity && distance >= distances[capacity - 1]) return count; + int i = Math.Min(count, capacity - 1); + while (i > 0 && distances[i - 1] > distance) + { + ids[i] = ids[i - 1]; + distances[i] = distances[i - 1]; + i--; + } + ids[i] = id; + distances[i] = distance; + return Math.Min(count + 1, capacity); + } + + /// Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno. + public static int EraIndex(int year, IReadOnlyList froms) + { + int index = 0; + for (int i = 0; i < froms.Count; i++) + { + if (froms[i] <= year) index = i; + } + return index; + } + + /// Avvicina un valore al bersaglio con velocità costante (unità al secondo). + public static float Approach(float current, float target, float ratePerSecond, float dt) + { + float step = ratePerSecond * dt; + return current < target ? MathF.Min(target, current + step) : MathF.Max(target, current - step); + } + + /// Lineare → decibel, con −80 dB come silenzio. + public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear); + + /// Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV). + public static byte[] ToPcm16(float[] samples) + { + var bytes = new byte[samples.Length * 2]; + for (int i = 0; i < samples.Length; i++) + { + short s = (short)Math.Clamp((int)MathF.Round(samples[i] * 32767f), short.MinValue, short.MaxValue); + bytes[2 * i] = (byte)s; + bytes[2 * i + 1] = (byte)(s >> 8); + } + return bytes; + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs b/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs new file mode 100644 index 0000000..3fadbc5 --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/AudioSettings.cs @@ -0,0 +1,91 @@ +using Godot; + +namespace RailEnterprise.Client.Audio; + +/// Bus audio del client: Master e quattro bus che vi confluiscono. +public static class AudioBuses +{ + public const string Master = "Master"; + public const string Music = "Music"; + public const string Ambience = "Ambience"; + public const string Sfx = "Sfx"; + public const string Ui = "Ui"; + + /// Nell'ordine dei cursori delle impostazioni. + public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui]; + + /// + /// Crea i bus che mancano (idempotente: chiamarla più volte non ne aggiunge altri) e un + /// limitatore sul Master, così la somma di musica, ambiente ed effetti non satura. + /// + public static void Ensure() + { + foreach (string name in All) + { + if (name == Master || AudioServer.GetBusIndex(name) >= 0) continue; + int index = AudioServer.BusCount; + AudioServer.AddBus(index); + AudioServer.SetBusName(index, name); + AudioServer.SetBusSend(index, Master); + } + bool limited = false; + for (int i = 0; i < AudioServer.GetBusEffectCount(0); i++) + { + if (AudioServer.GetBusEffect(0, i) is AudioEffectHardLimiter) limited = true; + } + if (!limited) AudioServer.AddBusEffect(0, new AudioEffectHardLimiter { CeilingDb = -0.5f }); + } +} + +/// +/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di +/// user://settings.cfg (lo stesso file della lingua e del server). +/// +public sealed class AudioSettings +{ + public const string Path = "user://settings.cfg"; + private const string Section = "audio"; + + private static readonly float[] Defaults = [0.8f, 0.55f, 0.7f, 0.8f, 0.7f]; + + /// Volumi nell'ordine di . + public float[] Volumes { get; } = (float[])Defaults.Clone(); + + public bool Muted { get; set; } + + public static AudioSettings Load() + { + var s = new AudioSettings(); + var cfg = new ConfigFile(); + if (cfg.Load(Path) != Error.Ok) return s; + for (int i = 0; i < AudioBuses.All.Length; i++) + { + float v = (float)(double)cfg.GetValue(Section, Key(i), Defaults[i]); + s.Volumes[i] = Math.Clamp(v, 0, 1); + } + s.Muted = (bool)cfg.GetValue(Section, "muted", false); + return s; + } + + public void Save() + { + var cfg = new ConfigFile(); + cfg.Load(Path); + for (int i = 0; i < AudioBuses.All.Length; i++) cfg.SetValue(Section, Key(i), Volumes[i]); + cfg.SetValue(Section, "muted", Muted); + cfg.Save(Path); + } + + private static string Key(int i) => AudioBuses.All[i].ToLowerInvariant(); + + /// Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²). + public void Apply() + { + for (int i = 0; i < AudioBuses.All.Length; i++) + { + int bus = AudioServer.GetBusIndex(AudioBuses.All[i]); + if (bus >= 0) AudioServer.SetBusVolumeDb(bus, AudioMix.LinearToDb(Volumes[i] * Volumes[i])); + } + AudioServer.SetBusMute(0, Muted); + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs b/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs new file mode 100644 index 0000000..4e9abe3 --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/AudioSettingsPanel.cs @@ -0,0 +1,110 @@ +using Godot; +using RailEnterprise.Client.App; +using static RailEnterprise.Client.App.Localization; + +namespace RailEnterprise.Client.Audio; + +/// +/// Pannello «Audio» sopra a tutto: un cursore per bus (generale, musica, ambiente, effetti, +/// interfaccia) e il muto generale. I cambi si sentono subito; quando il pannello esce dall'albero +/// (anche chiudendo la finestra del gioco) si salvano in user://settings.cfg. Esc o un clic +/// sinistro fuori chiudono. +/// +public partial class AudioSettingsPanel : Control +{ + private readonly AudioManager _audio; + private readonly List<(HSlider Slider, Label Value)> _rows = []; + private readonly CheckBox _mute = new() { Text = T("Muto") }; + + private static readonly string[] Captions = ["Volume generale", "Musica", "Ambiente", "Effetti", "Interfaccia"]; + + public AudioSettingsPanel(AudioManager audio) => _audio = audio; + + public override void _Ready() + { + SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + UiTheme.Apply(this); + var shade = new ColorRect { Color = new Color(0, 0, 0, 0.5f), MouseFilter = MouseFilterEnum.Stop }; + shade.SetAnchorsPreset(LayoutPreset.FullRect); + shade.GuiInput += e => + { + // solo il clic sinistro: la rotella e il tasto destro arrivano anch'essi come pressioni + if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) Close(); + }; + AddChild(shade); + var center = new CenterContainer { MouseFilter = MouseFilterEnum.Ignore }; + center.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(center); + var panel = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) }; + center.AddChild(panel); + var col = new VBoxContainer(); + col.AddThemeConstantOverride("separation", 12); + panel.AddChild(col); + col.AddChild(UiTheme.TitleLabel(T("Audio"), 34)); + + for (int i = 0; i < Captions.Length; i++) + { + int bus = i; + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 12); + var caption = UiTheme.Text(T(Captions[i]), 14, Palette.TextSecondary); + caption.CustomMinimumSize = new Vector2(150, 0); + row.AddChild(caption); + var slider = new HSlider + { + MinValue = 0, MaxValue = 1, Step = 0.05, SizeFlagsHorizontal = SizeFlags.ExpandFill, + SizeFlagsVertical = SizeFlags.ShrinkCenter, Value = _audio.Settings.Volumes[i], + }; + var value = UiTheme.Text("", 14, bold: true); + value.CustomMinimumSize = new Vector2(48, 0); + value.HorizontalAlignment = HorizontalAlignment.Right; + slider.ValueChanged += v => _audio.SetVolume(bus, (float)v); + row.AddChild(slider); + row.AddChild(value); + col.AddChild(row); + _rows.Add((slider, value)); + } + _mute.ButtonPressed = _audio.Settings.Muted; + _mute.Toggled += on => _audio.SetMuted(on); + col.AddChild(_mute); + var hint = UiTheme.Text(T("Il tasto M attiva e toglie il muto durante la partita."), 13, Palette.TextSecondary); + hint.AutowrapMode = TextServer.AutowrapMode.WordSmart; + col.AddChild(hint); + var close = UiTheme.Primary(T("Chiudi")); + close.Pressed += Close; + col.AddChild(close); + _audio.SettingsChanged += Refresh; + Refresh(); + } + + public override void _ExitTree() + { + _audio.SettingsChanged -= Refresh; + _audio.SaveSettings(); + } + + private void Refresh() + { + for (int i = 0; i < _rows.Count; i++) + { + _rows[i].Slider.SetValueNoSignal(_audio.Settings.Volumes[i]); + _rows[i].Value.Text = $"{Math.Round(_audio.Settings.Volumes[i] * 100):0} %"; + } + _mute.SetPressedNoSignal(_audio.Settings.Muted); + } + + public override void _Input(InputEvent e) + { + if (e is InputEventKey { Pressed: true, Keycode: Key.Escape }) + { + Close(); + GetViewport().SetInputAsHandled(); + } + } + + private void Close() + { + if (IsQueuedForDeletion()) return; + QueueFree(); + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs b/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs new file mode 100644 index 0000000..985a4c7 --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/MusicComposer.cs @@ -0,0 +1,327 @@ +namespace RailEnterprise.Client.Audio; + +/// +/// Temi musicali procedurali per era, senza dipendenze da Godot. Ogni era ha uno stile (tempo, +/// metro, scala, timbri: valzer da carillon e fisarmonica per il vapore, organo e basso che +/// cammina per il diesel, vibrafono e archi per l'elettrico, arpeggi a impulsi per l'alta +/// velocità); progressione, arpeggio e melodia escono da un seme fisso (hash dell'id dell'era), +/// quindi lo stesso tema a ogni avvio. Forma in 16 battute: introduzione (accompagnamento), +/// melodia, melodia variata, coda; le code delle note rientrano dall'inizio, così l'anello si +/// ripete senza scatti. Uscita mono a Hz. +/// +public static class MusicComposer +{ + public const int Bars = 16; + + public enum Timbre { MusicBox, Accordion, Organ, Vibraphone, Strings, Pulse, Saw, SoftBass, PluckBass } + + public enum Comping { Held, Waltz } + + /// Stile di un'era. + public sealed record Style(int Bpm, int BeatsPerBar, int[] Scale, int RootMidi, Timbre Pad, Comping Comping, + Timbre Arp, int ArpPerBeat, Timbre Lead, Timbre Bass, bool WalkingBass, float Swing); + + private static readonly int[] Major = [0, 2, 4, 5, 7, 9, 11]; + private static readonly int[] Mixolydian = [0, 2, 4, 5, 7, 9, 10]; + private static readonly int[] Dorian = [0, 2, 3, 5, 7, 9, 10]; + + /// Progressioni per grado della scala (0 = primo grado), una battuta per accordo. + private static readonly int[][] Progressions = + [ + [0, 3, 4, 0], [0, 5, 3, 4], [0, 4, 5, 3], [1, 4, 0, 5], [5, 3, 0, 4], [0, 3, 1, 4], + ]; + + /// Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo). + public static Style StyleFor(int eraIndex) => (Math.Max(0, eraIndex) % 4) switch + { + 0 => new Style(116, 3, Major, 62, Timbre.Accordion, Comping.Waltz, Timbre.MusicBox, 0, Timbre.MusicBox, Timbre.SoftBass, false, 0), + 1 => new Style(96, 4, Mixolydian, 60, Timbre.Organ, Comping.Held, Timbre.Vibraphone, 1, Timbre.Organ, Timbre.PluckBass, true, 0.18f), + 2 => new Style(104, 4, Major, 65, Timbre.Strings, Comping.Held, Timbre.Vibraphone, 2, Timbre.Vibraphone, Timbre.SoftBass, false, 0), + _ => new Style(124, 4, Dorian, 57, Timbre.Saw, Comping.Held, Timbre.Pulse, 4, Timbre.Saw, Timbre.SoftBass, false, 0), + }; + + /// Seme fisso del tema: hash dell'id dell'era e della sua posizione. + public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL); + + /// Durata dell'anello in secondi. + public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm; + + // ------------------------------------------------------------------ timbri + + private sealed class Voice + { + /// Ampiezza della n-esima armonica in Harmonics[n−1]. + public required float[] Harmonics { get; init; } + public float Attack { get; init; } = 0.005f; + /// Decadimento verso il sostegno (s). + public float Decay { get; init; } = 0.3f; + public float Sustain { get; init; } + public float Release { get; init; } = 0.1f; + /// Copie leggermente scordate (coro). + public float[] Detune { get; init; } = [0]; + public float TremoloHz { get; init; } + public float TremoloDepth { get; init; } + public float VibratoDepth { get; init; } + + // tabelle per numero di armoniche tenute (una per registro, costruite al primo uso) + private readonly Dictionary _tables = []; + + /// + /// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto + /// della frequenza di campionamento: quelle oltre Nyquist + /// tornerebbero indietro come toni stonati. + /// + public float[] TableFor(float frequency) + { + int n = Math.Clamp((int)(MaxHarmonicShare * Synth.Rate / frequency), 1, Harmonics.Length); + if (!_tables.TryGetValue(n, out var table)) + { + table = Table(Harmonics, n); + _tables[n] = table; + } + return table; + } + } + + /// Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro). + private const float MaxHarmonicShare = 0.45f; + + private const int TableSize = 2048; + + /// Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]). + private static float[] Table(float[] harmonics, int count) + { + var t = new float[TableSize]; + for (int i = 0; i < TableSize; i++) + { + float x = MathF.PI * 2 * i / TableSize; + float v = 0; + for (int h = 0; h < count; h++) v += harmonics[h] * MathF.Sin(x * (h + 1)); + t[i] = v; + } + Synth.Normalize(t, 1); + return t; + } + + private static float[] SawHarmonics(int n) + { + var h = new float[n]; + for (int i = 0; i < n; i++) h[i] = 1f / (i + 1); + return h; + } + + private static float[] PulseHarmonics(int n, float duty) + { + var h = new float[n]; + for (int i = 0; i < n; i++) h[i] = MathF.Abs(MathF.Sin(MathF.PI * (i + 1) * duty)) / (i + 1); + return h; + } + + private static Voice VoiceFor(Timbre timbre) => timbre switch + { + Timbre.MusicBox => new Voice { Harmonics = [1, 0.1f, 0.35f, 0, 0.12f], Attack = 0.002f, Decay = 0.7f, Sustain = 0, Release = 0.6f }, + Timbre.Accordion => new Voice { Harmonics = [1, 0.5f, 0.6f, 0.3f, 0.25f, 0.15f], Attack = 0.03f, Decay = 0.2f, Sustain = 0.8f, Release = 0.08f, Detune = [0, 0.004f], TremoloHz = 5, TremoloDepth = 0.12f }, + Timbre.Organ => new Voice { Harmonics = [1, 0.8f, 0.6f, 0.4f, 0, 0.3f, 0, 0.2f], Attack = 0.01f, Decay = 0.1f, Sustain = 0.9f, Release = 0.06f, TremoloHz = 6, TremoloDepth = 0.1f }, + Timbre.Vibraphone => new Voice { Harmonics = [1, 0, 0, 0.25f], Attack = 0.003f, Decay = 1.1f, Sustain = 0, Release = 0.8f, TremoloHz = 5, TremoloDepth = 0.3f }, + Timbre.Strings => new Voice { Harmonics = SawHarmonics(8), Attack = 0.3f, Decay = 0.5f, Sustain = 0.85f, Release = 0.35f, Detune = [-0.003f, 0, 0.003f], VibratoDepth = 0.003f }, + Timbre.Pulse => new Voice { Harmonics = PulseHarmonics(9, 0.25f), Attack = 0.004f, Decay = 0.22f, Sustain = 0, Release = 0.15f }, + Timbre.Saw => new Voice { Harmonics = SawHarmonics(10), Attack = 0.08f, Decay = 0.4f, Sustain = 0.7f, Release = 0.25f, Detune = [-0.005f, 0.005f], VibratoDepth = 0.002f }, + Timbre.PluckBass => new Voice { Harmonics = [1, 0.5f, 0.25f, 0.1f], Attack = 0.005f, Decay = 0.35f, Sustain = 0.15f, Release = 0.08f }, + _ => new Voice { Harmonics = [1, 0.3f, 0.1f], Attack = 0.01f, Decay = 0.4f, Sustain = 0.6f, Release = 0.1f }, + }; + + private static float Frequency(float midi) => 440f * MathF.Pow(2, (midi - 69) / 12f); + + /// Suona una nota nell'anello (con la coda che rientra dall'inizio). + private static void Note(float[] loop, Voice v, float startS, float durS, float midi, float gain) + { + int rate = Synth.Rate; + float f = Frequency(midi); + var table = v.TableFor(f); + int start = (int)(startS * rate); + float total = durS + v.Release; + int samples = Math.Min(loop.Length, (int)(total * rate)); + foreach (float detune in v.Detune) + { + float inc = f * (1 + detune) * TableSize / rate; + float phase = (detune + 0.5f) * 97 % TableSize; + float g = gain / v.Detune.Length; + for (int i = 0; i < samples; i++) + { + float t = i / (float)rate; + float env = t < v.Attack ? t / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(t - v.Attack) / v.Decay); + if (t > durS) + { + // rilascio dal livello raggiunto alla fine della nota + float atEnd = durS < v.Attack ? durS / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(durS - v.Attack) / v.Decay); + env = atEnd * MathF.Max(0, 1 - (t - durS) / v.Release); + } + if (v.TremoloDepth > 0) env *= 1 - v.TremoloDepth * (0.5f + 0.5f * MathF.Sin(MathF.PI * 2 * v.TremoloHz * t)); + float step = v.VibratoDepth > 0 ? inc * (1 + v.VibratoDepth * MathF.Sin(MathF.PI * 2 * 5.5f * t)) : inc; + phase += step; + if (phase >= TableSize) phase -= TableSize; + int i0 = (int)phase; + float frac = phase - i0; + float s = table[i0] + (table[(i0 + 1) & (TableSize - 1)] - table[i0]) * frac; + loop[(start + i) % loop.Length] += s * env * g; + } + } + } + + /// Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava). + private static int Degree(Style s, int degree) + { + int n = s.Scale.Length; + int octave = (int)Math.Floor(degree / (double)n); + int d = degree - octave * n; + return s.RootMidi + s.Scale[d] + 12 * octave; + } + + /// Compone e sintetizza il tema dell'era: campioni mono in [−1, 1]. + public static float[] Compose(int eraIndex, string eraId) + { + var style = StyleFor(eraIndex); + var rng = new SynthRng(Seed(eraIndex, eraId)); + float beat = 60f / style.Bpm; + float bar = beat * style.BeatsPerBar; + var loop = new float[(int)(LengthSeconds(style) * Synth.Rate)]; + var progression = Progressions[rng.Next(Progressions.Length)]; + var pad = VoiceFor(style.Pad); + var arp = VoiceFor(style.Arp); + var lead = VoiceFor(style.Lead); + var bass = VoiceFor(style.Bass); + bool arpDown = rng.Next(2) == 0; + + // motivo di quattro battute: un ritmo per battuta (in ottavi) e gradi vicini all'accordo + int eighths = style.BeatsPerBar * 2; + var motif = new List<(int Bar, int Eighth, int Length, int Degree)>(); + int current = 7 + progression[0]; + for (int b = 0; b < 4; b++) + { + int chord = progression[b]; + int e = 0; + while (e < eighths) + { + int len = rng.Next(4) switch { 0 => 1, 1 or 2 => 2, _ => 3 }; + len = Math.Min(len, eighths - e); + if (rng.Next(5) == 0 && e > 0) + { + e += len; // pausa + continue; + } + bool strong = e % (style.BeatsPerBar == 3 ? 6 : 4) == 0; + if (strong) + { + // sui tempi forti una nota dell'accordo vicina alla precedente + int best = current, bestD = int.MaxValue; + for (int k = -1; k <= 2; k++) + { + foreach (int ct in new[] { 0, 2, 4 }) + { + int cand = chord + ct + 7 * k; + int dist = Math.Abs(cand - current); + if (cand >= 4 && cand <= 13 && dist < bestD) + { + bestD = dist; + best = cand; + } + } + } + current = best; + } + else current = Math.Clamp(current + rng.Next(5) - 2, 4, 13); + motif.Add((b, e, len, current)); + e += len; + } + } + // l'ultima nota del motivo torna sulla tonica + if (motif.Count > 0) motif[^1] = motif[^1] with { Degree = 7 }; + + for (int barIndex = 0; barIndex < Bars; barIndex++) + { + int chord = progression[barIndex % 4]; + float t0 = barIndex * bar; + int[] tones = [Degree(style, chord), Degree(style, chord + 2), Degree(style, chord + 4)]; + + // accompagnamento + if (style.Comping == Comping.Waltz) + { + for (int k = 1; k < style.BeatsPerBar; k++) + foreach (int m in tones) Note(loop, pad, t0 + k * beat, beat * 0.55f, m, 0.11f); + } + else + { + foreach (int m in tones) Note(loop, pad, t0, bar * 0.95f, m, 0.12f); + } + + // basso: fondamentale (e quinta) o basso che cammina sulle note dell'accordo + int root = Degree(style, chord) - 24; + if (style.WalkingBass) + { + int next = Degree(style, progression[(barIndex + 1) % 4]) - 24; + int[] walk = [root, root + (tones[1] - tones[0]), root + 7, next + (next > root ? -1 : 1)]; + for (int k = 0; k < style.BeatsPerBar; k++) Note(loop, bass, t0 + k * beat, beat * 0.9f, walk[k % walk.Length], 0.32f); + } + else if (style.Comping == Comping.Waltz) Note(loop, bass, t0, beat * 0.9f, root, 0.34f); + else + { + Note(loop, bass, t0, beat * 1.8f, root, 0.32f); + Note(loop, bass, t0 + 2 * beat, beat * 1.8f, root + 7, 0.26f); + } + + // arpeggio (in introduzione e coda più presente) + if (style.ArpPerBeat > 0) + { + int steps = style.BeatsPerBar * style.ArpPerBeat; + float step = beat / style.ArpPerBeat; + float gain = barIndex is < 4 or >= 12 ? 0.13f : 0.08f; + for (int k = 0; k < steps; k++) + { + int idx = arpDown ? 3 - k % 4 : k % 4; + int m = idx < 3 ? tones[idx] + 12 : tones[0] + 24; + float swing = style.Swing > 0 && k % 2 == 1 ? style.Swing * step : 0; + Note(loop, arp, t0 + k * step + swing, step * 0.8f, m, gain); + } + } + + // melodia nelle battute 4–11 (la seconda volta un'ottava sopra le ultime due battute) + if (barIndex is >= 4 and < 12) + { + int motifBar = barIndex % 4; + bool variation = barIndex >= 8; + foreach (var n in motif) + { + if (n.Bar != motifBar) continue; + float eighth = beat / 2; + float swing = style.Swing > 0 && n.Eighth % 2 == 1 ? style.Swing * eighth : 0; + int midi = Degree(style, n.Degree) + (variation && motifBar >= 2 ? 12 : 0); + Note(loop, lead, t0 + n.Eighth * eighth + swing, n.Length * eighth * 0.92f, midi, 0.2f); + } + } + } + + // un po' di spazio: due echi smorzati sull'anello, poi limitazione morbida + Echo(loop, 0.27f, 0.22f); + Echo(loop, 0.41f, 0.15f); + Synth.Normalize(loop, 1); + for (int i = 0; i < loop.Length; i++) loop[i] = MathF.Tanh(loop[i] * 1.2f) * 0.7f; + return loop; + } + + /// Eco con retroazione su un anello (due giri per la continuità all'inizio). + private static void Echo(float[] loop, float delayS, float feedback) + { + int d = Math.Max(1, (int)(delayS * Synth.Rate)); + var lp = Biquad.LowPass(2500, 0.7f, Synth.Rate); + var wet = new float[loop.Length]; + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < loop.Length; i++) + { + int j = (i - d + loop.Length) % loop.Length; + wet[i] = lp.Process(loop[j] + wet[j] * feedback) * feedback; + } + } + for (int i = 0; i < loop.Length; i++) loop[i] += wet[i]; + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs b/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs new file mode 100644 index 0000000..bd4422d --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/SpeakerButton.cs @@ -0,0 +1,49 @@ +using Godot; +using RailEnterprise.Client.App; +using static RailEnterprise.Client.App.Localization; + +namespace RailEnterprise.Client.Audio; + +/// Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo. +public partial class SpeakerButton : Button +{ + public SpeakerButton() + { + Flat = true; + CustomMinimumSize = new Vector2(40, 40); + TooltipText = T("Audio (M: muto)"); + Pressed += () => AudioManager.Instance?.ShowSettings(); + MouseEntered += QueueRedraw; + MouseExited += QueueRedraw; + } + + public override void _EnterTree() + { + if (AudioManager.Instance is { } audio) audio.SettingsChanged += QueueRedraw; + } + + public override void _ExitTree() + { + if (AudioManager.Instance is { } audio) audio.SettingsChanged -= QueueRedraw; + } + + public override void _Draw() + { + bool muted = AudioManager.Instance?.Settings.Muted ?? false; + var col = IsHovered() ? Palette.AmberLight : muted ? Palette.TextSecondary : Palette.Text; + var c = Size / 2; + const float w = 2f; + // cassa e cono + DrawColoredPolygon([c + new Vector2(-10, -4), c + new Vector2(-5, -4), c + new Vector2(1, -10), c + new Vector2(1, 10), c + new Vector2(-5, 4), c + new Vector2(-10, 4)], col); + if (muted) + { + DrawLine(c + new Vector2(5, -5), c + new Vector2(13, 5), Palette.Danger, w); + DrawLine(c + new Vector2(13, -5), c + new Vector2(5, 5), Palette.Danger, w); + } + else + { + DrawArc(c + new Vector2(1, 0), 6, -0.9f, 0.9f, 10, col, w); + DrawArc(c + new Vector2(1, 0), 11, -0.9f, 0.9f, 14, col, w); + } + } +} diff --git a/client/RailEnterprise.Client/scripts/Audio/Synth.cs b/client/RailEnterprise.Client/scripts/Audio/Synth.cs new file mode 100644 index 0000000..4133028 --- /dev/null +++ b/client/RailEnterprise.Client/scripts/Audio/Synth.cs @@ -0,0 +1,554 @@ +namespace RailEnterprise.Client.Audio; + +/// +/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il Rng della +/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client. +/// +public struct SynthRng +{ + private ulong _s; + + public SynthRng(ulong seed) => _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed; + + public ulong NextU64() + { + _s ^= _s >> 12; + _s ^= _s << 25; + _s ^= _s >> 27; + return _s * 2685821657736338717UL; + } + + /// Numero in [0, 1). + public float Next01() => (NextU64() >> 40) * (1f / (1 << 24)); + + /// Numero in [−1, 1). + public float NextSigned() => Next01() * 2f - 1f; + + /// Intero in [0, n). + public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n); + + /// Numero in [a, b). + public float Range(float a, float b) => a + (b - a) * Next01(); + + /// FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era). + public static ulong Hash(string text) + { + ulong h = 14695981039346656037UL; + foreach (char c in text) + { + h ^= c; + h *= 1099511628211UL; + } + return h; + } +} + +/// Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario. +public struct Biquad +{ + private float _b0, _b1, _b2, _a1, _a2, _z1, _z2; + + private static Biquad Make(float b0, float b1, float b2, float a0, float a1, float a2) => + new() { _b0 = b0 / a0, _b1 = b1 / a0, _b2 = b2 / a0, _a1 = a1 / a0, _a2 = a2 / a0 }; + + private static (float Cos, float Alpha) W(float freq, float q, int rate) + { + float w0 = 2 * MathF.PI * Math.Clamp(freq, 1, rate * 0.45f) / rate; + return (MathF.Cos(w0), MathF.Sin(w0) / (2 * q)); + } + + public static Biquad LowPass(float freq, float q, int rate) + { + var (c, a) = W(freq, q, rate); + return Make((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + a, -2 * c, 1 - a); + } + + public static Biquad HighPass(float freq, float q, int rate) + { + var (c, a) = W(freq, q, rate); + return Make((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + a, -2 * c, 1 - a); + } + + public static Biquad BandPass(float freq, float q, int rate) + { + var (c, a) = W(freq, q, rate); + return Make(a, 0, -a, 1 + a, -2 * c, 1 - a); + } + + /// Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile). + public void Retune(Biquad coefficients) + { + _b0 = coefficients._b0; + _b1 = coefficients._b1; + _b2 = coefficients._b2; + _a1 = coefficients._a1; + _a2 = coefficients._a2; + } + + public float Process(float x) + { + float y = _b0 * x + _z1; + _z1 = _b1 * x - _a1 * y + _z2; + _z2 = _b2 * x - _a2 * y; + return y; + } +} + +/// +/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione +/// restituisce campioni mono in virgola mobile a Hz, da convertire in PCM a +/// 16 bit con . Gli anelli («Loop») si ripetono senza scatti: i +/// filtri girano due volte sullo stesso rumore (la seconda passata parte dallo stato della fine), +/// le modulazioni hanno un numero intero di periodi nell'anello e le code degli eventi brevi +/// rientrano dall'inizio. Semi fissi: stesso suono a ogni avvio. +/// +public static class Synth +{ + /// Frequenza di campionamento di tutti i suoni (Hz). + public const int Rate = 22050; + + private const float Tau = MathF.PI * 2; + + public static float[] Buffer(float seconds) => new float[Math.Max(1, (int)(seconds * Rate))]; + + /// Inviluppo attacco lineare e decadimento esponenziale. + public static float Env(float t, float attack, float decay) => + t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay); + + /// Porta il picco al valore indicato. + public static void Normalize(float[] buffer, float peak) + { + float max = 0; + foreach (float s in buffer) max = Math.Max(max, Math.Abs(s)); + if (max < 1e-6f) return; + float k = peak / max; + for (int i = 0; i < buffer.Length; i++) buffer[i] *= k; + } + + /// Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine). + public static void FadeOut(float[] buffer, float seconds = 0.01f) + { + int n = Math.Min(buffer.Length, (int)(seconds * Rate)); + for (int i = 0; i < n; i++) buffer[buffer.Length - 1 - i] *= i / (float)n; + } + + /// Rumore bianco ripetibile. + public static float[] Noise(int length, ulong seed) + { + var rng = new SynthRng(seed); + var n = new float[length]; + for (int i = 0; i < length; i++) n[i] = rng.NextSigned(); + return n; + } + + /// Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima. + public static float[] LoopFilter(float[] input, Biquad filter) + { + var output = new float[input.Length]; + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < input.Length; i++) output[i] = filter.Process(input[i]); + } + return output; + } + + /// Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate. + public static float[] BrownLoop(int length, ulong seed, float leak) + { + var white = Noise(length, seed); + var brown = new float[length]; + float acc = 0; + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < length; i++) + { + acc = acc * leak + white[i] * (1 - leak) * 10; + brown[i] = acc; + } + } + return brown; + } + + /// Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio. + public static void MixWrapped(float[] loop, float[] sound, int at, float gain) + { + for (int i = 0; i < sound.Length; i++) loop[(at + i) % loop.Length] += sound[i] * gain; + } + + // ------------------------------------------------------------------ interfaccia + + /// Clic dell'interfaccia: un colpetto secco e brillante. + public static float[] Click() + { + var b = Buffer(0.035f); + var noise = Noise(b.Length, 11); + var hp = Biquad.HighPass(2500, 0.7f, Rate); + for (int i = 0; i < b.Length; i++) + { + float t = i / (float)Rate; + b[i] = MathF.Sin(Tau * 1800 * t) * MathF.Exp(-t / 0.006f) * 0.6f + hp.Process(noise[i]) * MathF.Exp(-t / 0.003f) * 0.5f; + } + Normalize(b, 0.5f); + FadeOut(b, 0.005f); + return b; + } + + /// Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale. + private static void Tone(float[] b, float start, float freq, float decay, float gain, float[] harmonics) + { + int s0 = (int)(start * Rate); + for (int i = s0; i < b.Length; i++) + { + float t = (i - s0) / (float)Rate; + float env = Env(t, 0.005f, decay); + if (env < 1e-4f && t > 0.01f) break; + float v = 0; + for (int h = 0; h < harmonics.Length; h++) + { + float f = freq * (h + 1); + if (harmonics[h] != 0 && f < Rate * 0.45f) v += harmonics[h] * MathF.Sin(Tau * f * t); + } + b[i] += v * env * gain; + } + } + + /// Esito positivo di un comando: due note ascendenti (la, mi). + public static float[] Confirm() + { + var b = Buffer(0.32f); + float[] h = [1, 0.3f]; + Tone(b, 0, 880, 0.09f, 1, h); + Tone(b, 0.07f, 1318.5f, 0.11f, 0.9f, h); + Normalize(b, 0.42f); + FadeOut(b); + return b; + } + + /// Comando rifiutato: due note scure discendenti. + public static float[] Error() + { + var b = Buffer(0.38f); + float[] h = [1, 0, 0.33f, 0, 0.2f]; + Tone(b, 0, 330, 0.12f, 1, h); + Tone(b, 0.1f, 247, 0.14f, 1, h); + var lp = Biquad.LowPass(1800, 0.7f, Rate); + for (int i = 0; i < b.Length; i++) b[i] = lp.Process(b[i]); + Normalize(b, 0.45f); + FadeOut(b); + return b; + } + + /// Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade). + private static void Bell(float[] b, float start, float freq, float gain, float decay = 0.6f) + { + int s0 = (int)(start * Rate); + for (int i = s0; i < b.Length; i++) + { + float t = (i - s0) / (float)Rate; + float index = 2.5f * MathF.Exp(-t / 0.3f); + b[i] += MathF.Sin(Tau * freq * t + index * MathF.Sin(Tau * freq * 1.4f * t)) * Env(t, 0.003f, decay) * gain; + } + } + + /// Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica. + public static float[] Notify(int level) + { + float[] b; + switch (level) + { + case <= 0: + b = Buffer(1.0f); + Bell(b, 0, 1046.5f, 1); + Bell(b, 0.12f, 1568f, 0.6f); + break; + case 1: + b = Buffer(1.2f); + Bell(b, 0, 784f, 1, 0.7f); + Bell(b, 0.18f, 622.3f, 1, 0.7f); + break; + default: + // tre impulsi dissonanti: si distinguono anche sopra la musica + b = Buffer(1.0f); + float[] h = [1, 0, 0.33f, 0, 0.2f]; + for (int k = 0; k < 3; k++) + { + Tone(b, k * 0.22f, 523.3f, 0.09f, 0.8f, h); + Tone(b, k * 0.22f, 554.4f, 0.09f, 0.6f, h); + } + break; + } + Normalize(b, 0.55f); + FadeOut(b); + return b; + } + + /// Cantiere completato: due colpi metallici e un arpeggio maggiore. + public static float[] BuildComplete() + { + var b = Buffer(1.5f); + var noise = Noise(b.Length, 23); + foreach (var (at, gain) in new[] { (0f, 1f), (0.16f, 0.7f) }) + { + int s0 = (int)(at * Rate); + var bp = Biquad.BandPass(2500, 4, Rate); + for (int i = s0; i < b.Length; i++) + { + float t = (i - s0) / (float)Rate; + float metal = MathF.Sin(Tau * 420 * t + 3 * MathF.Exp(-t / 0.08f) * MathF.Sin(Tau * 420 * 2.76f * t)); + b[i] += (bp.Process(noise[i]) * 2 * Env(t, 0.001f, 0.04f) + metal * Env(t, 0.002f, 0.25f)) * gain * 0.6f; + } + } + float[] pluck = [1, 0.4f, 0.15f]; + float[] notes = [523.3f, 659.3f, 784f, 1046.5f]; + for (int k = 0; k < notes.Length; k++) Tone(b, 0.32f + k * 0.08f, notes[k], k == notes.Length - 1 ? 0.35f : 0.15f, 0.7f, pluck); + Normalize(b, 0.55f); + FadeOut(b, 0.05f); + return b; + } + + // ------------------------------------------------------------------ treni + + /// Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio. + public static float[] SteamWhistle() + { + var b = Buffer(1.35f); + var noise = Noise(b.Length, 31); + var bp = Biquad.BandPass(1500, 1.2f, Rate); + float[] freqs = [520, 650, 780]; + float[] phase = new float[freqs.Length]; + for (int i = 0; i < b.Length; i++) + { + float t = i / (float)Rate; + float amp = t < 0.06f ? t / 0.06f : t < 1.05f ? 1 : MathF.Max(0, 1 - (t - 1.05f) / 0.3f); + float bend = 0.94f + 0.06f * MathF.Min(1, t / 0.08f) - (t > 1.0f ? 0.03f * (t - 1.0f) : 0); + float vib = 1 + 0.004f * MathF.Sin(Tau * 5.5f * t); + float v = 0; + for (int k = 0; k < freqs.Length; k++) + { + phase[k] += Tau * freqs[k] * bend * vib / Rate; + v += MathF.Sin(phase[k]) / (k + 1.5f); + } + b[i] = (v + bp.Process(noise[i]) * 0.25f) * amp; + } + Normalize(b, 0.6f); + FadeOut(b); + return b; + } + + /// Tromba bitonale delle locomotive diesel ed elettriche. + public static float[] Horn() + { + var b = Buffer(0.95f); + float[] freqs = [311.1f, 370f]; + var lp = Biquad.LowPass(2500, 0.7f, Rate); + for (int i = 0; i < b.Length; i++) + { + float t = i / (float)Rate; + float amp = t < 0.03f ? t / 0.03f : t < 0.78f ? 1 : MathF.Max(0, 1 - (t - 0.78f) / 0.15f); + float v = 0; + foreach (float f in freqs) + { + for (int h = 1; h <= 6; h++) v += MathF.Sin(Tau * f * h * t) / h; + } + b[i] = lp.Process(v) * amp; + } + Normalize(b, 0.55f); + FadeOut(b); + return b; + } + + /// Sbuffo del vapore: rumore filtrato a banda con un tonfo grave. + public static float[] Chuff() + { + var b = Buffer(0.17f); + var noise = Noise(b.Length, 41); + var bp = Biquad.BandPass(900, 0.8f, Rate); + var lp = Biquad.LowPass(2500, 0.7f, Rate); + for (int i = 0; i < b.Length; i++) + { + float t = i / (float)Rate; + b[i] = lp.Process(bp.Process(noise[i])) * Env(t, 0.004f, 0.05f) + MathF.Sin(Tau * 70 * t) * Env(t, 0.002f, 0.04f) * 0.5f; + } + Normalize(b, 0.6f); + FadeOut(b, 0.02f); + return b; + } + + /// Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti. + public static float[] RailRumbleLoop() + { + int n = (int)(1.6f * Rate); + var loop = LoopFilter(BrownLoop(n, 53, 0.995f), Biquad.LowPass(300, 0.7f, Rate)); + Normalize(loop, 0.5f); + var clack = Buffer(0.08f); + var cn = Noise(clack.Length, 59); + var bp = Biquad.BandPass(1800, 2, Rate); + for (int i = 0; i < clack.Length; i++) + { + float t = i / (float)Rate; + clack[i] = bp.Process(cn[i]) * 1.5f * Env(t, 0.001f, 0.012f) + MathF.Sin(Tau * 90 * t) * Env(t, 0.002f, 0.03f) * 0.6f; + } + MixWrapped(loop, clack, (int)(0.20f * Rate), 0.8f); + MixWrapped(loop, clack, (int)(0.32f * Rate), 0.7f); + MixWrapped(loop, clack, (int)(1.00f * Rate), 0.75f); + MixWrapped(loop, clack, (int)(1.12f * Rate), 0.65f); + Normalize(loop, 0.6f); + return loop; + } + + /// Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz. + public static float[] DieselDroneLoop() + { + int n = Rate; + var b = new float[n]; + var noise = LoopFilter(Noise(n, 61), Biquad.LowPass(900, 0.7f, Rate)); + for (int i = 0; i < n; i++) + { + float t = i / (float)Rate; + float v = 0; + for (int h = 1; h <= 10; h++) v += MathF.Sin(Tau * 48 * h * t) / h; + float firing = 0.7f + 0.3f * MathF.Sin(Tau * 8 * t); + b[i] = v * firing * 0.5f + noise[i] * 0.4f; + } + Normalize(b, 0.6f); + return b; + } + + /// Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori. + public static float[] ElectricHumLoop() + { + int n = Rate; + var b = new float[n]; + var hiss = LoopFilter(Noise(n, 67), Biquad.LowPass(3000, 0.7f, Rate)); + for (int i = 0; i < n; i++) + { + float t = i / (float)Rate; + b[i] = 0.4f * MathF.Sin(Tau * 100 * t) + 0.2f * MathF.Sin(Tau * 200 * t) + 0.25f * MathF.Sin(Tau * 300 * t) + + 0.06f * MathF.Sin(Tau * 1150 * t) * (0.6f + 0.4f * MathF.Sin(Tau * t)) + hiss[i] * 0.12f; + } + Normalize(b, 0.5f); + return b; + } + + // ------------------------------------------------------------------ ambiente + + /// Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche. + public static float[] WindLoop() + { + const float seconds = 8; + int n = (int)(seconds * Rate); + var white = Noise(n, 71); + var b = new float[n]; + var f = Biquad.LowPass(400, 0.9f, Rate); + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < n; i++) + { + float t = i / (float)Rate; + float g = 0.55f + 0.25f * MathF.Sin(Tau * t / seconds) + 0.2f * MathF.Sin(Tau * 3 * t / seconds + 1.3f); + if ((i & 127) == 0) f.Retune(Biquad.LowPass(250 + 550 * g, 0.9f, Rate)); + b[i] = f.Process(white[i]) * g; + } + } + Normalize(b, 0.5f); + return b; + } + + /// Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle. + public static float[] RiverLoop() + { + const float seconds = 6; + int n = (int)(seconds * Rate); + var main = LoopFilter(Noise(n, 73), Biquad.BandPass(1200, 0.7f, Rate)); + var mod = LoopFilter(Noise(n, 79), Biquad.LowPass(6, 0.7f, Rate)); + Normalize(mod, 1); + var b = new float[n]; + for (int i = 0; i < n; i++) b[i] = main[i] * (0.6f + 0.4f * mod[i]); + Normalize(b, 1); + var rng = new SynthRng(83); + var bubble = Buffer(0.05f); + for (int k = 0; k < 60; k++) + { + float f0 = rng.Range(400, 1000); + for (int i = 0; i < bubble.Length; i++) + { + float t = i / (float)Rate; + bubble[i] = MathF.Sin(Tau * f0 * (1 + 4 * t) * t) * Env(t, 0.002f, 0.012f); + } + MixWrapped(b, bubble, rng.Next(n), rng.Range(0.1f, 0.3f)); + } + Normalize(b, 0.45f); + return b; + } + + /// Mare in anello (10 s): due onde con risacca e schiuma. + public static float[] SeaLoop() + { + const float seconds = 10; + int n = (int)(seconds * Rate); + var low = LoopFilter(Noise(n, 89), Biquad.LowPass(700, 0.7f, Rate)); + var foam = LoopFilter(Noise(n, 97), Biquad.HighPass(3000, 0.7f, Rate)); + var b = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)Rate; + float s = 0.5f + 0.5f * MathF.Sin(Tau * 2 * t / seconds - MathF.PI / 2); + float swell = 0.35f + 0.65f * s * s; + b[i] = low[i] * swell + foam[i] * swell * swell * 0.3f; + } + Normalize(b, 0.5f); + return b; + } + + /// Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte. + public static float[] CityLoop() + { + const float seconds = 8; + int n = (int)(seconds * Rate); + var rumble = LoopFilter(BrownLoop(n, 101, 0.996f), Biquad.LowPass(200, 0.7f, Rate)); + Normalize(rumble, 1); + var murmur = LoopFilter(Noise(n, 103), Biquad.BandPass(500, 1, Rate)); + Normalize(murmur, 1); + var mod = LoopFilter(Noise(n, 107), Biquad.LowPass(3, 0.7f, Rate)); + Normalize(mod, 1); + var b = new float[n]; + for (int i = 0; i < n; i++) b[i] = rumble[i] * 0.5f + murmur[i] * (0.2f + 0.15f * mod[i]); + var rng = new SynthRng(109); + var knock = Buffer(0.06f); + for (int k = 0; k < 24; k++) + { + var kn = Noise(knock.Length, 200 + (ulong)k); + var bp = Biquad.BandPass(rng.Range(1500, 3000), 3, Rate); + float decay = rng.Range(0.01f, 0.03f); + for (int i = 0; i < knock.Length; i++) knock[i] = bp.Process(kn[i]) * 3 * Env(i / (float)Rate, 0.001f, decay); + MixWrapped(b, knock, rng.Next(n), rng.Range(0.2f, 0.5f)); + } + Normalize(b, 0.45f); + return b; + } + + /// Cinguettio (varianti per numero): due–quattro brevi glissati acuti. + public static float[] Bird(int variant) + { + var rng = new SynthRng(300 + (ulong)variant); + int chirps = 2 + rng.Next(3); + float chirp = rng.Range(0.05f, 0.08f); + float gap = rng.Range(0.03f, 0.07f); + var b = Buffer(chirps * (chirp + gap) + 0.02f); + float f0 = rng.Range(2800, 3600), f1 = f0 * rng.Range(1.15f, 1.45f); + if (rng.Next(2) == 0) (f0, f1) = (f1, f0); + for (int k = 0; k < chirps; k++) + { + int s0 = (int)(k * (chirp + gap) * Rate); + float phase = 0; + for (int i = 0; i < (int)(chirp * Rate) && s0 + i < b.Length; i++) + { + float u = i / (chirp * Rate); + phase += Tau * (f0 + (f1 - f0) * u) / Rate; + b[s0 + i] += MathF.Sin(phase) * MathF.Sin(MathF.PI * u); + } + } + Normalize(b, 0.5f); + return b; + } +} diff --git a/client/RailEnterprise.Client/scripts/Hud/TopBar.cs b/client/RailEnterprise.Client/scripts/Hud/TopBar.cs index 3ebf49e..d27c444 100644 --- a/client/RailEnterprise.Client/scripts/Hud/TopBar.cs +++ b/client/RailEnterprise.Client/scripts/Hud/TopBar.cs @@ -7,7 +7,7 @@ using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client.Hud; -/// Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server. +/// Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio. public partial class TopBar : PanelContainer { private GameSession? _session; @@ -90,6 +90,9 @@ public partial class TopBar : PanelContainer var chipCenter = new CenterContainer(); chipCenter.AddChild(chip); row.AddChild(chipCenter); + var audio = new CenterContainer(); + audio.AddChild(new Audio.SpeakerButton()); + row.AddChild(audio); } private static VBoxContainer Stat(string caption, Label value) diff --git a/client/RailEnterprise.Client/scripts/Main.cs b/client/RailEnterprise.Client/scripts/Main.cs index 1528914..d4f2a4d 100644 --- a/client/RailEnterprise.Client/scripts/Main.cs +++ b/client/RailEnterprise.Client/scripts/Main.cs @@ -1,5 +1,6 @@ using Godot; using RailEnterprise.Client.App; +using RailEnterprise.Client.Audio; using RailEnterprise.Client.Net; using RailEnterprise.Client.Screens; using RailEnterprise.Client.Tutorial; @@ -9,17 +10,22 @@ using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client; /// -/// 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. /// public partial class Main : Node { private const string SettingsPath = "user://settings.cfg"; + // cartelle del server locale: la partita del giocatore (la apre la schermata di connessione), la + // partita di prova del tutorial e quella del collaudo (queste due ripartono sempre da una partita nuova) + private const string LocalDataDir = "user://server"; + private const string TutorialDataDir = "user://tutorial-server"; + private const string AutopilotDataDir = "user://autopilot-server"; private GameData? _data; private Node? _screen; private GameSession? _session; private string? _autopilot; - // tutorial della partita che si apre: casella del menu e opzione «Tutorial» (dal primo passo) + // tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo) private bool _tutorialRequested, _tutorialRestart; public override void _Ready() @@ -30,21 +36,27 @@ public partial class Main : Node Localization.Load(locale); GetWindow().Theme = UiTheme.Build(); GetWindow().Title = "Rail Enterprise"; + var args = OS.GetCmdlineUserArgs(); + int i = Array.IndexOf(args, "--autopilot"); + // audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo) + var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless"); + AddChild(audio); try { _data = GodotDataSource.LoadGameData(); + audio.SetEras(_data.Eras.Eras); } catch (Exception e) { GD.PrintErr($"Dati del gioco non validi: {e.Message}"); } - ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : ""); - var args = OS.GetCmdlineUserArgs(); - int i = Array.IndexOf(args, "--autopilot"); if (i >= 0 && _data is not null) + _autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot"); + // nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto + ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null); + if (_autopilot is not null) { // collaudo: mappa piccola e seme fisso per il server locale - _autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot"); System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64"); System.Environment.SetEnvironmentVariable("RE_SEED", "3"); System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0"); @@ -59,35 +71,48 @@ public partial class Main : Node AddChild(screen); } - private void ShowMenu(string status = "") + /// Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi. + /// Avvia subito la strada scelta l'ultima volta (server locale o in rete). + /// Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua). + private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null) { - var menu = new MenuScreen(); - menu.LocalGame += () => + if (_data is null) { - SetTutorial(menu.ShowTutorial, restart: false); - StartLocal(); + // 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; + } + // chi aggiorna con una partita locale già salvata non è alla prima partita: casella spenta + if (!TutorialSettings.Played && HasLocalSaves()) TutorialSettings.Played = true; + var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover); + screen.PlayRequested += session => + { + SetTutorial(screen.ShowTutorial, restart: false); + ShowGame(session, screen.GameScope); }; - menu.ConnectToServer += () => - { - SetTutorial(menu.ShowTutorial, restart: false); - ShowConnect(); - }; - menu.TutorialRequested += () => + screen.TutorialRequested += async () => { + // la partita di prova ha un suo server: quello della sessione di prova della schermata si chiude + var trial = screen.TakeSession(); + if (trial is not null) await trial.DisposeAsync(); SetTutorial(true, restart: true); - StartLocal(); + StartLocal(tutorial: true); }; - menu.LanguageChanged += code => + screen.AudioRequested += () => AudioManager.Instance?.ShowSettings(); + screen.LanguageChanged += code => { var cfg = new ConfigFile(); cfg.Load(SettingsPath); cfg.SetValue("ui", "locale", code); cfg.Save(SettingsPath); TranslationServer.SetLocale(code); - ShowMenu(); + // la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei + ShowMenu(handover: screen.TakeSession()); }; - Swap(menu); - if (status.Length > 0) menu.SetStatus(status); + Swap(screen); + if (status.Length > 0) screen.SetStatus(status, error: true); } private void SetTutorial(bool requested, bool restart) @@ -96,73 +121,72 @@ public partial class Main : Node _tutorialRestart = restart; } - private void ShowConnect() + /// Vero se la partita locale del giocatore ha già dei salvataggi (file .vfsave del server). + private static bool HasLocalSaves() { - var screen = new ConnectScreen(); - screen.Back += () => ShowMenu(); - screen.ConnectRequested += async (uri, token, label) => + try { - 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); + string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves"); + return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any(); + } + catch (IOException) + { + return false; + } } - private async void StartLocal() + /// + /// Server locale da zero e subito in partita, senza la schermata di connessione: il collaudo e la partita + /// di prova del tutorial, ciascuno nella sua cartella; la partita del giocatore non si tocca. + /// + /// pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo + private async void StartLocal(bool tutorial = false) { if (_data is null) return; string? server = LocalServerLauncher.FindServer(); if (server is null) { - ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH.")); + ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false); return; } - if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…")); + if (tutorial && _screen is ConnectScreen connect) connect.SetStatus(T("Avvio della partita di prova del tutorial…")); 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(tutorial ? TutorialDataDir : AutopilotDataDir); + 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; - ShowGame(session); + ShowGame(session, tutorial ? "tutorial" : "autopilot"); } catch (Exception e) { launcher.Dispose(); - ShowMenu($"{T("Partita locale non avviata")}: {e.Message}"); + ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false); } } - private void ShowGame(GameSession session) + /// origine della partita (locale, tutorial, server in rete) per la voce del tutorial + private void ShowGame(GameSession session, string scope) { _session = session; var game = new GameScreen(session); game.Exit += async () => { + // prima si chiude la partita (e il server locale), poi la schermata di connessione ne + // avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono var s = _session; _session = null; - ShowMenu(); if (s is not null) await s.DisposeAsync(); + ShowMenu(); }; Swap(game); - // il pilota automatico non mostra il tutorial: le sue schermate restano quelle di sempre + // il pilota automatico non mostra il tutorial: le sue schermate di partita restano quelle di sempre if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot)); else { - game.AddChild(new TutorialController(game, _tutorialRequested, _tutorialRestart)); + game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart)); TutorialSettings.Played = true; _tutorialRestart = false; } @@ -170,10 +194,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)); } } diff --git a/client/RailEnterprise.Client/scripts/Net/GameSession.cs b/client/RailEnterprise.Client/scripts/Net/GameSession.cs index f1c01be..ac928d9 100644 --- a/client/RailEnterprise.Client/scripts/Net/GameSession.cs +++ b/client/RailEnterprise.Client/scripts/Net/GameSession.cs @@ -134,9 +134,13 @@ public sealed class GameSession : IAsyncDisposable /// Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma). public byte? RequestedSpeed { get; private set; } + /// Velocità chieste finora da questo client (il tutorial non conta i cambi fatti da altri giocatori). + public int SpeedRequests { get; private set; } + public void SetSpeed(byte speed) { RequestedSpeed = speed; + SpeedRequests++; Send(new SetSpeed { Speed = speed }); } diff --git a/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs b/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs index e0b4914..fdbf420 100644 --- a/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs +++ b/client/RailEnterprise.Client/scripts/Panels/IndustryPanel.cs @@ -11,21 +11,39 @@ using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client.Panels; /// -/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario -/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di -/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato», -/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista». -/// La scheda del proprietario arriva su richiesta dal server (IndustryCard). +/// 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'è. /// 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 _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); + /// Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta). + private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary); + private Button? _overhaul, _upgrade; private readonly List