20 Commits
Author SHA1 Message Date
Alby96 357a743e91 Merge PR #35: F6 versione 0.6.0
CI / Build e test (push) Successful in 3m21s
Release / Build, test e pubblicazione (push) Successful in 14m57s
CI / Immagine Docker (push) Successful in 13s
Release / Immagine del server (push) Successful in 35s
2026-11-07 17:35:51 +01:00
Alby96andClaude Opus 5.5 5abf3645bb F6: versione 0.6.0 con mercato globale, compravendita in proprio ed eventi
CI / Build e test (pull_request) Successful in 1m21s
CI / Immagine Docker (pull_request) Successful in 27s
Prima versione con i pezzi della F6 già in main: il rilascio esporta il gioco
per verificare con il pilota automatico i nuovi pannelli.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 17:29:16 +01:00
Alby96 dafe9f6d11 Merge PR #34: F6 eventi del mondo con effetti temporanei e notizie
CI / Build e test (push) Successful in 3m40s
CI / Immagine Docker (push) Successful in 10s
2026-11-07 17:28:48 +01:00
Alby96andClaude Opus 5.5 5a4a156d52 F6: eventi del mondo, correzioni della revisione
CI / Build e test (pull_request) Successful in 1m23s
CI / Immagine Docker (pull_request) Successful in 30s
Allinea i giorni degli eventi a quelli annunciati, toglie le sovrapposizioni
di zona e impedisce che l'IA trasformi un effetto temporaneo in un
investimento permanente.

- Un evento è in vigore nei giorni [inizio, fine) per tutti: le
  interrogazioni di WorldEventState contano solo gli eventi in vigore nel
  giorno dell'orologio, l'usura conta il maltempo del giorno del traffico.
  Il maltempo non rallenta più i treni il giorno dell'estrazione e agisce
  per intero l'ultimo giorno; l'evento esce dall'elenco il mattino del
  primo giorno libero, con la notizia di fine. {until} è l'ultimo giorno.
- Niente zone sovrapposte tra due maltempi o tra due eventi sulla domanda
  dello stesso bene (né due boom né boom e crollo insieme): nessuna città
  e nessun arco ricevono due volte lo stesso effetto.
- IA: stime dei candidati sulla domanda senza eventi, sui posti scoperti
  senza le assenze di epidemie e scioperi (PresentWithoutEvents) e
  sull'efficienza senza il moltiplicatore di capacità (ADR 0017 §9).
- Client: conto alla rovescia dalla durata a 1 e «da domani» per gli
  eventi estratti oggi; avviso anche nelle città della zona e nel Registro
  officina del deposito in sciopero; dal resoconto il notiziario prende
  solo le notizie di fine, le altre arrivano già come Notification.

ADR 0017, STATE, ARCHITECTURE e PROTOCOL aggiornati; 2 test nuovi e
3 adattati alla nuova finestra.

Refs #33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 17:23:42 +01:00
Alby96andClaude Opus 5.5 1f8da87e51 F6: eventi del mondo con effetti temporanei e notizie
Aggiunge gli eventi della F6: fatti del mondo che cambiano il gioco per
un periodo limitato, leggibili nel notiziario e reversibili.

- Catalogo data/events.json con schema e validazione: incidente e boom
  di un'industria, fiera ed epidemia, boom e crollo della domanda di un
  bene in una zona, maltempo su un'area, sciopero di città o deposito.
- Effetti come moltiplicatori letti da un'unica sorgente
  (World.WorldEvents) dai sistemi esistenti: capacità delle industrie,
  consumi delle città, presenze dei pendolari, velocità dei treni e usura
  del binario. A evento finito il moltiplicatore torna 1.
- EventSystem tra le IA e l'hash, con flusso Rng dedicato «events»,
  bersaglio in ordine di id, frequenza per mappa scalata dalla difficoltà
  (eventFrequencyMultiplier), tetto di 6, niente doppioni, notizie di
  inizio e fine in italiano (EventKind.World).
- Salvataggio corpo versione 5 con gli eventi nell'hash; le versioni 1-4
  si caricano senza eventi e con la frequenza del preset.
- Protocollo: eventi in corso nel DailyDigest e nel MarketReport; client
  con il riquadro «Eventi in corso», avvisi nelle schede e «evento in
  corso» nel Mercato globale.
- Lo scenario Valdoria disattiva gli eventi: con gli eventi attivi la
  flotta F4 senza linea dei ricambi non scendeva più sotto 40, e
  l'accettazione deve misurare la manutenzione, non la fortuna (ADR 0017).
  Accettazione F4 invariata: 35 / 20 guasti senza linea, 75 / 2 con.

Decisioni in docs/adr/0017-eventi-del-mondo.md; 17 test nuovi.

Refs #33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:59:48 +01:00
Alby96 b258e0858a Merge PR #32: F6 compravendita in proprio e spedizione della merce tra stazioni
CI / Build e test (push) Successful in 3m22s
CI / Immagine Docker (push) Successful in 9s
2026-11-07 16:15:07 +01:00
Alby96andClaude Opus 5.5 596ce2c376 F6: compravendita in proprio, correzioni della revisione
CI / Build e test (pull_request) Successful in 1m19s
CI / Immagine Docker (pull_request) Successful in 29s
La revisione ha trovato casi in cui la merce della compagnia, già pagata,
poteva perdersi o restare bloccata, e il magazzino di destinazione
restare prenotato per sempre. Le correzioni:

- Il percorso della merce propria rispetta i flag carico e scarico delle
  fermate: LineGraph.From ha l'opzione stopFlags. ShipGoods rifiuta con
  Blocked la spedizione che esiste solo ignorando i flag. I pacchetti dei
  clienti non cambiano: l'accettazione F4 dà ancora 35/20 e 75/2.
- La scadenza in stazione della merce propria riparte a ogni trasbordo.
- La merce propria in attesa ricalcola ogni giorno il tratto sulle linee
  di quel giorno; se non c'è più un percorso torna nel magazzino.
- La merce propria a bordo scende alla prima fermata quando il suo tratto
  non è più sulla linea del treno. Un treno che lascia la linea
  (riassegnato, al deposito, in riserva, fine copertura) la lascia alla
  stazione dove si trova o alla prossima fermata.
- Una stazione con merce propria in partenza o in arrivo non si demolisce.
- La merce propria, in magazzino e in viaggio, entra nel valore contabile
  al prezzo globale: un acquisto non abbassa più il patrimonio netto
  dell'intero importo.
- Solo l'acquisto richiede lo sblocco del livello: la merce ereditata con
  una fusione si vende e si spedisce, e il riquadro del pannello compare.
- Nel riquadro, la stazione di arrivo predefinita è diversa da quella di
  partenza.

ADR 0016 e STATE aggiornati; sei test nuovi in TradingTests.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:05:29 +01:00
Alby96andClaude Opus 5.5 e157dd77bc F6: compravendita in proprio e spedizione della merce tra stazioni
Dal livello che sblocca il commercio la compagnia può comprare e vendere
merci in proprio. Così può fare arbitraggio tra un produttore con il
magazzino pieno e un consumatore a secco anche dove il vettore non ha
contratti. Le regole sono nell'ADR 0016.

- Ogni stazione della compagnia ha un magazzino: 500 unità e una
  giacenza di 25 centesimi per unità al mese, in balance.json, blocco
  «trading». La merce in magazzino rientra nell'invariante delle merci.
- BuyGoods compra al prezzo locale marginale dell'ADR 0004, unità per
  unità, partendo dal più economico, dai produttori del bacino e dagli
  hub. La merce presa dagli hub conta come importata.
- SellGoods vende ai consumatori del bacino partendo dal prezzo più
  alto, entro lo spazio libero e la cassa di ciascuno. Vende anche agli
  hub, e quella merce conta come esportata.
- Il denaro di entrambi i comandi passa dal registro, sulla voce
  «Commercio».
- ShipGoods (comando 40) spedisce la merce propria come pacchetto senza
  tariffa né consumatore. Il pacchetto entra nel magazzino di
  destinazione, che riserva lo spazio alla partenza. Il percorso dei
  pacchetti già esistenti non cambia: l'accettazione F4 dà ancora
  35/20 guasti senza la linea e 75/2 con la linea.
- Il salvataggio passa al corpo versione 4 (TradingSerializer). I
  salvataggi più vecchi si caricano con i magazzini vuoti, e i magazzini
  entrano nell'hash di stato.
- MarketReport porta i magazzini nel blocco 1. Il Mercato globale ha il
  riquadro «Compravendita in proprio».
- Le IA non commerciano ancora.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:26:20 +01:00
Alby96 3f00acb994 Merge PR #30: F6 mercato globale, storico prezzi a 24 mesi e previsione
CI / Build e test (push) Successful in 3m23s
CI / Immagine Docker (push) Successful in 12s
2026-11-07 14:47:03 +01:00
Alby96andClaude Opus 5.5 b2de314d7c F6: mercato globale, correzioni della revisione
CI / Build e test (pull_request) Successful in 1m31s
CI / Immagine Docker (pull_request) Successful in 29s
- «Dove conviene vendere» dice che il prezzo locale è quello della
  compravendita in proprio: oggi le consegne del vettore si pagano al prezzo
  globale (ADR 0015 §9).
- Gli hub che hanno esaurito la capacità del mese non compaiono tra le
  destinazioni.
- Senza compagnia l'avanzamento verso il commercio mostra comunque i
  requisiti del livello.
- I quattro test lunghi del mercato sono marcati lenti.
- «oggi» va in cima alla riga del grafico, per non coprire le etichette dei
  mesi.
- L'ADR annota la piccola differenza tra offerta e domanda mostrate e quelle
  del passo di mercato.

Refs #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:42:53 +01:00
Alby96andClaude Opus 5.5 2992e7cc36 F6: mercato globale, storico prezzi a 24 mesi e previsione
Prima parte della F6: il pannello «Mercato globale» dell'immagine di
riferimento 06, con i dati calcolati dal server.

- Lo storico dei prezzi globali passa da 360 a 720 giorni. I salvataggi
  con lo storico di un anno si migrano al caricamento allungando la
  finestra (RollingWindow.Extended), senza cambiare formato.
- MarketOutlook (Core) è un'analisi in sola lettura del mondo: storico
  mensile, variazione a 30 giorni, offerta e domanda con la quota
  mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi
  dalla componente mondiale con banda, destinazioni di vendita ordinate
  per prezzo con la linea che le collega, hub, evento in corso e
  avanzamento verso la compravendita in proprio. Parametri nuovi in
  balance.json (market.outlook); interpretazioni nell'ADR 0015.
- Protocollo: DetailKind.Market (7) e MarketReport (129); il server
  risponde su richiesta, il client lo mostra in un pannello a tutto
  schermo e il pilota automatico ne fa la schermata 16_mercato.
- Test: finestra allungata e migrazione, storico mensile, previsione
  deterministica ed entro i limiti, evento, analisi su Valdoria,
  round-trip del messaggio e quadro via WebSocket.

La simulazione non cambia: l'analisi non scrive nel mondo e
l'accettazione F4 dà gli stessi numeri di prima.

Closes #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:25:38 +01:00
Alby96 bfbdb6297e Merge PR #28: traduzioni nel gioco esportato e test del registro degli impieghi, versione 0.5.2
CI / Build e test (push) Successful in 3m25s
Release / Build, test e pubblicazione (push) Successful in 15m26s
CI / Immagine Docker (push) Successful in 10s
Release / Immagine del server (push) Successful in 38s
2026-11-07 13:22:53 +01:00
Alby96andClaude Opus 5.5 6333d1b663 Stato: test instabili descritti uno per riga
CI / Build e test (pull_request) Successful in 1m18s
CI / Immagine Docker (pull_request) Successful in 26s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:17:15 +01:00
Alby96andClaude Opus 5.5 10a508e719 Test: il registro degli impieghi si aspetta dopo la richiesta
CI / Build e test (pull_request) Successful in 1m23s
CI / Immagine Docker (pull_request) Successful in 30s
MaintenanceDetailsOnRequest falliva a volte (#24, sul runner e 2 volte su 4 in
locale con tutta la suite): il server manda il registro anche da solo a inizio
mese, già al giorno 0 prima che l'officina esista, e il test prendeva quello
invece della risposta. Ora aspetta un registro diverso da quello già ricevuto:
6 esecuzioni complete su 6 verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:17:03 +01:00
Alby96andClaude Opus 5.5 83316d4c8d Test: il registro degli impieghi senza officina riporta le righe ricevute
CI / Build e test (pull_request) Successful in 1m22s
CI / Immagine Docker (pull_request) Successful in 29s
MaintenanceDetailsOnRequest fallisce a volte sul runner (#24) e passa in locale:
il messaggio ora dice quali righe sono arrivate e di che giorno, per capire la
causa al prossimo fallimento.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:11:22 +01:00
Alby96andClaude Opus 5.5 8bef6551e4 Rilascio: traduzioni nel gioco esportato, versione 0.5.2
CI / Build e test (pull_request) Failing after 1m2s
CI / Immagine Docker (pull_request) Skipped
Localization legge assets/i18n/strings.csv così com'è, ma Godot lo importava
come traduzione e nel .pck finivano solo i file .translation: il gioco v0.5.1
partiva senza inglese («Traduzioni non trovate»). Il CSV ora usa l'importatore
«keep» e il workflow di rilascio fallisce se le traduzioni importate tornano
nel pacchetto. STATE.md registra il collaudo di v0.5.1 (pilota automatico
completo sul gioco scaricato) e il secondo test instabile (#24).

Closes #27.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:08:32 +01:00
Alby96 9f6747efe9 Merge PR #26: soluzione del client per l'esportazione Godot, versione 0.5.1
CI / Build e test (push) Successful in 4m12s
Release / Build, test e pubblicazione (push) Successful in 18m50s
CI / Immagine Docker (push) Successful in 22s
Release / Immagine del server (push) Successful in 45s
2026-11-07 12:37:31 +01:00
Alby96andClaude Opus 5.5 e57231b15a Rilascio: soluzione del client per l'esportazione Godot, versione 0.5.1
CI / Build e test (pull_request) Successful in 3m12s
CI / Immagine Docker (pull_request) Successful in 37s
Il gioco desktop di v0.5.0 si avviava senza codice C# perché Godot esporta
gli assembly .NET solo se trova la soluzione del client, che non era nel
repository. Aggiunge RailEnterprise.Client.sln con le configurazioni di
esportazione, fa fallire il rilascio se mancano gli assembly, porta la
versione di sviluppo a 0.5.1 e indica nel modello di PR le parole chiave
inglesi che Gitea usa per chiudere le issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 11:52:14 +01:00
Alby96 f377913a62 Merge PR #23: nome «Rail Enterprise», CI e rilasci su Gitea
CI / Build e test (push) Successful in 3m33s
CI / Immagine Docker (push) Successful in 11s
Release / Build, test e pubblicazione (push) Successful in 14m9s
Release / Immagine del server (push) Successful in 44s
2026-11-07 11:26:18 +01:00
Alby96andClaude Opus 5.5 c1a0049bcf Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s
Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 11:14:54 +01:00
327 changed files with 7652 additions and 1174 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
name: Difetto
about: Qualcosa non funziona nel gioco, nel server o negli strumenti
title: "[Difetto] "
labels: ["bug"]
body:
- type: textarea
id: cosa
attributes:
label: Cosa succede
description: Cosa hai visto e cosa ti aspettavi.
validations:
required: true
- type: textarea
id: passi
attributes:
label: Come riprodurlo
description: Passi, seme della mappa, difficoltà, salvataggio o registro dei comandi (--record) se disponibili.
- type: input
id: versione
attributes:
label: Versione
description: Versione del gioco o tag dell'immagine Docker.
- type: dropdown
id: dove
attributes:
label: Dove
options:
- Gioco desktop (partita locale)
- Server Docker
- Strumenti (railenterprise-tools)
- Altro
+17
View File
@@ -0,0 +1,17 @@
name: Funzionalità
about: Un lavoro della roadmap o una nuova idea
title: "[F?] "
labels: ["enhancement"]
body:
- type: textarea
id: obiettivo
attributes:
label: Obiettivo
description: Cosa deve fare e quale sezione di docs/GUIDA.md copre.
validations:
required: true
- type: textarea
id: accettazione
attributes:
label: Criteri di accettazione
description: Test o misure che dicono quando è finito.
+16
View File
@@ -0,0 +1,16 @@
## Cosa cambia e perché
<!-- Una o due frasi. Collega le issue con «Closes #N» (Gitea riconosce solo le parole chiave inglesi). -->
## Fase
<!-- F0…F7 secondo docs/GUIDA.md §16, oppure «infrastruttura» / «documentazione». -->
## Verifica
- [ ] `scripts/build.sh` verde (zero NuGet, warning come errori)
- [ ] `scripts/test.sh` verde (indica eventuali test lunghi saltati)
- [ ] `docs/STATE.md` aggiornato se cambia lo stato della fase
- [ ] ADR in `docs/adr/` per ogni decisione non coperta dalla guida
- [ ] Nessun numero magico nella simulazione (parametri in `data/*.json`), determinismo rispettato
- [ ] Schermate in `docs/screenshots/` se cambia l'interfaccia
+104
View File
@@ -0,0 +1,104 @@
name: CI
# Gitea Actions (ADR 0014). Il runner è act_runner in modalità Docker sul server Linux che ospita Gitea: ogni job
# gira in un container. I job .NET usano l'immagine dell'SDK e fanno il checkout con git, perché le azioni JavaScript
# richiedono Node.js, assente in quell'immagine. Nessuna cache e nessun artefatto: il risultato è il verde o il rosso.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
env:
DOTNET_NOLOGO: "1"
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
BUILD_CPUS: "4"
jobs:
build:
name: Build e test
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:10.0
timeout-minutes: 90
defaults:
run:
shell: bash
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
git log -1 --format='%h %s'
# Core e Protocol compilano anche per net8.0 (client Godot): serve il targeting pack 8.0, che l'SDK 10 scarica
# da solo come pacchetto di riferimento. Nessun PackageReference è ammesso (check-nuget).
- name: Zero pacchetti NuGet
run: scripts/check-nuget.sh
- name: Build Release (warning come errori)
run: dotnet build RailEnterprise.sln -c Release -m:"$BUILD_CPUS" -nologo
- name: Validazione dei dati
run: dotnet run --project src/RailEnterprise.Tools -c Release --no-build -- validate-data --data data
# Sulle PR i test lunghi (accettazioni pluriennali) si saltano; su main gira la suite completa.
- name: Test
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
dotnet run --project tests/RailEnterprise.Tests -c Release --no-build -- --skip-slow
else
dotnet run --project tests/RailEnterprise.Tests -c Release --no-build
fi
# Il server per Windows (quello che il gioco desktop avvia da «server/») si compila anche qui.
- name: Server Windows x64 (compilazione incrociata)
run: dotnet publish src/RailEnterprise.Server -c Release -r win-x64 --self-contained -p:ReServerOnly=true -o out/server-win-x64 -nologo
# Il client Godot compila con il proprio SDK (Godot.NET.Sdk da NuGet, unica eccezione ammessa): basta dotnet.
- name: Client Godot (compilazione C#)
run: dotnet build client/RailEnterprise.Client/RailEnterprise.Client.csproj -c Release -nologo
docker:
name: Immagine Docker
needs: build
runs-on: ubuntu-latest
timeout-minutes: 45
env:
NAME: re-ci-${{ github.run_id }}
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Build dell'immagine
run: docker build -f docker/Dockerfile -t "$NAME:ci" .
# Il container del job e quello del server non condividono la rete: la prova usa l'healthcheck interno.
- name: Prova di avvio (/health)
run: |
docker run -d --name "$NAME" -e RE_TOKEN=ci "$NAME:ci"
for i in $(seq 1 60); do
if docker exec "$NAME" dotnet RailEnterprise.Server.dll --healthcheck; then echo "server sano"; exit 0; fi
sleep 2
done
docker logs "$NAME" | tail -50
exit 1
- name: Pulizia
if: always()
run: |
docker rm -f "$NAME" 2> /dev/null || true
docker image rm "$NAME:ci" 2> /dev/null || true
+55
View File
@@ -0,0 +1,55 @@
name: Immagine nightly
# L'immagine del server di main come :nightly nel registro container di Gitea (ADR 0014). Mai una release.
on:
schedule:
- cron: "37 2 * * *"
workflow_dispatch:
permissions:
contents: read
packages: write
env:
PUBLIC_URL: ${{ vars.PUBLIC_URL || 'https://gitea.encke-hake.ts.net' }}
jobs:
nightly:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Accesso al registro
env:
REGISTRY: ${{ vars.REGISTRY }}
USER: ${{ vars.REGISTRY_USER || github.actor }}
TOKEN: ${{ secrets.REGISTRY_TOKEN || github.token }}
run: |
registry="${REGISTRY:-$(printf '%s' "$PUBLIC_URL" | sed -E 's#^[a-z]+://##; s#/.*$##')}"
owner="$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')"
{ echo "REGISTRY_HOST=$registry"; echo "IMAGE=$registry/$owner/rail-enterprise-server"; } >> "$GITHUB_ENV"
if ! printf '%s' "$TOKEN" | docker login "$registry" -u "$USER" --password-stdin; then
echo "::error title=Registro::Accesso a $registry rifiutato: serve il segreto REGISTRY_TOKEN."
exit 1
fi
- name: Build e push
run: |
docker build -f docker/Dockerfile --build-arg RE_VERSION="0.0.0-nightly.${{ github.run_number }}" -t "$IMAGE:nightly" .
docker push "$IMAGE:nightly"
- name: Pulizia
if: always()
run: |
docker image rm "$IMAGE:nightly" 2> /dev/null || true
docker logout "$REGISTRY_HOST" || true
+223
View File
@@ -0,0 +1,223 @@
name: Release
# Un tag vMAJOR.MINOR.PATCH[-PRERELEASE] costruisce, prova e pubblica tutto (ADR 0014):
# - sulla release Gitea: il gioco desktop per Windows (client Godot + server locale in «server/»), il server per
# Windows e per Linux, SHA256SUMS e le note di rilascio;
# - nel registro container di Gitea: l'immagine del server con il tag della versione e, per le versioni stabili, :latest.
# La versione viene dal tag e sovrascrive quella di Directory.Build.props, che resta la versione di sviluppo.
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag esistente da (ri)pubblicare, per esempio v0.6.0"
required: true
permissions:
contents: write
packages: write
env:
DOTNET_NOLOGO: "1"
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
BUILD_CPUS: "4"
TAG: ${{ github.event.inputs.tag || github.ref_name }}
PUBLIC_URL: ${{ vars.PUBLIC_URL || 'https://gitea.encke-hake.ts.net' }}
# Versione di Godot .NET usata per esportare il client (deve coincidere con Godot.NET.Sdk nel csproj del client).
GODOT_VERSION: "4.7.2"
GODOT_MIRROR: ${{ vars.GODOT_MIRROR || 'https://github.com/godotengine/godot-builds/releases/download' }}
jobs:
release:
name: Build, test e pubblicazione
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:10.0
timeout-minutes: 150
defaults:
run:
shell: bash
outputs:
version: ${{ steps.version.outputs.version }}
prerelease: ${{ steps.version.outputs.prerelease }}
steps:
- name: Versione
id: version
run: |
semver='^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$'
if [[ ! "$TAG" =~ $semver ]]; then
echo "::error title=Release::Il tag '$TAG' non è vMAJOR.MINOR.PATCH o vMAJOR.MINOR.PATCH-PRERELEASE"
exit 1
fi
version="${TAG#v}"
prerelease=false
if [[ "$version" == *-* ]]; then prerelease=true; fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "prerelease=$prerelease" >> "$GITHUB_OUTPUT"
{ echo "VERSION=$version"; echo "PRERELEASE=$prerelease"; } >> "$GITHUB_ENV"
# Storia completa e tag: le note di rilascio elencano i commit dal tag precedente.
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --tags origin
git checkout -q "refs/tags/$TAG"
git log -1 --format='%h %s'
- name: Strumenti di sistema
run: |
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends unzip zip curl jq libfontconfig1 > /dev/null
- name: Build e test
run: |
scripts/check-nuget.sh
dotnet build RailEnterprise.sln -c Release -m:"$BUILD_CPUS" -nologo -p:Version="$VERSION"
dotnet run --project src/RailEnterprise.Tools -c Release --no-build -- validate-data --data data
dotnet run --project tests/RailEnterprise.Tests -c Release --no-build
- name: Server autonomi (win-x64, linux-x64)
run: |
for rid in win-x64 linux-x64; do
dotnet publish src/RailEnterprise.Server -c Release -r "$rid" --self-contained -p:ReServerOnly=true \
-p:Version="$VERSION" -o "out/server-$rid" -nologo
done
# Godot .NET senza interfaccia esporta il client per Windows. Il server per Windows va in «server/» accanto al
# gioco: è lì che LocalServerLauncher lo cerca per la partita locale.
- name: Gioco desktop per Windows (esportazione Godot)
run: |
set -euo pipefail
tools="$RUNNER_TEMP/godot"
mkdir -p "$tools"
base="$GODOT_MIRROR/$GODOT_VERSION-stable"
curl -fsSL -o "$tools/godot.zip" "$base/Godot_v$GODOT_VERSION-stable_mono_linux_x86_64.zip"
curl -fsSL -o "$tools/templates.tpz" "$base/Godot_v$GODOT_VERSION-stable_mono_export_templates.tpz"
unzip -q "$tools/godot.zip" -d "$tools"
godot="$(find "$tools" -type f -name "Godot_v*_mono_linux.x86_64" | head -n1)"
chmod +x "$godot"
templates="$HOME/.local/share/godot/export_templates/$GODOT_VERSION.stable.mono"
mkdir -p "$templates"
unzip -q "$tools/templates.tpz" -d "$tools/tpl"
cp -r "$tools/tpl/templates/." "$templates/"
cd client/RailEnterprise.Client
mkdir -p export/windows
"$godot" --headless --import || true
"$godot" --headless --export-release "Windows Desktop" export/windows/RailEnterprise.exe
test -f export/windows/RailEnterprise.exe
# senza la soluzione del client Godot esporta il .pck senza il codice C#: il gioco partirebbe vuoto
if ! ls -d export/windows/data_RailEnterprise.Client_* > /dev/null 2>&1; then
echo "::error title=Esportazione::Mancano gli assembly .NET del client (data_RailEnterprise.Client_*)"
exit 1
fi
# Localization legge strings.csv così com'è: se Godot l'ha importato come traduzione, il CSV non è nel .pck
if grep -a -q "assets/i18n/strings\.[a-z]*\.translation" export/windows/RailEnterprise.pck; then
echo "::error title=Esportazione::strings.csv importato come traduzione: il gioco partirebbe senza inglese (serve importer=\"keep\")"
exit 1
fi
cp -r "../../out/server-win-x64" export/windows/server
- name: Pacchetti
run: |
set -euo pipefail
mkdir -p out/release
(cd client/RailEnterprise.Client/export/windows && zip -qr "$OLDPWD/out/release/RailEnterprise-$VERSION-windows-x64.zip" .)
(cd out/server-win-x64 && zip -qr "$OLDPWD/out/release/RailEnterprise-Server-$VERSION-windows-x64.zip" .)
tar -C out/server-linux-x64 -czf "out/release/RailEnterprise-Server-$VERSION-linux-x64.tar.gz" .
cp docker/docker-compose.yml "out/release/docker-compose.yml"
cp docker/unraid-template.xml "out/release/unraid-template.xml"
(cd out/release && sha256sum -- * > SHA256SUMS && cat SHA256SUMS)
- name: Note di rilascio
run: |
prev="$(git describe --tags --abbrev=0 "$TAG^" 2> /dev/null || true)"
owner="$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')"
host="$(printf '%s' "$PUBLIC_URL" | sed -E 's#^[a-z]+://##; s#/.*$##')"
{
echo "## Rail Enterprise $VERSION"
echo
echo "- **Gioco desktop (Windows x64):** scarica \`RailEnterprise-$VERSION-windows-x64.zip\`, estrai e avvia \`RailEnterprise.exe\`. «Partita locale» avvia da sola il server in \`server/\`."
echo "- **Server Docker:** \`docker pull $host/$owner/rail-enterprise-server:$VERSION\` (vedi \`docker-compose.yml\` e \`unraid-template.xml\`)."
echo "- **Server senza Docker:** \`RailEnterprise-Server-$VERSION-*.zip|tar.gz\`, poi \`RailEnterprise.Server --data ./dati\` con \`RE_TOKEN\` impostato."
echo
if [ -n "$prev" ]; then echo "### Modifiche da $prev"; else echo "### Modifiche"; fi
echo
git log --no-merges --format='- %s (%h)' ${prev:+$prev..}"$TAG"
} > out/release-notes.md
cat out/release-notes.md
# Creata come bozza, pubblicata quando tutti i file sono caricati.
- name: Release Gitea
env:
TOKEN: ${{ github.token }}
run: |
set -euo pipefail
api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}"
auth="Authorization: token $TOKEN"
existing="$(curl -fsS -H "$auth" "$api/releases/tags/$TAG" 2> /dev/null | jq -r '.id // empty' || true)"
if [ -n "$existing" ]; then curl -fsS -X DELETE -H "$auth" "$api/releases/$existing"; fi
body="$(jq -n --arg tag "$TAG" --arg name "Rail Enterprise $VERSION" --rawfile body out/release-notes.md \
--argjson pre "$PRERELEASE" '{tag_name:$tag, name:$name, body:$body, draft:true, prerelease:$pre}')"
id="$(curl -fsS -X POST -H "$auth" -H 'Content-Type: application/json' -d "$body" "$api/releases" | jq -r .id)"
for f in out/release/*; do
name="$(basename "$f")"
curl -fsS -X POST -H "$auth" -F "attachment=@$f" "$api/releases/$id/assets?name=$name" > /dev/null
echo "caricato $name"
done
curl -fsS -X PATCH -H "$auth" -H 'Content-Type: application/json' -d '{"draft":false}' "$api/releases/$id" > /dev/null
echo "Release pubblicata: $PUBLIC_URL/${{ github.repository }}/releases/tag/$TAG"
image:
name: Immagine del server
needs: release
runs-on: ubuntu-latest
timeout-minutes: 60
env:
VERSION: ${{ needs.release.outputs.version }}
PRERELEASE: ${{ needs.release.outputs.prerelease }}
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "refs/tags/$TAG:refs/tags/$TAG"
git checkout -q "refs/tags/$TAG"
- name: Accesso al registro
env:
REGISTRY: ${{ vars.REGISTRY }}
USER: ${{ vars.REGISTRY_USER || github.actor }}
TOKEN: ${{ secrets.REGISTRY_TOKEN || github.token }}
run: |
registry="${REGISTRY:-$(printf '%s' "$PUBLIC_URL" | sed -E 's#^[a-z]+://##; s#/.*$##')}"
owner="$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')"
{ echo "REGISTRY_HOST=$registry"; echo "IMAGE=$registry/$owner/rail-enterprise-server"; } >> "$GITHUB_ENV"
if ! printf '%s' "$TOKEN" | docker login "$registry" -u "$USER" --password-stdin; then
# il token del workflow (utente gitea-actions) non può scrivere i pacchetti di un'organizzazione
echo "::error title=Registro::Accesso a $registry rifiutato. Serve il segreto REGISTRY_TOKEN (organizzazione o repository): un token di un utente che può scrivere i pacchetti (scope package: read e write)."
exit 1
fi
- name: Build e push
run: |
docker build -f docker/Dockerfile --build-arg RE_VERSION="$VERSION" -t "$IMAGE:$VERSION" .
docker push "$IMAGE:$VERSION"
# Compose e Unraid seguono :latest, che si muove solo con le versioni stabili.
if [ "$PRERELEASE" != "true" ]; then
docker tag "$IMAGE:$VERSION" "$IMAGE:latest"
docker push "$IMAGE:latest"
fi
- name: Pulizia
if: always()
run: |
docker image rm "$IMAGE:$VERSION" "$IMAGE:latest" 2> /dev/null || true
docker logout "$REGISTRY_HOST" || true
+5 -5
View File
@@ -428,11 +428,11 @@ FodyWeavers.xsd
*.msm
*.msp
# --- Via Ferrea ---
# --- Rail Enterprise ---
# Godot
.godot/
client/ViaFerrea.Client/.godot/
client/ViaFerrea.Client/export/
client/RailEnterprise.Client/.godot/
client/RailEnterprise.Client/export/
# Output degli strumenti e dei test
/out/
/artifacts/
@@ -442,6 +442,6 @@ docker/data/
# Salvataggi locali di sviluppo
/saves/
# Dati copiati nel progetto Godot dalla build del client
client/ViaFerrea.Client/data/
client/RailEnterprise.Client/data/
# Traduzioni generate da Godot importando strings.csv
client/ViaFerrea.Client/assets/i18n/*.translation
client/RailEnterprise.Client/assets/i18n/*.translation
+17 -10
View File
@@ -1,4 +1,4 @@
# CLAUDE.md — Via Ferrea
# CLAUDE.md — Rail Enterprise
Gestionale ferroviario dall'alto: motore headless in C# (.NET 10), server ASP.NET Core in Docker, client Godot 4 .NET.
La specifica vincolante è `docs/GUIDA.md`; lo stato dei lavori è in `docs/STATE.md`. Leggili entrambi a inizio sessione.
@@ -8,8 +8,8 @@ La specifica vincolante è `docs/GUIDA.md`; lo stato dei lavori è in `docs/STAT
```
scripts/build.sh # check-nuget + build Release della soluzione
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
dotnet run --project tests/ViaFerrea.Tests -- --list
dotnet run --project src/ViaFerrea.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
dotnet run --project tests/RailEnterprise.Tests -- --list
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
```
## Regole non negoziabili
@@ -25,14 +25,21 @@ dotnet run --project src/ViaFerrea.Tools -- <comando> # validate-data, genmap,
## Flusso di lavoro
- Una fase alla volta (sezione 16 della guida). Fine fase: build verde, test verdi, `docs/STATE.md` aggiornato, commit `F<n>: <cosa>`.
- Nuovi test nel harness interno (`[Test]`, `Assert`), un file per area in `tests/ViaFerrea.Tests/<Area>/`.
- Nuovi test nel harness interno (`[Test]`, `Assert`), un file per area in `tests/RailEnterprise.Tests/<Area>/`.
- I test lunghi si marcano `[Test(Slow = true)]`.
## Gitea, CI e rilasci
- Repository `BalboSoft/Rail_Enterprise` su Gitea (`gitea.encke-hake.ts.net`, in LAN `192.168.30.23:3000`). Il progetto si chiamava «Via Ferrea»: il nome attuale è «Rail Enterprise» ovunque (ADR 0014).
- Ogni lavoro ha una issue nel milestone della sua fase (F0…F7, «Infrastruttura») e nel progetto «Roadmap»; PR verso `main` con `.gitea/PULL_REQUEST_TEMPLATE.md`, merge con la CI verde.
- `.gitea/workflows/ci.yml` (PR e main), `release.yml` (tag `vX.Y.Z`: gioco Windows + server + immagine Docker), `nightly.yml`. Segreto di organizzazione `REGISTRY_TOKEN`.
- La Wiki su Gitea (guida del giocatore, schermate) si aggiorna quando cambia l'interfaccia.
## Mappa del codice
- `src/ViaFerrea.Core` — Common, Time, Data, Map, Economy, Rail, Commands, Simulation, Persistence (vedi `docs/ARCHITECTURE.md`).
- `src/ViaFerrea.Protocol` — frame e messaggi (vedi `docs/PROTOCOL.md`).
- `src/ViaFerrea.Server` — GameLoop, sessioni WebSocket, API HTTP.
- `src/ViaFerrea.Tools` — `viaferrea-tools`.
- `client/ViaFerrea.Client` — progetto Godot.
- `reference/` — immagini di riferimento visivo vincolanti.
- `src/RailEnterprise.Core` — Common, Time, Data, Map, Economy, Rail, Commands, Simulation, Persistence (vedi `docs/ARCHITECTURE.md`).
- `src/RailEnterprise.Protocol` — frame e messaggi (vedi `docs/PROTOCOL.md`).
- `src/RailEnterprise.Server` — GameLoop, sessioni WebSocket, API HTTP.
- `src/RailEnterprise.Tools` — `railenterprise-tools`.
- `client/RailEnterprise.Client` — progetto Godot.
- `reference/` — immagini di riferimento visivo vincolanti (01–09: mappa, binari, treni, edifici, palette, mercato, industria, scalata, connessione).
+5 -5
View File
@@ -1,17 +1,17 @@
<Project>
<!-- Impostazioni comuni a tutti i progetti .NET di Via Ferrea (il client Godot ha il proprio). -->
<!-- Impostazioni comuni a tutti i progetti .NET di Rail Enterprise (il client Godot ha il proprio). -->
<PropertyGroup>
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
<Version>0.1.0</Version>
<Version>0.6.0</Version>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<InvariantGlobalization>true</InvariantGlobalization>
<Deterministic>true</Deterministic>
<Authors>Via Ferrea</Authors>
<Product>Via Ferrea</Product>
<Copyright>Via Ferrea</Copyright>
<Authors>Rail Enterprise</Authors>
<Product>Rail Enterprise</Product>
<Copyright>Rail Enterprise</Copyright>
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<!-- Nessun pacchetto NuGet: niente audit verso feed esterni. -->
+76 -37
View File
@@ -1,63 +1,101 @@
# Via Ferrea
# Rail Enterprise
Gestionale ferroviario visto dall'alto, ambientato dal 1850 in una regione immaginaria: binari con pendenze, trincee, ponti e gallerie; economia con prezzi globali e locali; pendolarismo di lavoratori e personale; manutenzione per componente di treni e industrie; concorrenti IA, borsa e scalate; un mondo che non finisce mai.
Il motore di gioco è headless e deterministico (C# su .NET 10) e gira sia dentro il client desktop (Godot 4 .NET) sia come server Linux in Docker.
Il motore di gioco è headless e deterministico (C# su .NET 10) e gira sia dentro il gioco desktop (client Godot 4 .NET, che avvia un server locale) sia come server Linux in Docker.
## Requisiti
![Linea con ponte nel client](docs/screenshots/f3-linea-con-ponte.jpg)
## Scaricare
Ogni versione è sulla pagina [Release](https://gitea.encke-hake.ts.net/BalboSoft/Rail_Enterprise/releases):
| File | Per |
|---|---|
| `RailEnterprise-<versione>-windows-x64.zip` | il gioco desktop: estrai e avvia `RailEnterprise.exe` («Partita locale» avvia il server in `server/`) |
| `RailEnterprise-Server-<versione>-windows-x64.zip` / `-linux-x64.tar.gz` | il server senza Docker |
| immagine `gitea.encke-hake.ts.net/balbosoft/rail-enterprise-server:<versione>` | il server in Docker / Unraid |
## Requisiti per lo sviluppo
- .NET SDK 10.x (`dotnet --version`)
- Godot 4 .NET, versione stabile più recente, come `godot` nel PATH (solo per il client)
- Godot 4.7 .NET come `godot` nel PATH (solo per avviare o esportare il client)
- Docker (solo per l'immagine del server)
## Compilare e provare
```
scripts/build.sh # controllo "zero NuGet" + build Release
scripts/test.sh # validazione dei dati + tutti i test
```bash
scripts/build.sh # controllo "zero NuGet" + build Release
scripts/test.sh # validazione dei dati + tutti i test
scripts/test.sh --skip-slow # senza i test di accettazione pluriennali
```
Su Windows: `./scripts/build.ps1 -Test`.
Su Windows (PowerShell): `./scripts/build.ps1 -Test`.
## Avviare in locale
**Server da sorgente** (porta 7400, token `prova`, salvataggi in `./dati-locali`):
```bash
dotnet run --project src/RailEnterprise.Server -c Release -- --port 7400 --token prova --data ./dati-locali
```
Poi `http://localhost:7400/health` e `http://localhost:7400/metrics`. Con `--local` il server sceglie una porta libera e stampa `LISTENING <porta>` (è il modo in cui lo avvia il client).
**Server in Docker** (dalla radice del repository):
```bash
docker compose -f docker/docker-compose.yml up -d --build
```
Variabili: `RE_TOKEN` (obbligatoria in rete), `RE_DIFFICULTY`, `RE_SEED`, `RE_MAP_SIZE`, `RE_DATA_DIR` (default `/data`), `RE_AUTOSAVE_MIN`, `RE_TICK_MS`, `RE_LOG_LEVEL`.
**Client Godot**:
```bash
dotnet build src/RailEnterprise.Server -c Release
dotnet build client/RailEnterprise.Client/RailEnterprise.Client.csproj
godot --path client/RailEnterprise.Client
```
Dal menu, «Partita locale» avvia il server compilato (`src/RailEnterprise.Server/bin/Release/...` oppure `RE_SERVER_PATH`); «Connetti a un server» usa indirizzo e token di un server già avviato.
**Collaudi senza mani**:
```bash
dotnet run --project src/RailEnterprise.Tools -- smoke --url ws://127.0.0.1:7400/ws --token prova
GODOT=/percorso/godot scripts/client-autopilot.sh
```
## Strumenti
`dotnet run --project src/RailEnterprise.Tools -- <comando>`: `validate-data`, `genmap`, `profile`, `simulate`, `bench`, `smoke`, `replay` (vedi la [Wiki](https://gitea.encke-hake.ts.net/BalboSoft/Rail_Enterprise/wiki)).
## Struttura
| Cartella | Contenuto |
|---|---|
| `src/ViaFerrea.Core` | simulazione, dati, mappa, economia, rete ferroviaria, salvataggi |
| `src/ViaFerrea.Protocol` | protocollo binario su WebSocket |
| `src/ViaFerrea.Server` | server autorevole (Kestrel) |
| `src/ViaFerrea.Tools` | `viaferrea-tools`: validate-data, genmap, profile, simulate, bench, smoke, replay |
| `tests/ViaFerrea.Tests` | harness di test interno e scenari |
| `client/ViaFerrea.Client` | client Godot |
| `src/RailEnterprise.Core` | simulazione, dati, mappa, economia, rete ferroviaria, salvataggi |
| `src/RailEnterprise.Protocol` | protocollo binario su WebSocket |
| `src/RailEnterprise.Server` | server autorevole (Kestrel) |
| `src/RailEnterprise.Tools` | `railenterprise-tools` |
| `tests/RailEnterprise.Tests` | harness di test interno e scenari |
| `client/RailEnterprise.Client` | client Godot |
| `data/` | parametri di gioco in JSON con schema |
| `docker/` | Dockerfile, compose, template Unraid |
| `docs/` | guida, GDD, architettura, protocollo, stato, ADR |
| `reference/` | immagini di riferimento visivo |
| `docs/` | guida, GDD, architettura, protocollo, stato, ADR, schermate |
| `reference/` | immagini di riferimento visivo vincolanti (01–09) |
| `.gitea/` | workflow di CI e rilascio, modelli di PR e issue |
## Server e client in locale
## CI e rilasci
```
dotnet run --project src/ViaFerrea.Server -- --local --token prova # stampa LISTENING <porta>
dotnet build client/ViaFerrea.Client/ViaFerrea.Client.csproj # poi apri client/ViaFerrea.Client con Godot 4.7 .NET
```
- **CI** (`.gitea/workflows/ci.yml`): su ogni PR e su `main` — zero NuGet, build, dati, test, server per Windows, client, immagine Docker con healthcheck.
- **Rilascio** (`.gitea/workflows/release.yml`): `git tag v0.6.0 && git push origin v0.6.0` pubblica la release con il gioco per Windows, i server e `SHA256SUMS`, e l'immagine Docker `:<versione>` (`:latest` per le versioni stabili).
- **Nightly** (`.gitea/workflows/nightly.yml`): immagine `:nightly` da `main` ogni notte.
Dal menu del client, «Partita locale» avvia da solo il server compilato (`src/ViaFerrea.Server/bin/...` oppure `VF_SERVER_PATH`).
Collaudi senza mani: `dotnet run --project src/ViaFerrea.Tools -- smoke --url ws://127.0.0.1:7400/ws --token prova`
contro un server in esecuzione; `GODOT=/percorso/godot scripts/client-autopilot.sh` per il client con schermate.
Dettagli in [ADR 0014](docs/adr/0014-nome-ci-e-rilasci.md).
![Linea con ponte nel client](docs/screenshots/f3-linea-con-ponte.jpg)
## Server in Docker
```
docker compose -f docker/docker-compose.yml up -d # oppure scripts/publish-image.sh per il registry Gitea
curl http://localhost:7400/health
curl http://localhost:7400/metrics
```
Variabili principali: `VF_TOKEN` (obbligatoria in rete), `VF_DIFFICULTY`, `VF_SEED`, `VF_MAP_SIZE`, `VF_DATA_DIR` (default `/data`).
Il server parla WebSocket in chiaro: per l'uso fuori da una rete privata mettilo dietro un reverse proxy con TLS (per esempio Caddy, Traefik o Nginx Proxy Manager su Unraid) ed esponi solo `wss://`.
Il server parla WebSocket in chiaro: fuori da una rete privata mettilo dietro un reverse proxy con TLS ed esponi solo `wss://`.
## Documentazione
@@ -67,3 +105,4 @@ Il server parla WebSocket in chiaro: per l'uso fuori da una rete privata mettilo
- `docs/PROTOCOL.md` — protocollo di rete
- `docs/STATE.md` — stato dei lavori
- `docs/adr/` — decisioni architetturali
- [Wiki](https://gitea.encke-hake.ts.net/BalboSoft/Rail_Enterprise/wiki) — guida del giocatore e schermate
+5 -5
View File
@@ -5,17 +5,17 @@ VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Core", "src\ViaFerrea.Core\ViaFerrea.Core.csproj", "{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Core", "src\RailEnterprise.Core\RailEnterprise.Core.csproj", "{D50BCC13-4F79-4DB1-BD16-5E7576006DA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Protocol", "src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj", "{7582B640-61C0-47F8-9A2E-B3607B01FD35}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Protocol", "src\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj", "{7582B640-61C0-47F8-9A2E-B3607B01FD35}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Server", "src\ViaFerrea.Server\ViaFerrea.Server.csproj", "{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Server", "src\RailEnterprise.Server\RailEnterprise.Server.csproj", "{D9E37057-86E8-4DDE-B3DA-EDC44F4EAE30}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Tools", "src\ViaFerrea.Tools\ViaFerrea.Tools.csproj", "{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Tools", "src\RailEnterprise.Tools\RailEnterprise.Tools.csproj", "{509F4E00-74B7-4FFB-84E0-3CB1F671A70E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ViaFerrea.Tests", "tests\ViaFerrea.Tests\ViaFerrea.Tests.csproj", "{BE4E0868-2350-4C87-968E-E424D4DEB1C5}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Tests", "tests\RailEnterprise.Tests\RailEnterprise.Tests.csproj", "{BE4E0868-2350-4C87-968E-E424D4DEB1C5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -1,13 +1,13 @@
<Project Sdk="Godot.NET.Sdk/4.7.2">
<!--
Client Godot di Via Ferrea: fuori dalla soluzione principale. Usa Core e Protocol (net8.0)
Client Godot di Rail Enterprise: fuori dalla soluzione principale. Usa Core e Protocol (net8.0)
per le anteprime e per la copia locale del mondo; nessuna logica di gioco.
-->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<EnableDynamicLoading>true</EnableDynamicLoading>
<RootNamespace>ViaFerrea.Client</RootNamespace>
<RootNamespace>RailEnterprise.Client</RootNamespace>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
@@ -16,8 +16,8 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ViaFerrea.Core\ViaFerrea.Core.csproj" />
<ProjectReference Include="..\..\src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj" />
<ProjectReference Include="..\..\src\RailEnterprise.Core\RailEnterprise.Core.csproj" />
<ProjectReference Include="..\..\src\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
</ItemGroup>
<!-- I file dati del gioco entrano nel progetto Godot (res://data) prima di ogni build. -->
@@ -0,0 +1,19 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RailEnterprise.Client", "RailEnterprise.Client.csproj", "{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
ExportDebug|Any CPU = ExportDebug|Any CPU
ExportRelease|Any CPU = ExportRelease|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
\t\t{6E1D5A3C-4B7F-4C2A-9D8E-2F0A1B3C5D7E}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
EndGlobalSection
EndGlobal
@@ -282,7 +282,7 @@ Seleziona un treno,,Select a train
Seleziona un treno e un deposito,,Select a train and a depot
Sentiment del mercato,,Market sentiment
Serve un deposito,,A depot is required
Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH.,,Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH.,,Local server not found: build src/RailEnterprise.Server or set RE_SERVER_PATH.
Servizi,,Services
Servono almeno due fermate,,At least two stops are needed
Soddisfazione,,Satisfaction
@@ -314,7 +314,7 @@ Veicoli,,Vehicles
Velocità,,Speed
Vendi,,Sell
Verde,,Green
Via Ferrea,,Via Ferrea
Rail Enterprise,,Rail Enterprise
a piedi,,on foot
abitanti,,inhabitants
agli azionisti; i dividendi alzano il sentiment del titolo.,,to shareholders; dividends raise the share's sentiment.
@@ -442,3 +442,111 @@ ultimi,,last
vincitore,,winner
"volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.",,"times annual profit, divided by the shares and multiplied by market sentiment."
⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto.,,⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
30 giorni,,30 days
Avanzamento verso,,Progress towards
Capacità,,Capacity
Capacità usata questo mese,,Capacity used this month
Città collegate oltre,,Connected towns over
Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello,,Buy goods at the source and resell them where the price is highest. Unlocked at level
Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello,,Buy goods at the source and resell them where the price is highest. Unlocks at level
Compravendita in proprio,,Own-account trading
Consumi della mappa,,Map consumption
Dazio,,Duty
Disponibile dal,,Available from
Domanda globale,,Global demand
Dove conviene vendere,,Where to sell
Evento in corso,,Current event
Hub verso il mercato mondiale via mare,,Hub to the world market by sea
Hub verso il mercato mondiale via terra,,Hub to the world market by land
"I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse.",,"World prices follow their multi-year cycle, with no shocks."
Il prezzo mondiale di,,The world price of
In attesa dei prezzi dal server…,,Waiting for prices from the server…
Indice materie prime,,Commodity index
Lo storico si forma giorno dopo giorno,,The history builds up day by day
"Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.",,"Average of the global prices of the available goods relative to their base price (100 = base prices), with the change over the last 30 days."
Mercato globale,,Global market
Merce,,Goods
Nessun evento in corso,,No current event
Nessuna industria consuma questa merce e nessun hub la compra.,,No industry consumes these goods and no hub buys them.
Non ancora disponibili,,Not yet available
Offerta,,Supply
Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub.,,Supply and demand add the map's production and consumption to the share of the world market traded through the hubs.
Offerta globale,,Global supply
Offerta · domanda,,Supply · demand
Pianifica la linea,,Plan the line
Porta i binari fino al confine per comprare e vendere via terra.,,Lay track to the border to buy and sell by land.
Porta i binari fino al porto per comprare e vendere via mare.,,Lay track to the port to buy and sell by sea.
"Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. Il trasporto è a parte.",,"Local price for own trading: higher where storage is empty; hubs buy at the world price minus duty. Carrier deliveries are still paid at the global price. Transport is extra."
Prezzi mondiali al,,World prices as of
Prezzo,,Price
"Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.",,"Global price at the end of each month; the dashed line is the forecast from the world component (cycle and fading shocks), the blue band its uncertainty."
Produzione della mappa,,Map production
Scegli una merce a sinistra,,Pick goods on the left
Servito da,,Served by
Torna alla mappa,,Back to the map
aggiornati ogni giorno di gioco,,updated every game day
ago,,Aug
apr,,Apr
collegato,,connected
dic,,Dec
domanda,,demand
esportazione,,export
feb,,Feb
gen,,Jan
giu,,Jun
in 30 giorni,,in 30 days
lug,,Jul
mag,,May
mar,,Mar
mese,,month
mesi e previsione a,,months and forecast for
"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"
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 collegato,,not connected
nov,,Nov
oggi,,today
ott,,Oct
prev.,,fcst.
prezzo mondiale in calo,,world price falling
prezzo mondiale in rialzo,,world price rising
quota mondiale dagli hub,,world share through the hubs
rispetto al ciclo per circa,,compared with the cycle for about
serve,,needs
servita dalla tua linea,,served by your line
set,,Sep
unità/mese,,units/month
è più alto del,,is higher by
è più basso del,,is lower by
Spedisci a,,Ship to
Quantità,,Quantity
"Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.",,"Buys from producers and hubs in the station's catchment, cheapest first, up to 10% above the quoted price."
"Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.",,"Sells from the warehouse to consumers and hubs in the catchment, highest price first, down to 10% below the quoted price."
"Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.",,"Ships the goods on your lines to the warehouse of another of your stations, with no fare."
In magazzino,,In the warehouse
Costruisci una stazione per avere un magazzino dove comprare e vendere.,,Build a station to get a warehouse where you can buy and sell.
in magazzino,,in the warehouse
Si compra a,,Buy at
disponibili,,available
Nessun produttore né hub nel bacino la vende,,No producer or hub in the catchment sells it
si vende a,,sell at
richieste,,wanted
nessun consumatore né hub nel bacino la compra,,no consumer or hub in the catchment buys it
Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.,,Local price: it rises as the seller runs low and falls as the buyer fills up.
Magazzino,,Warehouse
unità,,units
di cui,,of which
Vuoto,,Empty
Scegli una stazione di arrivo diversa da quella di partenza,,Choose a destination station different from the departure one
"Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra.",,"You have goods in your warehouses: you can sell or ship them, but not buy more."
Eventi in corso,,Current events
altri,,more
Capacità produttiva,,Production capacity
Consumi della città,,Town consumption
Domanda di,,Demand for
Presenze al lavoro,,Attendance at work
Velocità dei treni,,Train speed
Usura dei binari,,Track wear
entro,,within
fino al,,until
da domani,,from tomorrow
dal,,from
1 keys it en
282 Seleziona un treno e un deposito Select a train and a depot
283 Sentiment del mercato Market sentiment
284 Serve un deposito A depot is required
285 Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH. Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH. Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH. Local server not found: build src/RailEnterprise.Server or set RE_SERVER_PATH.
286 Servizi Services
287 Servono almeno due fermate At least two stops are needed
288 Soddisfazione Satisfaction
314 Velocità Speed
315 Vendi Sell
316 Verde Green
317 Via Ferrea Rail Enterprise Via Ferrea Rail Enterprise
318 a piedi on foot
319 abitanti inhabitants
320 agli azionisti; i dividendi alzano il sentiment del titolo. to shareholders; dividends raise the share's sentiment.
442 vincitore winner
443 volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato. times annual profit, divided by the shares and multiplied by market sentiment.
444 ⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto. ⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
445 30 giorni 30 days
446 Avanzamento verso Progress towards
447 Capacità Capacity
448 Capacità usata questo mese Capacity used this month
449 Città collegate oltre Connected towns over
450 Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello Buy goods at the source and resell them where the price is highest. Unlocked at level
451 Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello Buy goods at the source and resell them where the price is highest. Unlocks at level
452 Compravendita in proprio Own-account trading
453 Consumi della mappa Map consumption
454 Dazio Duty
455 Disponibile dal Available from
456 Domanda globale Global demand
457 Dove conviene vendere Where to sell
458 Evento in corso Current event
459 Hub verso il mercato mondiale via mare Hub to the world market by sea
460 Hub verso il mercato mondiale via terra Hub to the world market by land
461 I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse. World prices follow their multi-year cycle, with no shocks.
462 Il prezzo mondiale di The world price of
463 In attesa dei prezzi dal server… Waiting for prices from the server…
464 Indice materie prime Commodity index
465 Lo storico si forma giorno dopo giorno The history builds up day by day
466 Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni. Average of the global prices of the available goods relative to their base price (100 = base prices), with the change over the last 30 days.
467 Mercato globale Global market
468 Merce Goods
469 Nessun evento in corso No current event
470 Nessuna industria consuma questa merce e nessun hub la compra. No industry consumes these goods and no hub buys them.
471 Non ancora disponibili Not yet available
472 Offerta Supply
473 Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub. Supply and demand add the map's production and consumption to the share of the world market traded through the hubs.
474 Offerta globale Global supply
475 Offerta · domanda Supply · demand
476 Pianifica la linea Plan the line
477 Porta i binari fino al confine per comprare e vendere via terra. Lay track to the border to buy and sell by land.
478 Porta i binari fino al porto per comprare e vendere via mare. Lay track to the port to buy and sell by sea.
479 Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. Il trasporto è a parte. Local price for own trading: higher where storage is empty; hubs buy at the world price minus duty. Carrier deliveries are still paid at the global price. Transport is extra.
480 Prezzi mondiali al World prices as of
481 Prezzo Price
482 Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza. Global price at the end of each month; the dashed line is the forecast from the world component (cycle and fading shocks), the blue band its uncertainty.
483 Produzione della mappa Map production
484 Scegli una merce a sinistra Pick goods on the left
485 Servito da Served by
486 Torna alla mappa Back to the map
487 aggiornati ogni giorno di gioco updated every game day
488 ago Aug
489 apr Apr
490 collegato connected
491 dic Dec
492 domanda demand
493 esportazione export
494 feb Feb
495 gen Jan
496 giu Jun
497 in 30 giorni in 30 days
498 lug Jul
499 mag May
500 mar Mar
501 mese month
502 mesi e previsione a months and forecast for
503 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
504 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
505 non collegato not connected
506 nov Nov
507 oggi today
508 ott Oct
509 prev. fcst.
510 prezzo mondiale in calo world price falling
511 prezzo mondiale in rialzo world price rising
512 quota mondiale dagli hub world share through the hubs
513 rispetto al ciclo per circa compared with the cycle for about
514 serve needs
515 servita dalla tua linea served by your line
516 set Sep
517 unità/mese units/month
518 è più alto del is higher by
519 è più basso del is lower by
520 Spedisci a Ship to
521 Quantità Quantity
522 Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato. Buys from producers and hubs in the station's catchment, cheapest first, up to 10% above the quoted price.
523 Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato. Sells from the warehouse to consumers and hubs in the catchment, highest price first, down to 10% below the quoted price.
524 Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa. Ships the goods on your lines to the warehouse of another of your stations, with no fare.
525 In magazzino In the warehouse
526 Costruisci una stazione per avere un magazzino dove comprare e vendere. Build a station to get a warehouse where you can buy and sell.
527 in magazzino in the warehouse
528 Si compra a Buy at
529 disponibili available
530 Nessun produttore né hub nel bacino la vende No producer or hub in the catchment sells it
531 si vende a sell at
532 richieste wanted
533 nessun consumatore né hub nel bacino la compra no consumer or hub in the catchment buys it
534 Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie. Local price: it rises as the seller runs low and falls as the buyer fills up.
535 Magazzino Warehouse
536 unità units
537 di cui of which
538 Vuoto Empty
539 Scegli una stazione di arrivo diversa da quella di partenza Choose a destination station different from the departure one
540 Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra. You have goods in your warehouses: you can sell or ship them, but not buy more.
541 Eventi in corso Current events
542 altri more
543 Capacità produttiva Production capacity
544 Consumi della città Town consumption
545 Domanda di Demand for
546 Presenze al lavoro Attendance at work
547 Velocità dei treni Train speed
548 Usura dei binari Track wear
549 entro within
550 fino al until
551 da domani from tomorrow
552 dal from
@@ -0,0 +1,3 @@
[remap]
importer="keep"
File renamed without changes.

Before

Width:  |  Height:  |  Size: 351 B

After

Width:  |  Height:  |  Size: 351 B

@@ -8,7 +8,7 @@ custom_features=""
export_filter="all_resources"
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
exclude_filter=""
export_path="export/windows/ViaFerrea.exe"
export_path="export/windows/RailEnterprise.exe"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
@@ -21,8 +21,8 @@ custom_template/release=""
debug/export_console_wrapper=1
binary_format/embed_pck=false
binary_format/architecture="x86_64"
application/product_name="Via Ferrea"
application/company_name="Via Ferrea"
application/product_name="Rail Enterprise"
application/company_name="Rail Enterprise"
application/file_description="Gestionale ferroviario dall'alto"
dotnet/include_scripts_content=false
dotnet/include_debug_symbols=false
@@ -38,7 +38,7 @@ custom_features=""
export_filter="all_resources"
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
exclude_filter=""
export_path="export/linux/ViaFerrea.x86_64"
export_path="export/linux/RailEnterprise.x86_64"
encrypt_pck=false
encrypt_directory=false
@@ -1,11 +1,11 @@
; File di progetto di Godot 4: client di Via Ferrea (rendering, input, interfaccia).
; File di progetto di Godot 4: client di Rail Enterprise (rendering, input, interfaccia).
; Nessuna logica di gioco: il server è autorevole (docs/GUIDA.md, sezione 14.3).
config_version=5
[application]
config/name="Via Ferrea"
config/name="Rail Enterprise"
config/description="Gestionale ferroviario dall'alto"
run/main_scene="res://scenes/Main.tscn"
config/features=PackedStringArray("4.7", "C#", "GL Compatibility")
@@ -21,7 +21,7 @@ window/stretch/aspect="expand"
[dotnet]
project/assembly_name="ViaFerrea.Client"
project/assembly_name="RailEnterprise.Client"
[internationalization]
@@ -1,15 +1,15 @@
using Godot;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using RailEnterprise.Client.Hud;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace ViaFerrea.Client.App;
namespace RailEnterprise.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
@@ -235,6 +235,11 @@ public partial class AutoPilot : Node
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
await Shot("14_compagnia_giocatore", 40);
// Mercato globale (immagine 06): storico, previsione, hub ed evento in corso
_game.OpenMarket();
await Until(() => World.Market is not null, "quadro del mercato", 30);
await Shot("16_mercato", 40);
// Cronaca provvisoria
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
@@ -1,7 +1,7 @@
using Godot;
using ViaFerrea.Core.Data;
using RailEnterprise.Core.Data;
namespace ViaFerrea.Client.App;
namespace RailEnterprise.Client.App;
/// <summary>File dati del gioco dentro il progetto Godot (res://data, copiati dalla build del client).</summary>
public sealed class GodotDataSource(string root = "res://data") : IDataSource
@@ -1,11 +1,12 @@
using Godot;
namespace ViaFerrea.Client.App;
namespace RailEnterprise.Client.App;
/// <summary>
/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani),
/// le traduzioni stanno in <c>assets/i18n/strings.csv</c> (colonne keys, it, en) e si caricano
/// all'avvio senza passare dall'importazione dell'editor.
/// all'avvio senza passare dall'importazione dell'editor. Per questo <c>strings.csv.import</c> usa
/// l'importatore «keep»: con quello di traduzione Godot non metterebbe il CSV nel gioco esportato.
/// </summary>
public static class Localization
{
@@ -1,6 +1,6 @@
using Godot;
namespace ViaFerrea.Client.App;
namespace RailEnterprise.Client.App;
/// <summary>Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara.</summary>
public static class Palette
@@ -1,6 +1,6 @@
using Godot;
namespace ViaFerrea.Client.App;
namespace RailEnterprise.Client.App;
/// <summary>
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
@@ -1,10 +1,10 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Map;
using RailEnterprise.Core.Map;
using RailEnterprise.Protocol.Client;
namespace ViaFerrea.Client.Hud;
namespace RailEnterprise.Client.Hud;
/// <summary>Minimappa: terreno ridotto, linee, città e rettangolo della vista; un clic centra la mappa.</summary>
public partial class Minimap : Control
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
namespace RailEnterprise.Client.Hud;
/// <summary>Notiziario in basso (immagine 01): «Notizie» e gli ultimi eventi che scorrono.</summary>
public partial class Ticker : PanelContainer
@@ -1,8 +1,8 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
namespace RailEnterprise.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
namespace RailEnterprise.Client.Hud;
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
public partial class TopBar : PanelContainer
@@ -0,0 +1,41 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Panels;
using RailEnterprise.Protocol.Client;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Hud;
/// <summary>
/// Riquadro «Eventi in corso» del pannello destro, sopra la minimappa (ADR 0017): gli eventi del
/// mondo attivi dal resoconto giornaliero, con luogo, effetti e scadenza. Nascosto se non ce ne sono.
/// </summary>
public partial class WorldEventsBox : PanelContainer
{
private readonly VBoxContainer _list = new();
private readonly Label _title = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 10));
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 6);
AddChild(col);
col.AddChild(_title);
_list.AddThemeConstantOverride("separation", 8);
col.AddChild(_list);
Visible = false;
}
/// <summary>Ridisegna l'elenco (a ogni resoconto giornaliero).</summary>
public void Update(ClientWorld w)
{
var events = w.LastDigest?.WorldEvents ?? [];
Visible = events.Count > 0;
foreach (var c in _list.GetChildren()) c.QueueFree();
_title.Text = $"{T("Eventi in corso")} ({events.Count})";
// al massimo quattro righe: il riquadro non deve schiacciare la minimappa
foreach (var e in events.OrderBy(e => e.EndDay).Take(4)) _list.AddChild(WorldEventText.Row(w, e));
if (events.Count > 4) _list.AddChild(UiTheme.Text($"+ {events.Count - 4} {T("altri")}", 12, Palette.TextSecondary));
}
}
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Data;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Data;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client;
namespace RailEnterprise.Client;
/// <summary>
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
@@ -26,7 +26,7 @@ public partial class Main : Node
string locale = (string)cfg.GetValue("ui", "locale", "it");
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Via Ferrea";
GetWindow().Title = "Rail Enterprise";
try
{
_data = GodotDataSource.LoadGameData();
@@ -42,9 +42,9 @@ public partial class Main : Node
{
// 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("VF_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("VF_SEED", "3");
System.Environment.SetEnvironmentVariable("VF_AUTOSAVE_MIN", "0");
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
StartLocal();
}
}
@@ -102,7 +102,7 @@ public partial class Main : Node
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
ShowMenu(T("Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH."));
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
return;
}
if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…"));
@@ -1,10 +1,10 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Map;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
@@ -1,7 +1,7 @@
using Godot;
using ViaFerrea.Core.Common;
using RailEnterprise.Core.Common;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
@@ -1,7 +1,7 @@
using Godot;
using ViaFerrea.Client.Net;
using RailEnterprise.Client.Net;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Map;
using RailEnterprise.Protocol.Client;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>Sagome degli strumenti: tracciato in corso con l'anteprima delle opere, stazione o deposito da posare, fermate di una linea.</summary>
public partial class ToolOverlay : Node2D
@@ -1,10 +1,10 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
@@ -1,12 +1,12 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace ViaFerrea.Client.Map;
namespace RailEnterprise.Client.Map;
/// <summary>
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Data;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Data;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace ViaFerrea.Client.Net;
namespace RailEnterprise.Client.Net;
/// <summary>
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
@@ -1,7 +1,7 @@
using System.Diagnostics;
using Godot;
namespace ViaFerrea.Client.Net;
namespace RailEnterprise.Client.Net;
/// <summary>
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
@@ -14,22 +14,22 @@ public sealed class LocalServerLauncher : IDisposable
public int Port { get; private set; }
public string Token { get; } = Guid.NewGuid().ToString("N");
/// <summary>Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
/// <summary>Percorso del server: variabile RE_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
public static string? FindServer()
{
string? env = System.Environment.GetEnvironmentVariable("VF_SERVER_PATH");
string? env = System.Environment.GetEnvironmentVariable("RE_SERVER_PATH");
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
foreach (string name in new[] { "ViaFerrea.Server.exe", "ViaFerrea.Server", "ViaFerrea.Server.dll" })
foreach (string name in new[] { "RailEnterprise.Server.exe", "RailEnterprise.Server", "RailEnterprise.Server.dll" })
{
string candidate = Path.Combine(exeDir, "server", name);
if (File.Exists(candidate)) return candidate;
}
// sviluppo: il progetto Godot sta in client/ViaFerrea.Client, il server in src/
// sviluppo: il progetto Godot sta in client/RailEnterprise.Client, il server in src/
string project = ProjectSettings.GlobalizePath("res://");
foreach (string config in new[] { "Release", "Debug" })
{
string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "ViaFerrea.Server", "bin", config, "net10.0", "ViaFerrea.Server.dll"));
string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "RailEnterprise.Server", "bin", config, "net10.0", "RailEnterprise.Server.dll"));
if (File.Exists(candidate)) return candidate;
}
return null;
@@ -1,14 +1,14 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
@@ -1,13 +1,13 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Registro degli impieghi (sezione 9): convenzioni proposte dalle industrie (accetta o rifiuta),
@@ -1,9 +1,9 @@
using System.Globalization;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
@@ -1,14 +1,14 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>Scheda dell'entità selezionata (treno, stazione, industria, città) come nel pannello destro dell'immagine 01.</summary>
public partial class InfoPanel : VBoxContainer
@@ -142,6 +142,7 @@ public partial class InfoPanel : VBoxContainer
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
WorldEventText.AddNotices(w, this, WorldEventText.Industry, ind.Id);
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
int me = w.Summary?.CompanyId ?? 0;
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
@@ -180,6 +181,7 @@ public partial class InfoPanel : VBoxContainer
AddChild(PanelKit.Pair(T("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
WorldEventText.AddNotices(w, this, WorldEventText.Town, town.Id);
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
if (w.Employment is { } report)
{
@@ -197,7 +199,7 @@ public partial class InfoPanel : VBoxContainer
}
default:
{
AddChild(UiTheme.TitleLabel(T("Via Ferrea"), 38));
AddChild(UiTheme.TitleLabel(T("Rail Enterprise"), 38));
var help = UiTheme.Text(T("Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda."), 14, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
@@ -1,12 +1,12 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>Linee: fermate scelte con un clic sulle stazioni, nome e colore, attesa del pieno alla prima fermata.</summary>
public partial class LinesPanel : VBoxContainer
@@ -1,12 +1,12 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
@@ -279,6 +279,8 @@ public partial class MaintenancePanel : VBoxContainer
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
_workshop.AddChild(stats);
if (d.WaitingParts) _workshop.AddChild(UiTheme.Notice(T("Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.")));
// sciopero del personale del deposito (ADR 0017)
WorldEventText.AddNotices(w, _workshop, WorldEventText.Depot, _depot);
if (reg is not null)
{
if (reg.WorkRate < 0.999f)
@@ -0,0 +1,573 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// «Mercato globale» a tutto schermo (immagine di riferimento 06): a sinistra i beni con prezzo,
/// variazione a 30 giorni e barre di offerta e domanda; al centro il bene scelto con lo storico a
/// 24 mesi, la previsione, offerta, domanda, scorte e «Dove conviene vendere»; a destra gli hub,
/// l'evento di mercato in corso e l'avanzamento verso la compravendita in proprio. Tutti i numeri
/// arrivano dal server (MarketReport, ADR 0015): il pannello li chiede all'apertura e a ogni nuovo
/// giorno e li mostra com'è.
/// </summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _index = UiTheme.Text("", 22, bold: true);
private readonly Label _indexChange = UiTheme.Text("", 16, bold: true);
private readonly VBoxContainer _rows = PanelKit.Column(2);
private readonly Label _later = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _goodTitle = UiTheme.TitleLabel("", 40);
private readonly Label _goodCaption = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _goodPrice = UiTheme.Text("", 26, bold: true);
private readonly Label _goodChange = UiTheme.Text("", 14, bold: true);
private readonly SeriesChart _chart = new(250);
private readonly HBoxContainer _stats = PanelKit.Row(10);
private readonly VBoxContainer _sell = PanelKit.Column(4);
private readonly VBoxContainer _right = PanelKit.Column(14);
private readonly Dictionary<int, GoodRow> _rowByGood = [];
private readonly TradeBox _trade;
private MarketReport? _shown;
private string _rowsKey = "";
private int _selected = -1;
private long _requestedDay = long.MinValue;
private double _sinceRequest = double.MaxValue;
public event Action? CloseRequested;
/// <summary>Chiesto di pianificare una linea verso un hub (strumento binari centrato sull'hub).</summary>
public event Action<int>? PlanLineRequested;
public MarketPanel(GameSession session)
{
_session = session;
_trade = new TradeBox(session);
// dopo un comando di compravendita si chiede subito il quadro aggiornato (giacenze e prezzi)
_trade.Traded += () => _requestedDay = long.MinValue;
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
var header = PanelKit.Row(16);
var titles = PanelKit.Column(0);
titles.AddChild(UiTheme.TitleLabel(T("Mercato globale"), 40));
titles.AddChild(_subtitle);
header.AddChild(titles);
var index = PanelKit.Column(0);
index.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
index.SizeFlagsVertical = SizeFlags.ShrinkCenter;
var indexCaption = UiTheme.Text(T("Indice materie prime"), 13, Palette.TextSecondary);
indexCaption.HorizontalAlignment = HorizontalAlignment.Right;
index.AddChild(indexCaption);
var indexRow = new HBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
indexRow.AddThemeConstantOverride("separation", 8);
indexRow.AddChild(_index);
indexRow.AddChild(_indexChange);
index.AddChild(indexRow);
index.TooltipText = T("Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.");
index.MouseFilter = MouseFilterEnum.Pass;
header.AddChild(index);
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(150, 44) };
close.Pressed += () => CloseRequested?.Invoke();
header.AddChild(close);
AddChild(header);
var body = PanelKit.Row(16);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
AddChild(body);
var left = Column(body, 1.05f);
left.AddChild(TableHeader());
left.AddChild(PanelKit.Separator());
left.AddChild(_rows);
_later.AutowrapMode = TextServer.AutowrapMode.WordSmart;
left.AddChild(_later);
left.AddChild(Wrapped(T("Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub."), 12, Palette.TextSecondary));
var center = Column(body, 1.35f);
var top = PanelKit.Row(12);
var names = PanelKit.Column(0);
names.SizeFlagsHorizontal = SizeFlags.ExpandFill;
names.AddChild(_goodTitle);
names.AddChild(_goodCaption);
top.AddChild(names);
var price = PanelKit.Column(0);
price.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
_goodPrice.HorizontalAlignment = HorizontalAlignment.Right;
_goodChange.HorizontalAlignment = HorizontalAlignment.Right;
price.AddChild(_goodPrice);
price.AddChild(_goodChange);
top.AddChild(price);
center.AddChild(top);
center.AddChild(_chart);
center.AddChild(_stats);
center.AddChild(UiTheme.Text(T("Dove conviene vendere"), 16, bold: true));
center.AddChild(_sell);
var right = Column(body, 0.8f);
right.AddChild(_right);
_subtitle.Text = T("In attesa dei prezzi dal server…");
}
public override void _Notification(int what)
{
// il riquadro della compravendita fuori dall'albero (commercio non sbloccato) va liberato a mano
if (what == NotificationPredelete && IsInstanceValid(_trade) && _trade.GetParent() is null) _trade.Free();
}
/// <summary>Bene mostrato al centro (−1 se nessuno).</summary>
public int Selected => _selected;
public void Select(int good)
{
_selected = good;
foreach (var (id, row) in _rowByGood) row.SetSelected(id == good);
if (_session.World.Market is { } report)
{
ShowGood(_session.World, report);
_trade.Update(report, good, report.TradingUnlocked);
}
}
private static VBoxContainer Column(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 18));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
scroll.AddChild(margin);
var col = PanelKit.Column(12);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
public override void _Process(double delta)
{
var w = _session.World;
_sinceRequest += delta;
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
long today = Fmt.Today(w);
if (today != _requestedDay || (w.Market is null && _sinceRequest > 5))
{
_requestedDay = today;
_sinceRequest = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Market, Target = 0 });
}
if (w.Market is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
}
private void Refresh(ClientWorld w, MarketReport report)
{
_shown = report;
_subtitle.Text = $"{T("Prezzi mondiali al")} {Fmt.Date(w, report.Day)}, {T("aggiornati ogni giorno di gioco")}";
_index.Text = Fmt.Number(report.Index, 1);
SetChange(_indexChange, report.IndexChange, "");
RefreshRows(w, report);
if (_selected < 0 || report.Goods.All(g => g.Good != _selected))
_selected = report.Goods.Where(g => g.Available).Select(g => g.Good).DefaultIfEmpty(0).First();
foreach (var (id, row) in _rowByGood) row.SetSelected(id == _selected);
ShowGood(w, report);
RefreshRight(w, report);
}
// ------------------------------------------------------------------ dati di comodo (solo lettura)
private static string GoodName(ClientWorld w, int good)
{
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
private static string Unit(ClientWorld w, int good) => w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)].Unit;
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
private static string PerUnit(ClientWorld w, int good, double cents) => $"{Price(cents)} / {Unit(w, good)}";
/// <summary>Quantità intera con il punto delle migliaia («41.200»).</summary>
private static string Quantity(double units) => Fmt.Number(Math.Round(units), 0);
private static string LineName(ClientWorld w, int line) =>
w.Lines.TryGetValue(line, out var l) ? l.Name : $"{T("Linea")} {line + 1}";
/// <summary>Variazione con la freccia: ambra in salita, azzurro in discesa (immagine 06).</summary>
private static void SetChange(Label label, double change, string suffix)
{
bool up = change > 0.0005, down = change < -0.0005;
string arrow = up ? "▲ " : down ? "▼ " : "= ";
label.Text = arrow + Fmt.Pct(Math.Abs(change)) + suffix;
label.AddThemeColorOverride("font_color", up ? Palette.AmberLight : down ? Palette.Staff : Palette.TextSecondary);
}
// ------------------------------------------------------------------ elenco dei beni
private const float WPrice = 96, WChange = 86, WBars = 110;
private static Control TableHeader()
{
var row = PanelKit.Row(8);
var name = UiTheme.Text(T("Merce"), 13, Palette.TextSecondary);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
row.AddChild(name);
foreach (var (text, width) in new[] { (T("Prezzo"), WPrice), (T("30 giorni"), WChange), (T("Offerta · domanda"), WBars) })
{
var l = UiTheme.Text(text, 13, Palette.TextSecondary);
l.CustomMinimumSize = new Vector2(width, 0);
row.AddChild(l);
}
return row;
}
private void RefreshRows(ClientWorld w, MarketReport report)
{
var available = report.Goods.Where(g => g.Available).ToList();
string key = string.Join(",", available.Select(g => g.Good));
if (key != _rowsKey)
{
_rowsKey = key;
foreach (var c in _rows.GetChildren()) c.QueueFree();
_rowByGood.Clear();
foreach (var g in available)
{
int id = g.Good;
var row = new GoodRow();
row.Pressed += () => Select(id);
_rowByGood[id] = row;
_rows.AddChild(row);
}
}
foreach (var g in available)
{
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
_rowByGood[g.Good].Update(GoodName(w, g.Good), PerUnit(w, g.Good, g.Price), g.Change, supply, demand,
$"{GoodName(w, g.Good)}\n{T("Offerta")} {Quantity(supply)} {Unit(w, g.Good)}/{T("mese")} · {T("domanda")} {Quantity(demand)} {Unit(w, g.Good)}/{T("mese")}");
}
var later = report.Goods.Where(g => !g.Available).Select(g => $"{GoodName(w, g.Good)} ({w.Data.Goods[g.Good].Era})").ToList();
_later.Text = later.Count > 0 ? $"{T("Non ancora disponibili")}: {string.Join(", ", later)}" : "";
_later.Visible = later.Count > 0;
}
/// <summary>Riga di un bene: pulsante piatto con nome, prezzo, variazione e barre di offerta e domanda.</summary>
private sealed partial class GoodRow : Button
{
private readonly Label _name = UiTheme.Text("", 16, bold: true);
private readonly Label _price = UiTheme.Text("", 15);
private readonly Label _change = UiTheme.Text("", 14, bold: true);
private readonly SupplyDemandBars _bars = new();
public GoodRow()
{
CustomMinimumSize = new Vector2(0, 58);
FocusMode = FocusModeEnum.None;
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
SetSelected(false);
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
row.AddThemeConstantOverride("separation", 8);
row.SetAnchorsPreset(LayoutPreset.FullRect);
row.OffsetLeft = 12;
row.OffsetRight = -8;
AddChild(row);
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_name.ClipText = true;
_name.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
_name.CustomMinimumSize = new Vector2(24, 0);
foreach (var (l, width) in new[] { (_name, 0f), (_price, WPrice), (_change, WChange) })
{
if (width > 0) l.CustomMinimumSize = new Vector2(width, 0);
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
l.MouseFilter = MouseFilterEnum.Ignore;
row.AddChild(l);
}
_bars.CustomMinimumSize = new Vector2(WBars, 22);
_bars.SizeFlagsVertical = SizeFlags.ShrinkCenter;
row.AddChild(_bars);
}
public void SetSelected(bool on) =>
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
public void Update(string name, string price, double change, double supply, double demand, string tooltip)
{
_name.Text = name;
_price.Text = price;
SetChange(_change, change, "");
_bars.Set(supply, demand);
TooltipText = tooltip;
}
}
/// <summary>Due barre sovrapposte: offerta in azzurro, domanda in ambra, riferite alla maggiore delle due.</summary>
private sealed partial class SupplyDemandBars : Control
{
private double _supply, _demand;
public SupplyDemandBars() => MouseFilter = MouseFilterEnum.Ignore;
public void Set(double supply, double demand)
{
_supply = supply;
_demand = demand;
QueueRedraw();
}
public override void _Draw()
{
double top = Math.Max(1e-9, Math.Max(_supply, _demand) * 1.2);
float h = 6, gap = 5;
float y0 = (Size.Y - 2 * h - gap) / 2;
for (int i = 0; i < 2; i++)
{
var y = y0 + i * (h + gap);
double v = i == 0 ? _supply : _demand;
DrawRect(new Rect2(0, y, Size.X, h), Palette.Inner);
DrawRect(new Rect2(0, y, (float)(Size.X * Math.Clamp(v / top, 0, 1)), h), i == 0 ? Palette.Staff : Palette.Amber);
}
}
}
// ------------------------------------------------------------------ bene scelto
private void ShowGood(ClientWorld w, MarketReport report)
{
var g = report.Goods.FirstOrDefault(x => x.Good == _selected);
foreach (var c in _stats.GetChildren()) c.QueueFree();
foreach (var c in _sell.GetChildren()) c.QueueFree();
if (g is null)
{
_goodTitle.Text = "";
_goodCaption.Text = "";
_goodPrice.Text = "";
_goodChange.Text = "";
_chart.Show([], [], Price, SeriesChart.Style.Line, Palette.Amber, T("Scegli una merce a sinistra"));
return;
}
_goodTitle.Text = GoodName(w, g.Good);
int months = g.History.Count;
_goodCaption.Text = g.Forecast.Count > 0
? $"{T("Storico")} {months} {T("mesi e previsione a")} {g.Forecast.Count} {T("mesi")}"
: $"{T("Storico")} {months} {T("mesi")}";
_goodPrice.Text = PerUnit(w, g.Good, g.Price);
SetChange(_goodChange, g.Change, " " + T("in 30 giorni"));
var labels = g.History.Select((p, i) => i == g.History.Count - 1 ? "" : MonthLabel(w, p.Day)).ToList();
_chart.ShowWithForecast(g.History.Select(p => p.Price).ToList(), labels,
g.Forecast.Select(f => f.Price).ToList(), g.Forecast.Select(f => f.Low).ToList(), g.Forecast.Select(f => f.High).ToList(),
Price, Palette.Amber, T("Lo storico si forma giorno dopo giorno"), T("oggi"), g.Forecast.Count > 0 ? T("prev.") : "");
_chart.TooltipText = T("Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.");
_chart.MouseFilter = MouseFilterEnum.Pass;
string unit = Unit(w, g.Good);
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
AddStat(T("Offerta globale"), $"{Quantity(supply)} {unit}/{T("mese")}",
$"{T("Produzione della mappa")} {Quantity(g.SupplyMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldSupplyMonth)} {unit}");
AddStat(T("Domanda globale"), $"{Quantity(demand)} {unit}/{T("mese")}",
$"{T("Consumi della mappa")} {Quantity(g.DemandMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldDemandMonth)} {unit}");
AddStat(T("Scorte"), g.StockMonths < 0 ? "—" : $"{Fmt.Number(g.StockMonths, 1)} {T("mesi")}",
$"{Quantity(g.StockUnits)} {unit} {T("nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa")}");
if (!g.Available)
{
_sell.AddChild(Wrapped($"{T("Disponibile dal")} {w.Data.Goods[g.Good].Era}.", 13, Palette.TextSecondary));
return;
}
if (g.SellPlaces.Count == 0)
{
_sell.AddChild(Wrapped(T("Nessuna industria consuma questa merce e nessun hub la compra."), 13, Palette.TextSecondary));
return;
}
for (int i = 0; i < g.SellPlaces.Count; i++) _sell.AddChild(SellRow(w, g, g.SellPlaces[i], i == 0));
_sell.AddChild(Wrapped(T("Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. Il trasporto è a parte."), 12, Palette.TextSecondary));
}
private static string MonthLabel(ClientWorld w, long day)
{
if (w.Calendar is not { } c) return "";
var date = c.DateOfDay(Math.Max(0, day));
string[] months = [T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
return $"{months[Math.Clamp(date.Month, 1, 12) - 1]} {date.Year}";
}
private void AddStat(string caption, string value, string tooltip)
{
var stat = PanelKit.Stat(caption, PanelKit.Value(value));
stat.TooltipText = tooltip;
stat.MouseFilter = MouseFilterEnum.Pass;
_stats.AddChild(stat);
}
private static Control SellRow(ClientWorld w, GoodMarketInfo g, SellPlaceInfo p, bool best)
{
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", best ? UiTheme.Box(Palette.Inner, Palette.Inner, 6, 12) : UiTheme.Box(Palette.Panel, Palette.Panel, 6, 12));
var row = PanelKit.Row(10);
box.AddChild(row);
string name = p.Kind == SellPlaceInfo.Hub
? $"{(w.Hubs.TryGetValue(p.Target, out var hub) ? hub.Name : "#" + p.Target)}, {T("esportazione")}"
: w.Industries.TryGetValue(p.Target, out var ind) ? ind.Name : "#" + p.Target;
var label = UiTheme.Text(name, 14);
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
label.ClipText = true;
label.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
label.CustomMinimumSize = new Vector2(24, 0);
row.AddChild(label);
var price = UiTheme.Text(PerUnit(w, g.Good, p.Price), 14, bold: true);
price.CustomMinimumSize = new Vector2(110, 0);
row.AddChild(price);
var line = UiTheme.Text(p.Line >= 0 ? LineName(w, p.Line) : T("non collegato"), 14, p.Line >= 0 ? Palette.TextSecondary : Palette.Amber);
line.CustomMinimumSize = new Vector2(130, 0);
line.ClipText = true;
line.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
row.AddChild(line);
box.TooltipText = p.Line >= 0
? $"{name}: {T("servita dalla tua linea")} {LineName(w, p.Line)}"
: $"{name}: {T("nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino")}";
return box;
}
// ------------------------------------------------------------------ colonna destra
private void RefreshRight(ClientWorld w, MarketReport report)
{
// il riquadro della compravendita resta lo stesso nodo tra un quadro e l'altro
_trade.GetParent()?.RemoveChild(_trade);
foreach (var c in _right.GetChildren()) c.QueueFree();
foreach (var h in report.Hubs) _right.AddChild(HubCard(w, h));
_right.AddChild(EventCard(w, report));
_right.AddChild(TradingCard(w, report));
}
private Control HubCard(ClientWorld w, HubMarketInfo h)
{
var card = Card(Palette.Inner, Palette.Border);
var col = (VBoxContainer)card.GetChild(0);
var title = PanelKit.Row(8);
var name = UiTheme.Text(w.Hubs.TryGetValue(h.Hub, out var info) ? info.Name : $"Hub {h.Hub}", 17, bold: true);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
name.AutowrapMode = TextServer.AutowrapMode.WordSmart;
title.AddChild(name);
bool connected = h.Line >= 0;
title.AddChild(UiTheme.Text(connected ? T("collegato") : T("non collegato"), 13, connected ? Palette.Ok : Palette.Amber));
col.AddChild(title);
bool port = h.Kind == 0;
col.AddChild(Wrapped(port ? T("Hub verso il mercato mondiale via mare") : T("Hub verso il mercato mondiale via terra"), 13, Palette.TextSecondary));
col.AddChild(PanelKit.Pair(T("Capacità"), PanelKit.Value($"{Fmt.Number(h.MonthlyCapacity, 0)} {T("unità/mese")}")));
col.AddChild(PanelKit.Pair(T("Dazio"), PanelKit.Value(Fmt.Pct(h.Duty, 0))));
double used = h.MonthlyCapacity > 0 ? Math.Clamp((double)h.UsedThisMonth / h.MonthlyCapacity, 0, 1) : 0;
col.AddChild(Bar(used, Palette.Workers));
col.AddChild(UiTheme.Text($"{T("Capacità usata questo mese")}: {Fmt.Pct(used, 0)}", 12, Palette.TextSecondary));
if (connected)
{
col.AddChild(UiTheme.Text($"{T("Servito da")} {LineName(w, h.Line)}", 12, Palette.TextSecondary));
}
else
{
col.AddChild(Wrapped(port ? T("Porta i binari fino al porto per comprare e vendere via mare.") : T("Porta i binari fino al confine per comprare e vendere via terra."), 13, Palette.TextSecondary));
var plan = new Button { Text = T("Pianifica la linea"), CustomMinimumSize = new Vector2(0, 40) };
int hub = h.Hub;
plan.Pressed += () => PlanLineRequested?.Invoke(hub);
col.AddChild(plan);
}
return card;
}
private static Control EventCard(ClientWorld w, MarketReport report)
{
var card = Card(Palette.Inner, Palette.Inner);
var col = (VBoxContainer)card.GetChild(0);
if (report.EventGood < 0 && report.GoodEvents.Count == 0)
{
col.AddChild(UiTheme.Text(T("Nessun evento in corso"), 13, Palette.TextSecondary, bold: true));
col.AddChild(Wrapped(T("I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse."), 13, Palette.TextSecondary));
return card;
}
col.AddChild(UiTheme.Text(T("Evento in corso"), 13, Palette.AmberLight, bold: true));
// eventi del mondo sulla domanda di un bene in una zona (ADR 0017)
foreach (var e in report.GoodEvents)
{
col.AddChild(Wrapped($"{GoodName(w, e.Good)}: {WorldEventText.Name(w, e).ToLowerInvariant()} {WorldEventText.Where(w, e)}", 17, Palette.Text, bold: true));
col.AddChild(Wrapped($"{WorldEventText.Effects(w, e)}, {WorldEventText.Until(w, e)}.", 13, Palette.Text));
}
if (report.EventGood < 0) return card;
bool up = report.EventShock > 0;
string good = GoodName(w, report.EventGood);
col.AddChild(Wrapped(up ? $"{good}: {T("prezzo mondiale in rialzo")}" : $"{good}: {T("prezzo mondiale in calo")}", 17, Palette.Text, bold: true));
int months = Math.Max(1, (int)Math.Ceiling(report.EventMonths));
col.AddChild(Wrapped($"{T("Il prezzo mondiale di")} {good.ToLowerInvariant()} {(up ? T("è più alto del") : T("è più basso del"))} {Fmt.Pct(Math.Abs(report.EventShock), 0)} " +
$"{T("rispetto al ciclo per circa")} {months} {(months == 1 ? T("mese") : T("mesi"))}.", 13, Palette.Text));
return card;
}
private Control TradingCard(ClientWorld w, MarketReport report)
{
var card = Card(Palette.Panel, Palette.Border);
var col = (VBoxContainer)card.GetChild(0);
col.AddChild(UiTheme.Text(T("Compravendita in proprio"), 17, bold: true));
string tier = report.TradingTier > 0 ? Fmt.Tier(w, report.TradingTier) : "—";
if (report.TradingUnlocked)
{
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello")} {tier}.", 13, Palette.Text));
col.AddChild(_trade);
_trade.Update(report, _selected);
return card;
}
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
col.AddChild(Bar(report.TradingProgress, Palette.Amber));
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Pct(report.TradingProgress, 0)}", 12, Palette.TextSecondary));
// merce già in magazzino (per esempio ereditata da una fusione): si vende e si spedisce anche senza lo sblocco
if (report.Warehouses.Any(h => h.Incoming > 0 || h.Goods.Any(g => g.Units > 0)))
{
col.AddChild(Wrapped(T("Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra."), 13, Palette.Text));
col.AddChild(_trade);
_trade.Update(report, _selected, buyAllowed: false);
}
col.AddChild(Requirement($"{T("Patrimonio netto")} {report.NetWorth.ToString("short")} / {report.NetWorthRequired.ToString("short")}",
report.NetWorth.Cents >= report.NetWorthRequired.Cents));
col.AddChild(Requirement($"{T("Città collegate oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}: {report.TownsConnected} / {report.TownsRequired}",
report.TownsConnected >= report.TownsRequired));
col.AddChild(Requirement($"{T("Rating")} {report.Rating} ({T("serve")} {report.RatingRequired})", report.RatingMet));
return card;
}
// ------------------------------------------------------------------ mattoni
private static PanelContainer Card(Color background, Color border)
{
var card = new PanelContainer();
card.AddThemeStyleboxOverride("panel", UiTheme.Box(background, border, 10, 18));
card.AddChild(PanelKit.Column(8));
return card;
}
private static ProgressBar Bar(double fraction, Color color)
{
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 4, 0));
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
return bar;
}
private static Label Requirement(string text, bool met)
{
var l = UiTheme.Text((met ? "✓ " : "· ") + text, 12, met ? Palette.Ok : Palette.TextSecondary);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
{
var l = UiTheme.Text(text, size, color, bold);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -1,7 +1,7 @@
using Godot;
using ViaFerrea.Client.App;
using RailEnterprise.Client.App;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>Mattoni comuni dei pannelli laterali.</summary>
public static class PanelKit
@@ -1,9 +1,9 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Rail;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Map;
using RailEnterprise.Core.Rail;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>Grafico altimetrico del tracciato: terreno, quota del binario e opere colorate (pannello TrackProfile).</summary>
public partial class ProfileChart : Control
@@ -1,12 +1,13 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni e
/// delle merci (con la previsione tratteggiata e la sua banda, immagine 06), barre per il
/// patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// </summary>
public partial class SeriesChart : Control
{
@@ -18,6 +19,8 @@ public partial class SeriesChart : Control
private Style _style;
private Color _color = Palette.Amber;
private string _empty = "";
private IReadOnlyList<double> _forecast = [], _low = [], _high = [];
private string _todayLabel = "", _forecastLabel = "";
public SeriesChart(float height = 150)
{
@@ -34,9 +37,27 @@ public partial class SeriesChart : Control
_style = style;
_color = color;
_empty = empty;
_forecast = _low = _high = [];
QueueRedraw();
}
/// <summary>
/// Serie a linea seguita dalla previsione (prezzi, banda bassa e alta), un punto per passo
/// dopo l'ultimo valore; una riga verticale segna «oggi».
/// </summary>
public void ShowWithForecast(IReadOnlyList<double> values, IReadOnlyList<string> labels, IReadOnlyList<double> forecast,
IReadOnlyList<double> low, IReadOnlyList<double> high, Func<double, string> format, Color color, string empty,
string todayLabel, string forecastLabel)
{
Show(values, labels, format, Style.Line, color, empty);
bool consistent = forecast.Count == low.Count && forecast.Count == high.Count;
_forecast = consistent ? forecast : [];
_low = consistent ? low : [];
_high = consistent ? high : [];
_todayLabel = todayLabel;
_forecastLabel = forecastLabel;
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
@@ -50,6 +71,11 @@ public partial class SeriesChart : Control
return;
}
double min = _values.Min(), max = _values.Max();
if (_style == Style.Line && _forecast.Count > 0)
{
min = Math.Min(min, _low.Min());
max = Math.Max(max, _high.Max());
}
if (_style == Style.Bars) min = Math.Min(0, min);
if (max - min < 1e-9)
{
@@ -84,12 +110,14 @@ public partial class SeriesChart : Control
return;
}
float step = area.Size.X / (n - 1);
int f = _forecast.Count;
float step = area.Size.X / (n - 1 + f);
var points = new Vector2[n];
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
var fill = new List<Vector2>(points) { new(points[^1].X, area.End.Y), new(area.Position.X, area.End.Y) };
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
DrawPolyline(points, _color, 2.5f, true);
if (f > 0) DrawForecast(area, points[^1], step, Y, font, fontSize);
DrawCircle(points[^1], 4, Palette.AmberLight);
string last = _format(_values[^1]);
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
@@ -99,6 +127,37 @@ public partial class SeriesChart : Control
DrawLabels(area, n, step, font, fontSize, centered: false);
}
/// <summary>Previsione: banda chiara, linea tratteggiata e riga verticale di «oggi».</summary>
private void DrawForecast(Rect2 area, Vector2 today, float step, Func<double, float> y, Font font, int fontSize)
{
int f = _forecast.Count;
var band = new List<Vector2> { today };
for (int i = 0; i < f; i++) band.Add(new Vector2(today.X + step * (i + 1), y(_high[i])));
for (int i = f - 1; i >= 0; i--) band.Add(new Vector2(today.X + step * (i + 1), y(_low[i])));
DrawColoredPolygon(band.ToArray(), Palette.WithAlpha(Palette.Workers, 0.22f));
var previous = today;
for (int i = 0; i < f; i++)
{
var next = new Vector2(today.X + step * (i + 1), y(_forecast[i]));
DrawDashedLine(previous, next, Palette.Staff, 2f, 6f);
previous = next;
}
DrawDashedLine(new Vector2(today.X, area.Position.Y), new Vector2(today.X, area.End.Y), Palette.TextSecondary, 1f, 4f);
if (_todayLabel.Length > 0)
{
// in cima alla riga verticale: in basso si sovrapporrebbe alle etichette dei mesi
var dims = font.GetStringSize(_todayLabel, HorizontalAlignment.Left, -1, fontSize);
float x = Math.Min(today.X + 4, Size.X - dims.X - 4);
DrawString(font, new Vector2(x, area.Position.Y + fontSize), _todayLabel, HorizontalAlignment.Left, -1, fontSize, Palette.Text);
}
if (_forecastLabel.Length > 0)
{
var dims = font.GetStringSize(_forecastLabel, HorizontalAlignment.Left, -1, fontSize);
DrawString(font, new Vector2(Math.Min(area.End.X - dims.X / 2, Size.X - dims.X - 4), area.End.Y + 16), _forecastLabel,
HorizontalAlignment.Left, -1, fontSize, Palette.Staff);
}
}
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
{
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>Strumento stazione: numero di binari, nome facoltativo, costo stimato; clic sulla mappa per posarla.</summary>
public partial class StationPanel : VBoxContainer
@@ -78,39 +78,6 @@ public partial class HelpPanel : VBoxContainer
}
}
/// <summary>Prezzi globali del giorno (resoconto giornaliero).</summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _rows = PanelKit.Column(4);
private long _day = -1;
public MarketPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Mercato"), 34));
AddChild(UiTheme.Text(T("Prezzi globali di oggi (la borsa arriva in seguito)."), 13, Palette.TextSecondary));
AddChild(_rows);
}
public override void _Process(double delta)
{
var digest = _session.World.LastDigest;
if (digest is null || digest.Day == _day) return;
_day = digest.Day;
foreach (var c in _rows.GetChildren()) c.QueueFree();
var goods = _session.World.Data.Goods;
for (int g = 0; g < Math.Min(goods.Count, digest.Prices.Count); g++)
{
var ratio = digest.Prices[g].Cents / (double)Math.Max(1, goods[g].BasePrice);
var value = PanelKit.Value($"{digest.Prices[g]} / {goods[g].Unit}");
value.AddThemeColorOverride("font_color", ratio > 1.15 ? Palette.AmberLight : ratio < 0.85 ? Palette.Staff : Palette.Text);
_rows.AddChild(PanelKit.Pair(goods[g].NameIt, value));
}
}
}
/// <summary>Conti della compagnia e prestiti.</summary>
public partial class FinancePanel : VBoxContainer
{
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Strumento binari: classe, ponti, gallerie, doppio binario, elettrificazione e quota; anteprima
@@ -0,0 +1,236 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Riquadro «Compravendita in proprio» del Mercato globale, quando il livello lo sblocca (ADR 0016):
/// scelta della stazione propria, quantità, Compra, Vendi e Spedisci a un'altra stazione per la
/// merce scelta nel pannello; giacenze del magazzino. Prezzi, disponibilità e giacenze arrivano dal
/// server nel MarketReport: i comandi li ricalcola il server. I controlli restano gli stessi tra un
/// quadro e l'altro, così le scelte non si perdono a ogni nuovo giorno.
/// </summary>
public sealed partial class TradeBox : VBoxContainer
{
/// <summary>Margine sul prezzo mostrato: si compra fino al 10 % sopra e si vende fino al 10 % sotto.</summary>
private const double PriceTolerance = 0.10;
private readonly GameSession _session;
private readonly OptionButton _station = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly OptionButton _destination = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly SpinBox _quantity = new() { MinValue = 1, MaxValue = 100_000, Step = 1, Rounded = true, Value = 50, SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Label _good = UiTheme.Text("", 14, bold: true);
private readonly Label _quote = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _capacity = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly VBoxContainer _stock = PanelKit.Column(2);
private readonly Label _status = UiTheme.Text("", 12);
private readonly Button _buy = UiTheme.Primary(T("Compra"));
private readonly Button _sell = new() { Text = T("Vendi") };
private readonly Button _ship = new() { Text = T("Spedisci a") };
private readonly List<int> _stationIds = [];
private readonly List<int> _destinationIds = [];
private MarketReport? _report;
private int _goodId = -1;
private bool _buyAllowed = true;
/// <summary>Esito di un comando: il pannello chiede subito un quadro aggiornato.</summary>
public event Action? Traded;
public TradeBox(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
foreach (var l in new[] { _quote, _capacity, _status }) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
var station = PanelKit.Row(6);
station.AddChild(UiTheme.Text(T("Stazione"), 13, Palette.TextSecondary));
station.AddChild(_station);
AddChild(station);
_station.ItemSelected += _ =>
{
PickDestination(SelectedDestination);
Render();
};
AddChild(_good);
AddChild(_quote);
var qty = PanelKit.Row(6);
qty.AddChild(UiTheme.Text(T("Quantità"), 13, Palette.TextSecondary));
qty.AddChild(_quantity);
AddChild(qty);
var trade = PanelKit.Row(6);
_buy.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_sell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_buy.TooltipText = T("Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.");
_sell.TooltipText = T("Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.");
_buy.Pressed += Buy;
_sell.Pressed += Sell;
trade.AddChild(_buy);
trade.AddChild(_sell);
AddChild(trade);
var ship = PanelKit.Row(6);
_ship.TooltipText = T("Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.");
_ship.Pressed += Ship;
ship.AddChild(_ship);
ship.AddChild(_destination);
AddChild(ship);
AddChild(_capacity);
AddChild(UiTheme.Text(T("In magazzino"), 13, Palette.TextSecondary, bold: true));
AddChild(_stock);
AddChild(_status);
}
/// <summary>
/// Aggiorna stazioni, quotazioni e giacenze dal quadro ricevuto, per la merce scelta. Senza lo
/// sblocco del livello (<paramref name="buyAllowed"/> falso) si vende e si spedisce solo la merce
/// già in magazzino, per esempio quella ereditata da una fusione.
/// </summary>
public void Update(MarketReport report, int good, bool buyAllowed = true)
{
_report = report;
_goodId = good;
_buyAllowed = buyAllowed;
var w = _session.World;
int keep = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
int keepTo = SelectedDestination;
_stationIds.Clear();
_station.Clear();
foreach (var h in report.Warehouses)
{
_stationIds.Add(h.Station);
_station.AddItem(StationName(w, h.Station));
}
int index = _stationIds.IndexOf(keep);
if (_stationIds.Count > 0) _station.Select(index >= 0 ? index : 0);
_destinationIds.Clear();
_destination.Clear();
foreach (var h in report.Warehouses)
{
_destinationIds.Add(h.Station);
_destination.AddItem(StationName(w, h.Station));
}
PickDestination(keepTo);
Render();
}
private int SelectedDestination =>
_destination.Selected >= 0 && _destination.Selected < _destinationIds.Count ? _destinationIds[_destination.Selected] : -1;
/// <summary>
/// Mantiene la stazione di arrivo scelta se è ancora nell'elenco e diversa da quella di partenza,
/// altrimenti sceglie la prima diversa dalla partenza.
/// </summary>
private void PickDestination(int keep)
{
if (_destinationIds.Count == 0) return;
int from = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
int to = _destinationIds.IndexOf(keep);
if (to < 0 || _destinationIds[to] == from) to = _destinationIds.FindIndex(id => id != from);
_destination.Select(to >= 0 ? to : 0);
}
private WarehouseInfo? Current =>
_report is null || _station.Selected < 0 || _station.Selected >= _stationIds.Count
? null
: _report.Warehouses.FirstOrDefault(h => h.Station == _stationIds[_station.Selected]);
private WarehouseGoodInfo? CurrentGood => Current?.Goods.FirstOrDefault(g => g.Good == _goodId);
private void Render()
{
var w = _session.World;
foreach (var c in _stock.GetChildren()) c.QueueFree();
var house = Current;
bool any = house is not null && _goodId >= 0 && _goodId < w.Data.Goods.Count;
_buy.Disabled = _sell.Disabled = _ship.Disabled = !any;
if (!any)
{
_good.Text = "";
_quote.Text = T("Costruisci una stazione per avere un magazzino dove comprare e vendere.");
_capacity.Text = "";
return;
}
string unit = w.Data.Goods[_goodId].Unit;
var g = CurrentGood;
_good.Text = $"{T("Merce")}: {GoodName(w, _goodId)} · {T("in magazzino")} {g?.Units ?? 0} {unit}";
string buy = g is { BuyPrice: >= 0 }
? $"{T("Si compra a")} {Price(g.BuyPrice)}/{unit} ({Fmt.Number(g.BuyUnits, 0)} {unit} {T("disponibili")})"
: T("Nessun produttore né hub nel bacino la vende");
string sell = g is { SellPrice: >= 0 }
? $"{T("si vende a")} {Price(g.SellPrice)}/{unit} ({Fmt.Number(g.SellUnits, 0)} {unit} {T("richieste")})"
: T("nessun consumatore né hub nel bacino la compra");
_quote.Text = $"{buy}; {sell}. {T("Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.")}";
_buy.Disabled = !_buyAllowed || g is not { BuyPrice: >= 0 };
_sell.Disabled = g is not { SellPrice: >= 0 } || g.Units <= 0;
_ship.Disabled = (g?.Units ?? 0) <= 0 || _destinationIds.Count < 2;
int used = house!.Goods.Sum(x => x.Units) + house.Incoming;
_capacity.Text = $"{T("Magazzino")}: {Fmt.Number(used, 0)} / {Fmt.Number(house.Capacity, 0)} {T("unità")}"
+ (house.Incoming > 0 ? $" ({T("di cui")} {Fmt.Number(house.Incoming, 0)} {T("in arrivo")})" : "");
var held = house.Goods.Where(x => x.Units > 0).ToList();
if (held.Count == 0) _stock.AddChild(UiTheme.Text(T("Vuoto"), 12, Palette.TextSecondary));
foreach (var x in held)
_stock.AddChild(PanelKit.Pair(GoodName(w, x.Good), PanelKit.Value($"{Fmt.Number(x.Units, 0)} {w.Data.Goods[x.Good].Unit}")));
}
private void Buy()
{
if (Current is not { } house || CurrentGood is not { BuyPrice: >= 0 } g) return;
var max = Money.FromCentsRounded(g.BuyPrice * (1 + PriceTolerance));
_session.Command(new BuyGoodsCommand(new StationId(house.Station), GoodId(), Units(), max), Result);
}
private void Sell()
{
if (Current is not { } house || CurrentGood is not { SellPrice: >= 0 } g) return;
var min = Money.FromCentsRounded(g.SellPrice * (1 - PriceTolerance));
_session.Command(new SellGoodsCommand(new StationId(house.Station), GoodId(), Units(), min), Result);
}
private void Ship()
{
if (Current is not { } house || _destination.Selected < 0 || _destination.Selected >= _destinationIds.Count) return;
int to = _destinationIds[_destination.Selected];
if (to == house.Station)
{
ShowStatus(T("Scegli una stazione di arrivo diversa da quella di partenza"), false);
return;
}
_session.Command(new ShipGoodsCommand(new StationId(house.Station), new StationId(to), GoodId(), Units()), Result);
}
private string GoodId() => _session.World.Data.Goods[_goodId].Id;
private int Units() => (int)Math.Max(1, Math.Round(_quantity.Value));
private void Result(CommandResultMessage r)
{
ShowStatus(r.Message, r.Ok);
Traded?.Invoke();
}
private void ShowStatus(string text, bool ok)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", ok ? Palette.Ok : Palette.Danger);
}
private static string StationName(ClientWorld w, int station) =>
w.Stations.TryGetValue(station, out var s) ? s.Name : $"{T("Stazione")} {station}";
private static string GoodName(ClientWorld w, int good)
{
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
}
@@ -1,14 +1,14 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
@@ -0,0 +1,138 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Data;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Testi degli eventi del mondo in corso (ADR 0017) per l'elenco «Eventi in corso», le schede delle
/// entità e il Mercato globale. Solo presentazione: i valori dei moltiplicatori arrivano dal server.
/// </summary>
public static class WorldEventText
{
// codici di EntityKind del protocollo
private const byte TownEntity = 1, IndustryEntity = 2, DepotEntity = 7;
private static bool English => TranslationServer.GetLocale().StartsWith("en");
public static WorldEventDef? Def(ClientWorld w, WorldEventInfo e) => w.Data.Events.Events.FirstOrDefault(d => d.Id == e.Type);
/// <summary>Nome del tipo di evento nella lingua dell'interfaccia.</summary>
public static string Name(ClientWorld w, WorldEventInfo e) =>
Def(w, e) is { } d ? (English ? d.NameEn : d.NameIt) : e.Type;
/// <summary>Nome dell'entità coinvolta (città, industria, deposito).</summary>
public static string Target(ClientWorld w, WorldEventInfo e) => e.Entity switch
{
TownEntity => w.Towns.TryGetValue(e.EntityIndex, out var t) ? t.Name : "?",
IndustryEntity => w.Industries.TryGetValue(e.EntityIndex, out var i) ? i.Name : "?",
DepotEntity => w.Depots.TryGetValue(e.EntityIndex, out var d) ? d.Name : "?",
_ => "?",
};
public static string GoodName(ClientWorld w, int good)
{
if (good < 0 || good >= w.Data.Goods.Count) return "";
var def = w.Data.Goods[good];
return English ? def.NameEn : def.NameIt;
}
/// <summary>Effetti con il loro valore («Produzione 25%», «Velocità dei treni 80%»).</summary>
public static string Effects(ClientWorld w, WorldEventInfo e)
{
var def = Def(w, e);
if (def is null) return "";
var parts = new List<string>();
for (int i = 0; i < def.Effects.Count && i < e.Effects.Length; i++)
{
string label = def.Effects[i].Kind switch
{
EventEffectKind.IndustryCapacity => T("Capacità produttiva"),
EventEffectKind.TownDemand => T("Consumi della città"),
EventEffectKind.GoodDemand => $"{T("Domanda di")} {GoodName(w, e.Good).ToLowerInvariant()}",
EventEffectKind.Attendance => T("Presenze al lavoro"),
EventEffectKind.TrainSpeed => T("Velocità dei treni"),
EventEffectKind.TrackWear => T("Usura dei binari"),
_ => "",
};
parts.Add($"{label} {Fmt.Pct(e.Effects[i], 0)}");
}
return string.Join(" · ", parts);
}
/// <summary>Zona dell'evento («entro 12 km da Valdoria») per area e domanda di un bene.</summary>
public static string Where(ClientWorld w, WorldEventInfo e)
{
var def = Def(w, e);
string target = Target(w, e);
return def?.RadiusKm is { } km ? $"{T("entro")} {Fmt.Number(km, 0)} km {T("da")} {target}" : target;
}
/// <summary>
/// Scadenza: ultimo giorno dell'evento (EndDay − 1) e giorni che restano, oggi compreso. Il server
/// toglie l'evento il mattino di EndDay, quindi il conto va dalla durata estratta a 1. Un evento
/// estratto oggi inizia domani: si dice da quando, con la sua durata.
/// </summary>
public static string Until(ClientWorld w, WorldEventInfo e)
{
long today = Fmt.Today(w);
string until = $"{T("fino al")} {Fmt.Date(w, e.EndDay - 1)}";
if (e.StartDay > today)
{
string from = e.StartDay == today + 1 ? T("da domani") : $"{T("dal")} {Fmt.Date(w, e.StartDay)}";
return $"{from} {until} ({Days(e.EndDay - e.StartDay)})";
}
return $"{until} ({Days(Math.Max(1, e.EndDay - today))})";
}
private static string Days(long n) => $"{n} {(n == 1 ? T("giorno") : T("giorni"))}";
/// <summary>Colore della gravità: opportunità in verde, avvisi in ambra, critici in rosso.</summary>
public static Color Color(WorldEventInfo e) => e.Severity switch
{
1 => Palette.Ok,
2 => Palette.AmberLight,
3 => Palette.Danger,
_ => Palette.Text,
};
/// <summary>Riga compatta: titolo, luogo, effetti e scadenza.</summary>
public static Control Row(ClientWorld w, WorldEventInfo e)
{
var col = PanelKit.Column(2);
col.AddChild(UiTheme.Text($"{Name(w, e)} · {Where(w, e)}", 14, Color(e), bold: true));
var effects = UiTheme.Text(Effects(w, e), 12, Palette.Text);
effects.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(effects);
col.AddChild(UiTheme.Text(Until(w, e), 12, Palette.TextSecondary));
return col;
}
/// <summary>
/// Eventi che riguardano un'entità: bersaglio diretto oppure, per una città, zona (maltempo,
/// domanda di un bene) che la contiene. Come sul server, una città è nella zona se dista dalla città
/// centro al più il raggio del catalogo.
/// </summary>
public static IEnumerable<WorldEventInfo> For(ClientWorld w, byte entity, int index) =>
(w.LastDigest?.WorldEvents ?? []).Where(e => (e.Entity == entity && e.EntityIndex == index) || (entity == TownEntity && InZone(w, e, index)));
private static bool InZone(ClientWorld w, WorldEventInfo e, int town)
{
if (e.Entity != TownEntity || Def(w, e)?.RadiusKm is not { } km) return false;
if (!w.Towns.TryGetValue(town, out var t) || !w.Towns.TryGetValue(e.EntityIndex, out var center)) return false;
double r = km * 1000;
return (t.Position - center.Position).LengthSquared <= r * r;
}
/// <summary>Avvisi «Evento in corso» per la scheda dell'entità.</summary>
public static void AddNotices(ClientWorld w, Control into, byte entity, int index)
{
foreach (var e in For(w, entity, index))
into.AddChild(UiTheme.Notice($"{T("Evento in corso")}: {Name(w, e)} · {Effects(w, e)} · {Until(w, e)}"));
}
public const byte Town = TownEntity, Industry = IndustryEntity, Depot = DepotEntity;
}
@@ -1,11 +1,11 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Panels;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Panels;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Cronaca finale (12.3), a tutto schermo sopra la partita: storia della compagnia anno per anno
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more