Compare commits
58
Commits
f6c2a17b4d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78c934e916 | ||
|
|
bc873360c1 | ||
|
|
27fc1e920e | ||
|
|
5acb8d6d2b | ||
|
|
f275c67688 | ||
|
|
b0191e4b93 | ||
|
|
67a3dd05f9 | ||
|
|
3d394c01d3 | ||
|
|
4bea03ab6b | ||
|
|
69416e7db8 | ||
|
|
4beedd2e75 | ||
|
|
19a3dd3af1 | ||
|
|
1579f63287 | ||
|
|
64209afd5f | ||
|
|
2e781bbba2 | ||
|
|
767661957b | ||
|
|
fe97cf4616 | ||
|
|
0667a4a544 | ||
|
|
c84c16605e | ||
|
|
4ce3912f03 | ||
|
|
b7737455c6 | ||
|
|
ebe4308e75 | ||
|
|
e1d47fff54 | ||
|
|
e75c8e1586 | ||
|
|
45462bf9ec | ||
|
|
f7c286bf1d | ||
|
|
b1ee6879a7 | ||
|
|
7eec322202 | ||
|
|
8b3a9bdb9c | ||
|
|
1f8830337a | ||
|
|
9bf64b9286 | ||
|
|
c041afd8f7 | ||
|
|
2e5215c570 | ||
|
|
d473e21708 | ||
|
|
a61bf1dc27 | ||
|
|
640d4423d7 | ||
|
|
208faf625f | ||
|
|
d6b631405b | ||
|
|
357a743e91 | ||
|
|
5abf3645bb | ||
|
|
dafe9f6d11 | ||
|
|
5a4a156d52 | ||
|
|
1f8da87e51 | ||
|
|
b258e0858a | ||
|
|
596ce2c376 | ||
|
|
e157dd77bc | ||
|
|
3f00acb994 | ||
|
|
b2de314d7c | ||
|
|
2992e7cc36 | ||
|
|
bfbdb6297e | ||
|
|
6333d1b663 | ||
|
|
10a508e719 | ||
|
|
83316d4c8d | ||
|
|
8bef6551e4 | ||
|
|
9f6747efe9 | ||
|
|
e57231b15a | ||
|
|
f377913a62 | ||
|
|
c1a0049bcf |
No files matched your search
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
@@ -428,11 +428,11 @@ FodyWeavers.xsd
|
|||||||
*.msm
|
*.msm
|
||||||
*.msp
|
*.msp
|
||||||
|
|
||||||
# --- Via Ferrea ---
|
# --- Rail Enterprise ---
|
||||||
# Godot
|
# Godot
|
||||||
.godot/
|
.godot/
|
||||||
client/ViaFerrea.Client/.godot/
|
client/RailEnterprise.Client/.godot/
|
||||||
client/ViaFerrea.Client/export/
|
client/RailEnterprise.Client/export/
|
||||||
# Output degli strumenti e dei test
|
# Output degli strumenti e dei test
|
||||||
/out/
|
/out/
|
||||||
/artifacts/
|
/artifacts/
|
||||||
@@ -442,6 +442,6 @@ docker/data/
|
|||||||
# Salvataggi locali di sviluppo
|
# Salvataggi locali di sviluppo
|
||||||
/saves/
|
/saves/
|
||||||
# Dati copiati nel progetto Godot dalla build del client
|
# Dati copiati nel progetto Godot dalla build del client
|
||||||
client/ViaFerrea.Client/data/
|
client/RailEnterprise.Client/data/
|
||||||
# Traduzioni generate da Godot importando strings.csv
|
# Traduzioni generate da Godot importando strings.csv
|
||||||
client/ViaFerrea.Client/assets/i18n/*.translation
|
client/RailEnterprise.Client/assets/i18n/*.translation
|
||||||
@@ -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.
|
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.
|
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/build.sh # check-nuget + build Release della soluzione
|
||||||
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
|
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
|
||||||
dotnet run --project tests/ViaFerrea.Tests -- --list
|
dotnet run --project tests/RailEnterprise.Tests -- --list
|
||||||
dotnet run --project src/ViaFerrea.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
|
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, balance, bench, replay
|
||||||
```
|
```
|
||||||
|
|
||||||
## Regole non negoziabili
|
## Regole non negoziabili
|
||||||
@@ -25,14 +25,21 @@ dotnet run --project src/ViaFerrea.Tools -- <comando> # validate-data, genmap,
|
|||||||
## Flusso di lavoro
|
## 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>`.
|
- 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)]`.
|
- 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
|
## Mappa del codice
|
||||||
|
|
||||||
- `src/ViaFerrea.Core` — Common, Time, Data, Map, Economy, Rail, Commands, Simulation, Persistence (vedi `docs/ARCHITECTURE.md`).
|
- `src/RailEnterprise.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/RailEnterprise.Protocol` — frame e messaggi (vedi `docs/PROTOCOL.md`).
|
||||||
- `src/ViaFerrea.Server` — GameLoop, sessioni WebSocket, API HTTP.
|
- `src/RailEnterprise.Server` — GameLoop, sessioni WebSocket, API HTTP.
|
||||||
- `src/ViaFerrea.Tools` — `viaferrea-tools`.
|
- `src/RailEnterprise.Tools` — `railenterprise-tools`.
|
||||||
- `client/ViaFerrea.Client` — progetto Godot.
|
- `client/RailEnterprise.Client` — progetto Godot.
|
||||||
- `reference/` — immagini di riferimento visivo vincolanti.
|
- `reference/` — immagini di riferimento visivo vincolanti (01–09: mappa, binari, treni, edifici, palette, mercato, industria, scalata, connessione).
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
<Project>
|
<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>
|
<PropertyGroup>
|
||||||
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
|
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
|
||||||
<Version>0.1.0</Version>
|
<Version>0.7.0</Version>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
<InvariantGlobalization>true</InvariantGlobalization>
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
<Deterministic>true</Deterministic>
|
<Deterministic>true</Deterministic>
|
||||||
<Authors>Via Ferrea</Authors>
|
<Authors>Rail Enterprise</Authors>
|
||||||
<Product>Via Ferrea</Product>
|
<Product>Rail Enterprise</Product>
|
||||||
<Copyright>Via Ferrea</Copyright>
|
<Copyright>Rail Enterprise</Copyright>
|
||||||
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
|
||||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||||
<!-- Nessun pacchetto NuGet: niente audit verso feed esterni. -->
|
<!-- Nessun pacchetto NuGet: niente audit verso feed esterni. -->
|
||||||
|
|||||||
@@ -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.
|
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
|

|
||||||
|
|
||||||
|
## 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`)
|
- .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)
|
- Docker (solo per l'immagine del server)
|
||||||
|
|
||||||
## Compilare e provare
|
## Compilare e provare
|
||||||
|
|
||||||
```
|
```bash
|
||||||
scripts/build.sh # controllo "zero NuGet" + build Release
|
scripts/build.sh # controllo "zero NuGet" + build Release
|
||||||
scripts/test.sh # validazione dei dati + tutti i test
|
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
|
## Struttura
|
||||||
|
|
||||||
| Cartella | Contenuto |
|
| Cartella | Contenuto |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `src/ViaFerrea.Core` | simulazione, dati, mappa, economia, rete ferroviaria, salvataggi |
|
| `src/RailEnterprise.Core` | simulazione, dati, mappa, economia, rete ferroviaria, salvataggi |
|
||||||
| `src/ViaFerrea.Protocol` | protocollo binario su WebSocket |
|
| `src/RailEnterprise.Protocol` | protocollo binario su WebSocket |
|
||||||
| `src/ViaFerrea.Server` | server autorevole (Kestrel) |
|
| `src/RailEnterprise.Server` | server autorevole (Kestrel) |
|
||||||
| `src/ViaFerrea.Tools` | `viaferrea-tools`: validate-data, genmap, profile, simulate, bench, smoke, replay |
|
| `src/RailEnterprise.Tools` | `railenterprise-tools` |
|
||||||
| `tests/ViaFerrea.Tests` | harness di test interno e scenari |
|
| `tests/RailEnterprise.Tests` | harness di test interno e scenari |
|
||||||
| `client/ViaFerrea.Client` | client Godot |
|
| `client/RailEnterprise.Client` | client Godot |
|
||||||
| `data/` | parametri di gioco in JSON con schema |
|
| `data/` | parametri di gioco in JSON con schema |
|
||||||
| `docker/` | Dockerfile, compose, template Unraid |
|
| `docker/` | Dockerfile, compose, template Unraid |
|
||||||
| `docs/` | guida, GDD, architettura, protocollo, stato, ADR |
|
| `docs/` | guida, GDD, architettura, protocollo, stato, ADR, schermate |
|
||||||
| `reference/` | immagini di riferimento visivo |
|
| `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
|
||||||
|
|
||||||
```
|
- **CI** (`.gitea/workflows/ci.yml`): su ogni PR e su `main` — zero NuGet, build, dati, test, server per Windows, client, immagine Docker con healthcheck.
|
||||||
dotnet run --project src/ViaFerrea.Server -- --local --token prova # stampa LISTENING <porta>
|
- **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).
|
||||||
dotnet build client/ViaFerrea.Client/ViaFerrea.Client.csproj # poi apri client/ViaFerrea.Client con Godot 4.7 .NET
|
- **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`).
|
Dettagli in [ADR 0014](docs/adr/0014-nome-ci-e-rilasci.md).
|
||||||
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.
|
|
||||||
|
|
||||||

|
Il server parla WebSocket in chiaro: fuori da una rete privata mettilo dietro un reverse proxy con TLS ed esponi solo `wss://`.
|
||||||
|
|
||||||
## 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://`.
|
|
||||||
|
|
||||||
## Documentazione
|
## 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/PROTOCOL.md` — protocollo di rete
|
||||||
- `docs/STATE.md` — stato dei lavori
|
- `docs/STATE.md` — stato dei lavori
|
||||||
- `docs/adr/` — decisioni architetturali
|
- `docs/adr/` — decisioni architetturali
|
||||||
|
- [Wiki](https://gitea.encke-hake.ts.net/BalboSoft/Rail_Enterprise/wiki) — guida del giocatore e schermate
|
||||||
@@ -5,17 +5,17 @@ VisualStudioVersion = 17.0.31903.59
|
|||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||||
EndProject
|
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
|
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
|
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
|
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
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
||||||
EndProject
|
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
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
<Project Sdk="Godot.NET.Sdk/4.7.2">
|
<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.
|
per le anteprime e per la copia locale del mondo; nessuna logica di gioco.
|
||||||
-->
|
-->
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||||
<RootNamespace>ViaFerrea.Client</RootNamespace>
|
<RootNamespace>RailEnterprise.Client</RootNamespace>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
@@ -16,8 +16,8 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\ViaFerrea.Core\ViaFerrea.Core.csproj" />
|
<ProjectReference Include="..\..\src\RailEnterprise.Core\RailEnterprise.Core.csproj" />
|
||||||
<ProjectReference Include="..\..\src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj" />
|
<ProjectReference Include="..\..\src\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<!-- I file dati del gioco entrano nel progetto Godot (res://data) prima di ogni build. -->
|
<!-- 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
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
|||||||
|
[remap]
|
||||||
|
|
||||||
|
importer="keep"
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
|
Before Width: | Height: | Size: 351 B After Width: | Height: | Size: 351 B |
File renamed without changes.
@@ -0,0 +1,142 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"id": "welcome",
|
||||||
|
"title": "Benvenuto in Rail Enterprise",
|
||||||
|
"text": "Guidi una compagnia ferroviaria: costruisci binari e stazioni, trasporti merci e pendolari e fai crescere il patrimonio fino a dominare il mercato. Questo tutorial ti accompagna nella prima linea; puoi saltare un passo o chiuderlo quando vuoi."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "map",
|
||||||
|
"title": "Muovi la mappa",
|
||||||
|
"text": "Trascina con il tasto destro (o usa WASD e le frecce) per spostarti e gira la rotella per lo zoom. Cerca una città e un'industria vicine: saranno le due stazioni della prima linea.",
|
||||||
|
"highlight": "map",
|
||||||
|
"done": { "all": [ { "counter": "mapPan", "increase": 0.5 }, { "counter": "mapZoom", "increase": 0.5 } ] }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "time",
|
||||||
|
"title": "Il tempo",
|
||||||
|
"text": "In alto scegli la velocità del gioco: II mette in pausa, 1× – 8× accelerano. Anche la barra spaziatrice mette in pausa e riprende. Cambia la velocità per proseguire.",
|
||||||
|
"highlight": "topbar:speed",
|
||||||
|
"done": { "counter": "speedChanges", "increase": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "stations",
|
||||||
|
"title": "Costruisci due stazioni",
|
||||||
|
"text": "Apri lo strumento Stazione e fai clic sulla mappa vicino a un'industria e poi vicino a una città. Il cerchio è il bacino di utenza: le merci e i passeggeri arrivano solo da lì.",
|
||||||
|
"highlight": "toolbar:station",
|
||||||
|
"done": { "counter": "stations", "atLeast": 2 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "depot",
|
||||||
|
"title": "Costruisci un deposito",
|
||||||
|
"text": "Con lo strumento Deposito posa un deposito vicino a una delle stazioni. Nel deposito si comprano i veicoli, si compongono i treni e si fanno le manutenzioni.",
|
||||||
|
"highlight": "toolbar:depot",
|
||||||
|
"done": { "counter": "depots", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "track-tool",
|
||||||
|
"title": "Lo strumento Binari",
|
||||||
|
"text": "Apri lo strumento Binari: scegli la classe del binario e se ammettere ponti e gallerie.",
|
||||||
|
"highlight": "toolbar:track",
|
||||||
|
"done": { "panel": "track" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "track-profile",
|
||||||
|
"title": "Guarda il profilo e le opere",
|
||||||
|
"text": "Fai clic sulla prima stazione e muovi il mouse verso la seconda: il profilo mostra il terreno e la quota del binario. Sotto compaiono rilevati, trincee, ponti e gallerie con lunghezza, pendenza, costo e giorni di cantiere. Se attraversi un fiume vedrai il ponte.",
|
||||||
|
"highlight": "track:profile",
|
||||||
|
"fallback": "toolbar:track",
|
||||||
|
"done": { "counter": "trackPreviews", "increase": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "track-build",
|
||||||
|
"title": "Costruisci il binario",
|
||||||
|
"text": "Aggiungi punti con altri clic per evitare salite ripide, poi premi Costruisci (o Invio). Il costo viene addebitato subito e il cantiere parte.",
|
||||||
|
"highlight": "track:build",
|
||||||
|
"fallback": "toolbar:track",
|
||||||
|
"done": { "counter": "cmd:BuildTrack", "increase": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "depot-link",
|
||||||
|
"title": "Collega il deposito",
|
||||||
|
"text": "Il deposito deve essere raccordato alla linea: traccia un breve binario dal deposito alla stazione più vicina. Se è già collegato, premi Salta passo.",
|
||||||
|
"highlight": "track:build",
|
||||||
|
"fallback": "toolbar:track",
|
||||||
|
"done": { "counter": "cmd:BuildTrack", "increase": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "construction",
|
||||||
|
"title": "Attendi i cantieri",
|
||||||
|
"text": "I cantieri richiedono giorni di gioco: accelera il tempo e osserva il tratteggio dei lavori che diventa binario.",
|
||||||
|
"highlight": "topbar:speed",
|
||||||
|
"done": { "all": [ { "counter": "edges", "atLeast": 1 }, { "counter": "edgesBuilding", "atMost": 0 } ] }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "locomotive",
|
||||||
|
"title": "Compra una locomotiva",
|
||||||
|
"text": "Apri Treni, scegli il deposito e una locomotiva dal catalogo, poi premi Compra veicoli.",
|
||||||
|
"highlight": "trains:buy",
|
||||||
|
"fallback": "toolbar:trains",
|
||||||
|
"done": { "counter": "locomotives", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "cars",
|
||||||
|
"title": "Compra i carri",
|
||||||
|
"text": "Ora compra qualche carro per la merce dell'industria (o carrozze per i pendolari): ogni carro accetta solo alcune merci.",
|
||||||
|
"highlight": "trains:buy",
|
||||||
|
"fallback": "toolbar:trains",
|
||||||
|
"done": { "counter": "cars", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "compose",
|
||||||
|
"title": "Componi il treno",
|
||||||
|
"text": "Seleziona nell'elenco del deposito la locomotiva e i carri, nell'ordine in cui li vuoi, dai un nome al treno e premi Componi.",
|
||||||
|
"highlight": "trains:compose",
|
||||||
|
"fallback": "toolbar:trains",
|
||||||
|
"done": { "counter": "trains", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "line",
|
||||||
|
"title": "Crea una linea",
|
||||||
|
"text": "Apri Linee e fai clic sulle due stazioni in ordine: sono le fermate. Scegli nome e colore e premi Crea linea.",
|
||||||
|
"highlight": "lines:create",
|
||||||
|
"fallback": "toolbar:lines",
|
||||||
|
"done": { "counter": "lines", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "assign",
|
||||||
|
"title": "Assegna il treno alla linea",
|
||||||
|
"text": "Torna in Treni, seleziona il treno, scegli la linea e premi Assegna: il treno esce dal deposito e comincia il servizio.",
|
||||||
|
"highlight": "trains:assign",
|
||||||
|
"fallback": "toolbar:trains",
|
||||||
|
"done": { "counter": "trainsOnLine", "atLeast": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "market",
|
||||||
|
"title": "Il Mercato globale",
|
||||||
|
"text": "Apri il Mercato: prezzi, offerta e domanda di ogni bene, la previsione e dove conviene vendere. Ti dice quali linee rendono di più.",
|
||||||
|
"highlight": "toolbar:market",
|
||||||
|
"done": { "panel": "market" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "finance",
|
||||||
|
"title": "Le Finanze",
|
||||||
|
"text": "Apri le Finanze: conto economico per voce, rating e prestiti. Un prestito ben speso costruisce linee; troppi debiti abbassano il rating e alzano il tasso.",
|
||||||
|
"highlight": "toolbar:finance",
|
||||||
|
"done": { "panel": "finance" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "climb",
|
||||||
|
"title": "La tua scalata",
|
||||||
|
"text": "Apri la Scalata (o fai clic sul livello in alto): i livelli della compagnia, che cosa sbloccano e che cosa manca per salire.",
|
||||||
|
"highlight": "toolbar:climb",
|
||||||
|
"done": { "panel": "climb" }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "tips",
|
||||||
|
"title": "Qualche consiglio",
|
||||||
|
"text": "Collega industrie che producono a chi consuma la loro merce e porta i lavoratori dalle città alle industrie. Tieni d'occhio le Officine: un treno trascurato si guasta. Controlla cassa e rating prima di indebitarti. Buon viaggio! Puoi riaprire il tutorial con F1."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+6
-6
@@ -6,9 +6,9 @@ runnable=true
|
|||||||
dedicated_server=false
|
dedicated_server=false
|
||||||
custom_features=""
|
custom_features=""
|
||||||
export_filter="all_resources"
|
export_filter="all_resources"
|
||||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/tutorial/*.json, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||||
exclude_filter=""
|
exclude_filter=""
|
||||||
export_path="export/windows/ViaFerrea.exe"
|
export_path="export/windows/RailEnterprise.exe"
|
||||||
encryption_include_filters=""
|
encryption_include_filters=""
|
||||||
encryption_exclude_filters=""
|
encryption_exclude_filters=""
|
||||||
encrypt_pck=false
|
encrypt_pck=false
|
||||||
@@ -21,8 +21,8 @@ custom_template/release=""
|
|||||||
debug/export_console_wrapper=1
|
debug/export_console_wrapper=1
|
||||||
binary_format/embed_pck=false
|
binary_format/embed_pck=false
|
||||||
binary_format/architecture="x86_64"
|
binary_format/architecture="x86_64"
|
||||||
application/product_name="Via Ferrea"
|
application/product_name="Rail Enterprise"
|
||||||
application/company_name="Via Ferrea"
|
application/company_name="Rail Enterprise"
|
||||||
application/file_description="Gestionale ferroviario dall'alto"
|
application/file_description="Gestionale ferroviario dall'alto"
|
||||||
dotnet/include_scripts_content=false
|
dotnet/include_scripts_content=false
|
||||||
dotnet/include_debug_symbols=false
|
dotnet/include_debug_symbols=false
|
||||||
@@ -36,9 +36,9 @@ runnable=true
|
|||||||
dedicated_server=false
|
dedicated_server=false
|
||||||
custom_features=""
|
custom_features=""
|
||||||
export_filter="all_resources"
|
export_filter="all_resources"
|
||||||
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
include_filter="data/*.json, data/schema/*.json, assets/i18n/*.csv, assets/tutorial/*.json, assets/fonts/*.ttf, assets/fonts/OFL.txt"
|
||||||
exclude_filter=""
|
exclude_filter=""
|
||||||
export_path="export/linux/ViaFerrea.x86_64"
|
export_path="export/linux/RailEnterprise.x86_64"
|
||||||
encrypt_pck=false
|
encrypt_pck=false
|
||||||
encrypt_directory=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).
|
; Nessuna logica di gioco: il server è autorevole (docs/GUIDA.md, sezione 14.3).
|
||||||
|
|
||||||
config_version=5
|
config_version=5
|
||||||
|
|
||||||
[application]
|
[application]
|
||||||
|
|
||||||
config/name="Via Ferrea"
|
config/name="Rail Enterprise"
|
||||||
config/description="Gestionale ferroviario dall'alto"
|
config/description="Gestionale ferroviario dall'alto"
|
||||||
run/main_scene="res://scenes/Main.tscn"
|
run/main_scene="res://scenes/Main.tscn"
|
||||||
config/features=PackedStringArray("4.7", "C#", "GL Compatibility")
|
config/features=PackedStringArray("4.7", "C#", "GL Compatibility")
|
||||||
@@ -21,7 +21,7 @@ window/stretch/aspect="expand"
|
|||||||
|
|
||||||
[dotnet]
|
[dotnet]
|
||||||
|
|
||||||
project/assembly_name="ViaFerrea.Client"
|
project/assembly_name="RailEnterprise.Client"
|
||||||
|
|
||||||
[internationalization]
|
[internationalization]
|
||||||
|
|
||||||
File renamed without changes.
+57
-13
@@ -1,15 +1,15 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.Hud;
|
using RailEnterprise.Client.Hud;
|
||||||
using ViaFerrea.Client.Map;
|
using RailEnterprise.Client.Map;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Client.Screens;
|
using RailEnterprise.Client.Screens;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.App;
|
namespace RailEnterprise.Client.App;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
|
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
|
||||||
@@ -209,13 +209,14 @@ public partial class AutoPilot : Node
|
|||||||
var anchor = MapScale.V(near);
|
var anchor = MapScale.V(near);
|
||||||
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
||||||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
||||||
|
// dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di
|
||||||
|
// un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo
|
||||||
|
// (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom
|
||||||
_game.OpenIndustry(industry.Id);
|
_game.OpenIndustry(industry.Id);
|
||||||
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
||||||
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
|
// al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda
|
||||||
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
||||||
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
||||||
_game.Map.CenterOn(MapScale.V(industry.Position));
|
|
||||||
_game.Map.SetZoom(0.3f);
|
|
||||||
await Shot("12_industria", 40);
|
await Shot("12_industria", 40);
|
||||||
_game.ScrollPanel(1);
|
_game.ScrollPanel(1);
|
||||||
await Shot("12b_industria_scorte", 20);
|
await Shot("12b_industria_scorte", 20);
|
||||||
@@ -235,9 +236,52 @@ public partial class AutoPilot : Node
|
|||||||
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
|
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
|
||||||
await Shot("14_compagnia_giocatore", 40);
|
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);
|
||||||
|
|
||||||
|
// La tua scalata (immagine 08): livelli, sblocchi, requisiti, stato patrimoniale
|
||||||
|
_game.OpenClimb();
|
||||||
|
await Until(() => World.Climb is not null, "quadro della scalata", 30);
|
||||||
|
await Shot("17_scalata", 40);
|
||||||
|
|
||||||
|
// Finanze: conto economico per voce, rating spiegato, prestiti
|
||||||
|
_game.OpenFinance();
|
||||||
|
await Until(() => World.Finance is not null, "quadro delle finanze", 30);
|
||||||
|
await Shot("18_finanze", 40);
|
||||||
|
|
||||||
// Cronaca provvisoria
|
// Cronaca provvisoria
|
||||||
_game.OpenChronicle();
|
_game.OpenChronicle();
|
||||||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||||||
await Shot("15_cronaca", 30);
|
await Shot("15_cronaca", 30);
|
||||||
|
_game.CloseChronicle();
|
||||||
|
|
||||||
|
// F6, scheda dell'industria (immagine 07): un'industria di trasformazione vicino alla linea,
|
||||||
|
// con catena produttiva, forza lavoro e crescita
|
||||||
|
var processing = World.Industries.Values
|
||||||
|
.Where(i => !i.Closed && i.Level > 0 && World.Data.Industries.FirstOrDefault(d => d.Id == i.Type)?.Recipe.Inputs.Count > 0)
|
||||||
|
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).FirstOrDefault() ?? industry;
|
||||||
|
_game.OpenIndustry(processing.Id);
|
||||||
|
await Until(() => World.IndustryCards.TryGetValue(processing.Id, out var c) && c.Sheet is not null, "scheda completa dell'industria", 30);
|
||||||
|
_game.ScrollPanel(0);
|
||||||
|
await Shot("19_scheda_industria", 40);
|
||||||
|
|
||||||
|
// F6, schermata di connessione (immagine 09) sopra la partita: sessione di prova sul server
|
||||||
|
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
|
||||||
|
Session.Send(new Save { Name = "Collaudo" });
|
||||||
|
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
|
||||||
|
// livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la
|
||||||
|
// schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa
|
||||||
|
_game.CloseTools();
|
||||||
|
var layer = new CanvasLayer { Layer = 10 };
|
||||||
|
_game.AddChild(layer);
|
||||||
|
var connect = new ConnectScreen(World.Data, remember: false, autoStart: false);
|
||||||
|
layer.AddChild(connect);
|
||||||
|
await Frame();
|
||||||
|
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
|
||||||
|
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
|
||||||
|
await Shot("20_connessione", 30);
|
||||||
|
layer.QueueFree();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File renamed without changes.
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Godot;
|
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>
|
/// <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
|
public sealed class GodotDataSource(string root = "res://data") : IDataSource
|
||||||
File renamed without changes.
+3
-2
@@ -1,11 +1,12 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.App;
|
namespace RailEnterprise.Client.App;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani),
|
/// 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
|
/// 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>
|
/// </summary>
|
||||||
public static class Localization
|
public static class Localization
|
||||||
{
|
{
|
||||||
File renamed without changes.
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
using Godot;
|
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>
|
/// <summary>Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara.</summary>
|
||||||
public static class Palette
|
public static class Palette
|
||||||
File renamed without changes.
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.App;
|
namespace RailEnterprise.Client.App;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
|
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
|
||||||
File renamed without changes.
@@ -0,0 +1,643 @@
|
|||||||
|
using Godot;
|
||||||
|
using RailEnterprise.Client.Map;
|
||||||
|
using RailEnterprise.Client.Net;
|
||||||
|
using RailEnterprise.Core.Data;
|
||||||
|
using RailEnterprise.Core.Map;
|
||||||
|
using RailEnterprise.Core.Rail;
|
||||||
|
using RailEnterprise.Protocol;
|
||||||
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Regia dell'audio, figlia di <c>Main</c> per tutta la vita del client: bus e volumi, effetti
|
||||||
|
/// dell'interfaccia (clic di ogni pulsante, esito dei comandi), notifiche, cantieri completati,
|
||||||
|
/// treni in moto vicini al centro della telecamera (rotolamento, motore, sbuffi), ambiente dal
|
||||||
|
/// terreno sotto la telecamera e musica per era. Non decide nulla del gioco: reagisce a ciò che il
|
||||||
|
/// client riceve (esiti, notifiche, <c>DailyDigest</c>, moti dei treni) e alla vista.
|
||||||
|
/// I suoni si sintetizzano all'avvio su un altro thread (<see cref="Synth"/>, <see cref="MusicComposer"/>);
|
||||||
|
/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ).
|
||||||
|
/// </summary>
|
||||||
|
public partial class AudioManager : Node
|
||||||
|
{
|
||||||
|
/// <summary>Unica istanza (nulla prima dell'avvio del client).</summary>
|
||||||
|
public static AudioManager? Instance { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Volumi e muto attuali (anche con l'audio disattivato, per il pannello).</summary>
|
||||||
|
public AudioSettings Settings { get; private set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra).</summary>
|
||||||
|
public event Action? SettingsChanged;
|
||||||
|
|
||||||
|
private readonly bool _enabled;
|
||||||
|
private Task<SoundBank>? _bankTask;
|
||||||
|
private bool _loaded;
|
||||||
|
|
||||||
|
// suoni singoli
|
||||||
|
private AudioStreamWav? _click, _confirm, _error, _build, _chuff;
|
||||||
|
private readonly Callable _clickCallable;
|
||||||
|
private readonly AudioStreamWav?[] _notify = new AudioStreamWav?[3];
|
||||||
|
private AudioStreamWav[] _birds = [];
|
||||||
|
private AudioStreamWav? _diesel, _hum;
|
||||||
|
|
||||||
|
// riproduttori polifonici per bus e nomi dei bus già pronti (niente StringName per chiamata)
|
||||||
|
private readonly StringName _busUi = AudioBuses.Ui, _busSfx = AudioBuses.Sfx, _busAmbience = AudioBuses.Ambience;
|
||||||
|
private AudioStreamPlaybackPolyphonic? _ui, _sfx, _ambience;
|
||||||
|
|
||||||
|
// ambiente: vento, acqua, mare, città
|
||||||
|
private const int AmbienceLoops = 4;
|
||||||
|
private static readonly float[] AmbienceLevel = [0.55f, 0.6f, 0.6f, 0.5f];
|
||||||
|
private readonly AudioStreamPlayer[] _ambiencePlayers = new AudioStreamPlayer[AmbienceLoops];
|
||||||
|
private readonly float[] _ambienceGain = new float[AmbienceLoops];
|
||||||
|
private readonly float[] _ambienceTarget = new float[AmbienceLoops];
|
||||||
|
private float _birdsChance;
|
||||||
|
private float _sinceAmbience = 1, _birdTimer = 3;
|
||||||
|
|
||||||
|
// treni
|
||||||
|
private sealed class TrainChannel
|
||||||
|
{
|
||||||
|
public int Train = -1;
|
||||||
|
public Traction Traction;
|
||||||
|
public float Gain, Target, ChuffTimer;
|
||||||
|
public bool Kept;
|
||||||
|
public required AudioStreamPlayer Rumble { get; init; }
|
||||||
|
public required AudioStreamPlayer Engine { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly TrainChannel[] _channels = new TrainChannel[AudioMix.TrainChannels];
|
||||||
|
private readonly int[] _nearIds = new int[AudioMix.TrainChannels];
|
||||||
|
private readonly float[] _nearDistances = new float[AudioMix.TrainChannels];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Età massima (ms) dell'ultimo moto di un treno perché suoni: il server manda i moti dei treni
|
||||||
|
/// in marcia ogni 100 ms; un moto più vecchio è di un treno fermo in stazione (durante la sosta
|
||||||
|
/// non arrivano moti) o uscito dalla zona sottoscritta, e non va più ascoltato.
|
||||||
|
/// </summary>
|
||||||
|
private const long StaleMotionMs = 500;
|
||||||
|
|
||||||
|
// musica: due riproduttori per la dissolvenza incrociata
|
||||||
|
private const float MusicLevel = 0.6f;
|
||||||
|
private const float FadeSeconds = 3f;
|
||||||
|
private readonly AudioStreamPlayer[] _music = new AudioStreamPlayer[2];
|
||||||
|
private readonly float[] _musicGain = new float[2];
|
||||||
|
private int _activeMusic;
|
||||||
|
private int _musicEra = -1;
|
||||||
|
private readonly Dictionary<int, AudioStreamWav> _themes = [];
|
||||||
|
private readonly HashSet<int> _failedThemes = [];
|
||||||
|
private Task<float[]>? _composing;
|
||||||
|
private int _composingEra;
|
||||||
|
private string[] _eraIds = ["steam"];
|
||||||
|
private int[] _eraFroms = [0];
|
||||||
|
|
||||||
|
// partita in corso
|
||||||
|
private GameSession? _session;
|
||||||
|
private MapView? _map;
|
||||||
|
private Dictionary<string, VehicleDef> _vehicles = [];
|
||||||
|
private SynthRng _rng = new(0xA0D10);
|
||||||
|
private ulong _lastUiMs, _lastNotifyMs;
|
||||||
|
private bool _settingsDirty;
|
||||||
|
|
||||||
|
// pannello delle impostazioni
|
||||||
|
private CanvasLayer? _overlay;
|
||||||
|
private AudioSettingsPanel? _panel;
|
||||||
|
|
||||||
|
/// <param name="enabled">Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto.</param>
|
||||||
|
public AudioManager(bool enabled)
|
||||||
|
{
|
||||||
|
_enabled = enabled;
|
||||||
|
Name = "AudioManager";
|
||||||
|
_clickCallable = Callable.From(PlayClick);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AudioManager() : this(true)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Ready()
|
||||||
|
{
|
||||||
|
Instance = this;
|
||||||
|
AudioBuses.Ensure();
|
||||||
|
Settings = AudioSettings.Load();
|
||||||
|
ApplySettings();
|
||||||
|
if (!_enabled) return;
|
||||||
|
_bankTask = Task.Run(SoundBank.Create);
|
||||||
|
GetTree().NodeAdded += OnNodeAdded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _ExitTree()
|
||||||
|
{
|
||||||
|
if (Instance == this) Instance = null;
|
||||||
|
Unbind();
|
||||||
|
// chiusura della finestra con un volume appena cambiato: si salva comunque
|
||||||
|
SaveSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale.</summary>
|
||||||
|
public void SetEras(IReadOnlyList<EraDef> eras)
|
||||||
|
{
|
||||||
|
if (eras.Count == 0) return;
|
||||||
|
_eraIds = new string[eras.Count];
|
||||||
|
_eraFroms = new int[eras.Count];
|
||||||
|
for (int i = 0; i < eras.Count; i++)
|
||||||
|
{
|
||||||
|
_eraIds[i] = eras[i].Id;
|
||||||
|
_eraFroms[i] = eras[i].From;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ impostazioni
|
||||||
|
|
||||||
|
private void ApplySettings()
|
||||||
|
{
|
||||||
|
Settings.Apply();
|
||||||
|
// senza audio (collaudo, server senza schermo) il Master resta muto, senza toccare il file
|
||||||
|
if (!_enabled) AudioServer.SetBusMute(0, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cambia il volume di un bus (indice in <see cref="AudioBuses.All"/>) e lo applica subito.</summary>
|
||||||
|
public void SetVolume(int bus, float value)
|
||||||
|
{
|
||||||
|
Settings.Volumes[bus] = Math.Clamp(value, 0, 1);
|
||||||
|
_settingsDirty = true;
|
||||||
|
ApplySettings();
|
||||||
|
SettingsChanged?.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetMuted(bool muted)
|
||||||
|
{
|
||||||
|
Settings.Muted = muted;
|
||||||
|
_settingsDirty = true;
|
||||||
|
ApplySettings();
|
||||||
|
SettingsChanged?.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ToggleMute()
|
||||||
|
{
|
||||||
|
SetMuted(!Settings.Muted);
|
||||||
|
SaveSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Scrive volumi e muto in <c>user://settings.cfg</c> se sono cambiati dall'ultimo salvataggio.</summary>
|
||||||
|
public void SaveSettings()
|
||||||
|
{
|
||||||
|
if (!_settingsDirty) return;
|
||||||
|
_settingsDirty = false;
|
||||||
|
Settings.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Apre il pannello «Audio» sopra a tutto (menu o partita).</summary>
|
||||||
|
public void ShowSettings()
|
||||||
|
{
|
||||||
|
if (_panel is not null && IsInstanceValid(_panel)) return;
|
||||||
|
if (_overlay is null)
|
||||||
|
{
|
||||||
|
_overlay = new CanvasLayer { Layer = 50 };
|
||||||
|
AddChild(_overlay);
|
||||||
|
}
|
||||||
|
_panel = new AudioSettingsPanel(this);
|
||||||
|
_panel.TreeExited += () => _panel = null;
|
||||||
|
_overlay.AddChild(_panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _UnhandledKeyInput(InputEvent e)
|
||||||
|
{
|
||||||
|
if (e is InputEventKey { Pressed: true, Echo: false, Keycode: Key.M } key && !key.CtrlPressed && !key.AltPressed && !key.MetaPressed)
|
||||||
|
{
|
||||||
|
ToggleMute();
|
||||||
|
GetViewport().SetInputAsHandled();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ partita
|
||||||
|
|
||||||
|
/// <summary>Collega la partita: messaggi della sessione e vista della mappa.</summary>
|
||||||
|
public void Bind(GameSession session, MapView map)
|
||||||
|
{
|
||||||
|
Unbind();
|
||||||
|
_session = session;
|
||||||
|
_map = map;
|
||||||
|
_vehicles = session.World.Data.Vehicles.ToDictionary(v => v.Id);
|
||||||
|
SetEras(session.World.Data.Eras.Eras);
|
||||||
|
session.MessageApplied += OnMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scollega la partita (ritorno al menu): treni e ambiente sfumano. Con «only» scollega solo
|
||||||
|
/// se è ancora quella sessione (la schermata vecchia esce dall'albero dopo l'arrivo della nuova).
|
||||||
|
/// </summary>
|
||||||
|
public void Unbind(GameSession? only = null)
|
||||||
|
{
|
||||||
|
if (only is not null && !ReferenceEquals(only, _session)) return;
|
||||||
|
if (_session is not null) _session.MessageApplied -= OnMessage;
|
||||||
|
_session = null;
|
||||||
|
_map = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMessage(IMessage message)
|
||||||
|
{
|
||||||
|
if (!_loaded) return;
|
||||||
|
switch (message)
|
||||||
|
{
|
||||||
|
case CommandResultMessage r:
|
||||||
|
PlayUi(r.Ok ? _confirm : _error, r.Ok ? 0.7f : 0.85f);
|
||||||
|
break;
|
||||||
|
case Notification n:
|
||||||
|
Notify(n.Event);
|
||||||
|
break;
|
||||||
|
case DailyDigest d:
|
||||||
|
int me = _session?.World.Summary?.CompanyId ?? -1;
|
||||||
|
for (int i = 0; i < d.Events.Count; i++)
|
||||||
|
{
|
||||||
|
var e = d.Events[i];
|
||||||
|
if (e.Kind == ConstructionEventKind && e.Company == me && me >= 0)
|
||||||
|
{
|
||||||
|
Play(_sfx, _build, 0.8f, 1, _busSfx);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo).</summary>
|
||||||
|
private const byte ConstructionEventKind = 5;
|
||||||
|
|
||||||
|
private void Notify(EventInfo e)
|
||||||
|
{
|
||||||
|
int me = _session?.World.Summary?.CompanyId ?? -1;
|
||||||
|
if (e.Company >= 0 && e.Company != me) return;
|
||||||
|
int level = e.Severity switch { 3 => 2, 2 => 1, _ => 0 };
|
||||||
|
ulong now = Time.GetTicksMsec();
|
||||||
|
// più notizie insieme: una sola campanella (le critiche suonano sempre)
|
||||||
|
if (level < 2 && now - _lastNotifyMs < 600) return;
|
||||||
|
_lastNotifyMs = now;
|
||||||
|
Play(_ui, _notify[level], level == 2 ? 0.9f : 0.75f, 1, _busUi);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnNodeAdded(Node node)
|
||||||
|
{
|
||||||
|
// un pulsante staccato e riattaccato (MarketPanel lo fa a ogni resoconto) è già collegato
|
||||||
|
if (node is BaseButton button && !button.IsConnected(BaseButton.SignalName.Pressed, _clickCallable))
|
||||||
|
button.Connect(BaseButton.SignalName.Pressed, _clickCallable);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PlayClick() => PlayUi(_click, 0.6f);
|
||||||
|
|
||||||
|
private void PlayUi(AudioStreamWav? stream, float gain)
|
||||||
|
{
|
||||||
|
ulong now = Time.GetTicksMsec();
|
||||||
|
if (stream == _click && now - _lastUiMs < 40) return;
|
||||||
|
_lastUiMs = now;
|
||||||
|
Play(_ui, stream, gain, 1, _busUi);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Play(AudioStreamPlaybackPolyphonic? playback, AudioStreamWav? stream, float gain, float pitch, StringName bus)
|
||||||
|
{
|
||||||
|
if (playback is null || stream is null || gain <= 0.001f) return;
|
||||||
|
playback.PlayStream(stream, 0, AudioMix.LinearToDb(gain), pitch, AudioServer.PlaybackType.Default, bus);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ caricamento
|
||||||
|
|
||||||
|
/// <summary>Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale.</summary>
|
||||||
|
private sealed class SoundBank
|
||||||
|
{
|
||||||
|
public required float[] Click, Confirm, Error, Construction, Chuff, Rumble, Diesel, Hum, Wind, River, Sea, City;
|
||||||
|
public required float[][] Notify, Birds;
|
||||||
|
|
||||||
|
public static SoundBank Create() => new()
|
||||||
|
{
|
||||||
|
Click = Synth.Click(), Confirm = Synth.Confirm(), Error = Synth.Error(), Construction = Synth.BuildComplete(),
|
||||||
|
Chuff = Synth.Chuff(), Rumble = Synth.RailRumbleLoop(),
|
||||||
|
Diesel = Synth.DieselDroneLoop(), Hum = Synth.ElectricHumLoop(), Wind = Synth.WindLoop(), River = Synth.RiverLoop(),
|
||||||
|
Sea = Synth.SeaLoop(), City = Synth.CityLoop(),
|
||||||
|
Notify = [Synth.Notify(0), Synth.Notify(1), Synth.Notify(2)],
|
||||||
|
Birds = [Synth.Bird(0), Synth.Bird(1), Synth.Bird(2)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AudioStreamWav Wav(float[] samples, bool loop = false)
|
||||||
|
{
|
||||||
|
var w = new AudioStreamWav
|
||||||
|
{
|
||||||
|
Format = AudioStreamWav.FormatEnum.Format16Bits,
|
||||||
|
MixRate = Synth.Rate,
|
||||||
|
Stereo = false,
|
||||||
|
Data = AudioMix.ToPcm16(samples),
|
||||||
|
};
|
||||||
|
if (loop)
|
||||||
|
{
|
||||||
|
w.LoopMode = AudioStreamWav.LoopModeEnum.Forward;
|
||||||
|
w.LoopBegin = 0;
|
||||||
|
w.LoopEnd = samples.Length;
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AudioStreamPlayer Player(string bus, AudioStream? stream = null)
|
||||||
|
{
|
||||||
|
var p = new AudioStreamPlayer { Bus = bus, Stream = stream };
|
||||||
|
AddChild(p);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AudioStreamPlaybackPolyphonic? Polyphonic(string bus, int voices)
|
||||||
|
{
|
||||||
|
var p = Player(bus, new AudioStreamPolyphonic { Polyphony = voices });
|
||||||
|
p.Play();
|
||||||
|
return p.GetStreamPlayback() as AudioStreamPlaybackPolyphonic;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Load(SoundBank bank)
|
||||||
|
{
|
||||||
|
_click = Wav(bank.Click);
|
||||||
|
_confirm = Wav(bank.Confirm);
|
||||||
|
_error = Wav(bank.Error);
|
||||||
|
_build = Wav(bank.Construction);
|
||||||
|
_chuff = Wav(bank.Chuff);
|
||||||
|
for (int i = 0; i < _notify.Length; i++) _notify[i] = Wav(bank.Notify[i]);
|
||||||
|
_birds = bank.Birds.Select(b => Wav(b)).ToArray();
|
||||||
|
_diesel = Wav(bank.Diesel, loop: true);
|
||||||
|
_hum = Wav(bank.Hum, loop: true);
|
||||||
|
var rumble = Wav(bank.Rumble, loop: true);
|
||||||
|
|
||||||
|
_ui = Polyphonic(AudioBuses.Ui, 8);
|
||||||
|
_sfx = Polyphonic(AudioBuses.Sfx, 16);
|
||||||
|
_ambience = Polyphonic(AudioBuses.Ambience, 4);
|
||||||
|
float[][] loops = [bank.Wind, bank.River, bank.Sea, bank.City];
|
||||||
|
for (int i = 0; i < AmbienceLoops; i++)
|
||||||
|
{
|
||||||
|
var p = Player(AudioBuses.Ambience, Wav(loops[i], loop: true));
|
||||||
|
p.VolumeLinear = 0;
|
||||||
|
_ambiencePlayers[i] = p;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _channels.Length; i++)
|
||||||
|
{
|
||||||
|
var r = Player(AudioBuses.Sfx, rumble);
|
||||||
|
var e = Player(AudioBuses.Sfx);
|
||||||
|
r.VolumeLinear = e.VolumeLinear = 0;
|
||||||
|
_channels[i] = new TrainChannel { Rumble = r, Engine = e };
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _music.Length; i++) _music[i] = Player(AudioBuses.Music);
|
||||||
|
_loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ ciclo
|
||||||
|
|
||||||
|
public override void _Process(double delta)
|
||||||
|
{
|
||||||
|
if (!_enabled) return;
|
||||||
|
if (!_loaded)
|
||||||
|
{
|
||||||
|
if (_bankTask is not { IsCompleted: true }) return;
|
||||||
|
if (_bankTask.IsCompletedSuccessfully) Load(_bankTask.Result);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
GD.PrintErr($"Audio: sintesi non riuscita: {_bankTask.Exception?.GetBaseException().Message}");
|
||||||
|
_bankTask = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
float dt = (float)Math.Min(delta, 0.1);
|
||||||
|
UpdateMusic(dt);
|
||||||
|
UpdateAmbience(dt);
|
||||||
|
UpdateTrains(dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int WantedEra()
|
||||||
|
{
|
||||||
|
var w = _session?.World;
|
||||||
|
if (w?.Calendar is null) return 0;
|
||||||
|
return AudioMix.EraIndex(w.Year, _eraFroms);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateMusic(float dt)
|
||||||
|
{
|
||||||
|
int want = WantedEra();
|
||||||
|
if (_composing is { IsCompleted: true })
|
||||||
|
{
|
||||||
|
if (_composing.IsCompletedSuccessfully) _themes[_composingEra] = Wav(_composing.Result, loop: true);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_failedThemes.Add(_composingEra);
|
||||||
|
GD.PrintErr($"Audio: tema dell'era non composto: {_composing.Exception?.GetBaseException().Message}");
|
||||||
|
}
|
||||||
|
_composing = null;
|
||||||
|
}
|
||||||
|
if (want != _musicEra)
|
||||||
|
{
|
||||||
|
if (_themes.TryGetValue(want, out var theme))
|
||||||
|
{
|
||||||
|
// dissolvenza incrociata: il nuovo tema entra sull'altro riproduttore
|
||||||
|
_activeMusic = 1 - _activeMusic;
|
||||||
|
var p = _music[_activeMusic];
|
||||||
|
p.Stream = theme;
|
||||||
|
_musicGain[_activeMusic] = 0;
|
||||||
|
p.VolumeLinear = 0;
|
||||||
|
p.Play();
|
||||||
|
_musicEra = want;
|
||||||
|
}
|
||||||
|
else if (_composing is null && !_failedThemes.Contains(want))
|
||||||
|
{
|
||||||
|
int era = want;
|
||||||
|
string id = _eraIds[Math.Clamp(era, 0, _eraIds.Length - 1)];
|
||||||
|
_composingEra = era;
|
||||||
|
_composing = Task.Run(() => MusicComposer.Compose(era, id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < _music.Length; i++)
|
||||||
|
{
|
||||||
|
float target = i == _activeMusic && _musicEra >= 0 ? 1 : 0;
|
||||||
|
_musicGain[i] = AudioMix.Approach(_musicGain[i], target, 1 / FadeSeconds, dt);
|
||||||
|
_music[i].VolumeLinear = _musicGain[i] * MusicLevel;
|
||||||
|
if (_musicGain[i] <= 0 && i != _activeMusic && _music[i].Playing) _music[i].Stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateAmbience(float dt)
|
||||||
|
{
|
||||||
|
_sinceAmbience += dt;
|
||||||
|
if (_sinceAmbience >= 0.25f)
|
||||||
|
{
|
||||||
|
_sinceAmbience = 0;
|
||||||
|
var gains = _map is not null && _session?.World.Terrain is { } terrain
|
||||||
|
? AudioMix.Ambience(_map.Zoom, SampleTerrain(terrain, _map.VisibleRect()))
|
||||||
|
: default;
|
||||||
|
_ambienceTarget[0] = gains.Wind;
|
||||||
|
_ambienceTarget[1] = gains.Water;
|
||||||
|
_ambienceTarget[2] = gains.Sea;
|
||||||
|
_ambienceTarget[3] = gains.City;
|
||||||
|
_birdsChance = gains.Birds;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < AmbienceLoops; i++)
|
||||||
|
{
|
||||||
|
_ambienceGain[i] = AudioMix.Approach(_ambienceGain[i], _ambienceTarget[i], 0.5f, dt);
|
||||||
|
var p = _ambiencePlayers[i];
|
||||||
|
p.VolumeLinear = _ambienceGain[i] * AmbienceLevel[i];
|
||||||
|
if (_ambienceGain[i] > 0 && !p.Playing) p.Play(_rng.Next01() * 4);
|
||||||
|
else if (_ambienceGain[i] <= 0 && p.Playing) p.Stop();
|
||||||
|
}
|
||||||
|
if (_birdsChance > 0.05f && _birds.Length > 0)
|
||||||
|
{
|
||||||
|
_birdTimer -= dt;
|
||||||
|
if (_birdTimer <= 0)
|
||||||
|
{
|
||||||
|
Play(_ambience, _birds[_rng.Next(_birds.Length)], _birdsChance * 0.45f, _rng.Range(0.9f, 1.15f), _busAmbience);
|
||||||
|
_birdTimer = _rng.Range(1.5f, 6f) / (0.3f + _birdsChance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina).</summary>
|
||||||
|
private static TerrainMix SampleTerrain(Terrain t, Rect2 view)
|
||||||
|
{
|
||||||
|
const int grid = 8;
|
||||||
|
view = view.Grow(Math.Max(view.Size.X, view.Size.Y) * 0.125f);
|
||||||
|
int river = 0, lake = 0, sea = 0, town = 0, forest = 0, open = 0, total = 0;
|
||||||
|
for (int gy = 0; gy < grid; gy++)
|
||||||
|
{
|
||||||
|
for (int gx = 0; gx < grid; gx++)
|
||||||
|
{
|
||||||
|
double x = view.Position.X + (gx + 0.5) / grid * view.Size.X;
|
||||||
|
double y = view.Position.Y + (gy + 0.5) / grid * view.Size.Y;
|
||||||
|
int cx = (int)Math.Floor(x / t.CellSizeM), cy = (int)Math.Floor(y / t.CellSizeM);
|
||||||
|
if (!t.InBounds(cx, cy)) continue;
|
||||||
|
int i = t.Index(cx, cy);
|
||||||
|
total++;
|
||||||
|
switch ((CellType)t.Types[i])
|
||||||
|
{
|
||||||
|
case CellType.Water when t.RiverWidth[i] > 0: river++; break;
|
||||||
|
case CellType.Water: lake++; break;
|
||||||
|
case CellType.Sea: sea++; break;
|
||||||
|
case CellType.Town or CellType.Industry: town++; break;
|
||||||
|
case CellType.Forest: forest++; break;
|
||||||
|
default: open++; break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (total == 0) return default;
|
||||||
|
float k = 1f / total;
|
||||||
|
return new TerrainMix { River = river * k, Lake = lake * k, Sea = sea * k, Town = town * k, Forest = forest * k, Open = open * k };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateTrains(float dt)
|
||||||
|
{
|
||||||
|
var w = _session?.World;
|
||||||
|
var map = _map;
|
||||||
|
int count = 0;
|
||||||
|
Vector2 center = default;
|
||||||
|
float zoom = 1, radius = 1;
|
||||||
|
if (w is not null && map is not null && _session is { } session && w.Speed > 0)
|
||||||
|
{
|
||||||
|
center = map.Camera.GetScreenCenterPosition();
|
||||||
|
zoom = map.Zoom;
|
||||||
|
radius = map.GetViewportRect().Size.Length() / 2;
|
||||||
|
long now = (long)Time.GetTicksMsec();
|
||||||
|
foreach (var (id, head) in map.Trains.Heads)
|
||||||
|
{
|
||||||
|
if (!w.Motions.TryGetValue(id, out var m) || m.State != (byte)TrainState.Moving || m.Speed < 0.5f) continue;
|
||||||
|
if (!session.MotionReceivedMs.TryGetValue(id, out long at) || now - at > StaleMotionMs) continue;
|
||||||
|
// oltre il raggio non si sentirebbe: niente canale (eviterebbe Play e Stop a ogni fotogramma)
|
||||||
|
float distance = head.DistanceTo(center) * zoom;
|
||||||
|
if (distance >= radius) continue;
|
||||||
|
count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, distance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// i canali restano ai loro treni finché sono tra i più vicini; gli altri sfumano
|
||||||
|
foreach (var ch in _channels) ch.Kept = ch.Train >= 0 && Contains(_nearIds, count, ch.Train);
|
||||||
|
for (int k = 0; k < count; k++)
|
||||||
|
{
|
||||||
|
int id = _nearIds[k];
|
||||||
|
if (HasChannel(id)) continue;
|
||||||
|
foreach (var ch in _channels)
|
||||||
|
{
|
||||||
|
if (ch.Train >= 0 && (ch.Kept || ch.Gain > 0.01f)) continue;
|
||||||
|
Assign(ch, id, w!);
|
||||||
|
ch.Kept = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (var ch in _channels)
|
||||||
|
{
|
||||||
|
float speed = 0;
|
||||||
|
if (ch.Kept && w is not null && map is not null && w.Motions.TryGetValue(ch.Train, out var m) && map.Trains.Heads.TryGetValue(ch.Train, out var head))
|
||||||
|
{
|
||||||
|
speed = m.Speed;
|
||||||
|
ch.Target = AudioMix.TrainGain(head.DistanceTo(center) * zoom, radius, speed, zoom);
|
||||||
|
}
|
||||||
|
else ch.Target = 0;
|
||||||
|
ch.Gain = AudioMix.Approach(ch.Gain, ch.Target, 2.5f, dt);
|
||||||
|
if (ch.Train < 0) continue;
|
||||||
|
if (ch.Gain <= 0 && ch.Target <= 0)
|
||||||
|
{
|
||||||
|
ch.Train = -1;
|
||||||
|
ch.Rumble.Stop();
|
||||||
|
ch.Engine.Stop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (speed > 0)
|
||||||
|
{
|
||||||
|
ch.Rumble.PitchScale = AudioMix.RumblePitch(speed);
|
||||||
|
ch.Engine.PitchScale = AudioMix.EnginePitch(speed);
|
||||||
|
}
|
||||||
|
ch.Rumble.VolumeLinear = ch.Gain * 0.7f;
|
||||||
|
bool steam = ch.Traction == Traction.Steam;
|
||||||
|
ch.Engine.VolumeLinear = steam ? 0 : ch.Gain * 0.45f;
|
||||||
|
if (steam && speed > 0 && ch.Gain > 0.02f)
|
||||||
|
{
|
||||||
|
ch.ChuffTimer -= dt;
|
||||||
|
if (ch.ChuffTimer <= 0)
|
||||||
|
{
|
||||||
|
Play(_sfx, _chuff, ch.Gain * 0.9f, _rng.Range(0.92f, 1.08f), _busSfx);
|
||||||
|
ch.ChuffTimer = Math.Max(ch.ChuffTimer, 0) + AudioMix.ChuffInterval(speed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Contains(int[] ids, int count, int id)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
if (ids[i] == id) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HasChannel(int train)
|
||||||
|
{
|
||||||
|
foreach (var ch in _channels)
|
||||||
|
{
|
||||||
|
if (ch.Train == train) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Assign(TrainChannel ch, int train, Protocol.Client.ClientWorld w)
|
||||||
|
{
|
||||||
|
ch.Train = train;
|
||||||
|
ch.Traction = TractionOf(train, w);
|
||||||
|
ch.Gain = 0;
|
||||||
|
ch.ChuffTimer = _rng.Next01() * 0.2f;
|
||||||
|
ch.Rumble.VolumeLinear = 0;
|
||||||
|
ch.Rumble.Play(_rng.Next01() * 1.5f);
|
||||||
|
ch.Engine.VolumeLinear = 0;
|
||||||
|
if (ch.Traction == Traction.Steam) ch.Engine.Stop();
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ch.Engine.Stream = ch.Traction == Traction.Diesel ? _diesel : _hum;
|
||||||
|
ch.Engine.Play(_rng.Next01() * 0.9f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Trazione della prima locomotiva del treno (vapore se non si sa).</summary>
|
||||||
|
private Traction TractionOf(int train, Protocol.Client.ClientWorld w)
|
||||||
|
{
|
||||||
|
if (!w.Trains.TryGetValue(train, out var info)) return Traction.Steam;
|
||||||
|
foreach (int vid in info.Vehicles)
|
||||||
|
{
|
||||||
|
if (w.Vehicles.TryGetValue(vid, out var v) && _vehicles.TryGetValue(v.Type, out var def) && def.Kind == VehicleKind.Locomotive && def.Traction is { } traction) return traction;
|
||||||
|
}
|
||||||
|
return Traction.Steam;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti).</summary>
|
||||||
|
public struct TerrainMix
|
||||||
|
{
|
||||||
|
public float River;
|
||||||
|
public float Lake;
|
||||||
|
public float Sea;
|
||||||
|
public float Town;
|
||||||
|
public float Forest;
|
||||||
|
public float Open;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli.</summary>
|
||||||
|
public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Miscelazione dell'audio senza dipendenze da Godot: guadagni dell'ambiente dal terreno e dallo
|
||||||
|
/// zoom, volume e intonazione dei treni dalla distanza sullo schermo e dalla velocità, scelta dei
|
||||||
|
/// treni più vicini senza allocazioni, ere dall'anno, dissolvenze e conversione in PCM. Le costanti
|
||||||
|
/// sono di resa sonora del client, non della simulazione.
|
||||||
|
/// </summary>
|
||||||
|
public static class AudioMix
|
||||||
|
{
|
||||||
|
/// <summary>Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme.</summary>
|
||||||
|
public const float FarZoom = 0.02f;
|
||||||
|
/// <summary>Zoom da cui ambiente e treni sono al massimo.</summary>
|
||||||
|
public const float NearZoom = 0.5f;
|
||||||
|
/// <summary>Canali dei treni: al più tanti treni suonano insieme.</summary>
|
||||||
|
public const int TrainChannels = 3;
|
||||||
|
/// <summary>Velocità (m/s) a cui il rotolamento è al massimo.</summary>
|
||||||
|
public const float FullSpeedMs = 25f;
|
||||||
|
/// <summary>Sbuffi al secondo da fermo (al passo) e alla velocità <see cref="ChuffFullSpeedMs"/>.</summary>
|
||||||
|
public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f;
|
||||||
|
/// <summary>Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti.</summary>
|
||||||
|
public const float ChuffFullSpeedMs = 30f;
|
||||||
|
|
||||||
|
public static float Clamp01(float x) => x < 0 ? 0 : x > 1 ? 1 : x;
|
||||||
|
|
||||||
|
public static float SmoothStep(float x)
|
||||||
|
{
|
||||||
|
x = Clamp01(x);
|
||||||
|
return x * x * (3 - 2 * x);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom.</summary>
|
||||||
|
public static float Closeness(float zoom)
|
||||||
|
{
|
||||||
|
if (zoom <= 0) return 0;
|
||||||
|
return SmoothStep((MathF.Log(zoom) - MathF.Log(FarZoom)) / (MathF.Log(NearZoom) - MathF.Log(FarZoom)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ambiente: il vento c'è sempre (più forte da lontano), acqua, mare e città seguono la
|
||||||
|
/// frazione del terreno visibile e si attenuano allontanandosi; gli uccelli solo da vicino in
|
||||||
|
/// campagna e nei boschi.
|
||||||
|
/// </summary>
|
||||||
|
public static AmbienceGains Ambience(float zoom, in TerrainMix t)
|
||||||
|
{
|
||||||
|
float close = Closeness(zoom);
|
||||||
|
float wind = 0.35f + 0.35f * (1 - close) + 0.15f * t.Open;
|
||||||
|
float water = Clamp01((t.River * 3 + t.Lake * 1.5f) * (0.25f + 0.75f * close));
|
||||||
|
float sea = Clamp01(t.Sea * 1.6f * (0.45f + 0.55f * close));
|
||||||
|
float city = Clamp01(t.Town * 4 * (0.15f + 0.85f * close));
|
||||||
|
float birds = Clamp01((t.Forest + t.Open * 0.6f) * close * close * (1 - t.Town * 2));
|
||||||
|
// l'acqua e la città coprono un po' il vento
|
||||||
|
wind *= 1 - 0.4f * MathF.Max(sea, city);
|
||||||
|
return new AmbienceGains(Clamp01(wind), water, sea, city, birds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Volume di un treno: vicinanza al centro dello schermo, velocità e zoom.</summary>
|
||||||
|
/// <param name="distancePx">Distanza in pixel dal centro dello schermo.</param>
|
||||||
|
/// <param name="radiusPx">Raggio oltre il quale non si sente (di solito metà della diagonale).</param>
|
||||||
|
public static float TrainGain(float distancePx, float radiusPx, float speedMs, float zoom)
|
||||||
|
{
|
||||||
|
if (radiusPx <= 0) return 0;
|
||||||
|
float near = 1 - Clamp01(distancePx / radiusPx);
|
||||||
|
float speed = Clamp01(speedMs / FullSpeedMs);
|
||||||
|
return near * near * (0.25f + 0.75f * speed) * (0.15f + 0.85f * Closeness(zoom));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Intonazione del rotolamento: più rapido e acuto con la velocità.</summary>
|
||||||
|
public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs);
|
||||||
|
|
||||||
|
/// <summary>Intonazione del motore (diesel o elettrico) con la velocità.</summary>
|
||||||
|
public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare
|
||||||
|
/// da <see cref="ChuffMinRate"/> a <see cref="ChuffMaxRate"/> fino a <see cref="ChuffFullSpeedMs"/>,
|
||||||
|
/// così segue la velocità su tutto l'esercizio normale. È una resa sonora, non il passo reale della
|
||||||
|
/// ruota: sullo schermo il tempo dei treni corre decine di volte più veloce e gli sbuffi reali
|
||||||
|
/// sarebbero un ronzio continuo.
|
||||||
|
/// </summary>
|
||||||
|
public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Inserisce un candidato nell'elenco ordinato dei più vicini (al più ids.Length): nessuna
|
||||||
|
/// allocazione, gli elenchi sono preparati una volta sola. Restituisce il nuovo conteggio.
|
||||||
|
/// </summary>
|
||||||
|
public static int InsertNearest(int[] ids, float[] distances, int count, int id, float distance)
|
||||||
|
{
|
||||||
|
int capacity = ids.Length;
|
||||||
|
if (count == capacity && distance >= distances[capacity - 1]) return count;
|
||||||
|
int i = Math.Min(count, capacity - 1);
|
||||||
|
while (i > 0 && distances[i - 1] > distance)
|
||||||
|
{
|
||||||
|
ids[i] = ids[i - 1];
|
||||||
|
distances[i] = distances[i - 1];
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
ids[i] = id;
|
||||||
|
distances[i] = distance;
|
||||||
|
return Math.Min(count + 1, capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno.</summary>
|
||||||
|
public static int EraIndex(int year, IReadOnlyList<int> froms)
|
||||||
|
{
|
||||||
|
int index = 0;
|
||||||
|
for (int i = 0; i < froms.Count; i++)
|
||||||
|
{
|
||||||
|
if (froms[i] <= year) index = i;
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Avvicina un valore al bersaglio con velocità costante (unità al secondo).</summary>
|
||||||
|
public static float Approach(float current, float target, float ratePerSecond, float dt)
|
||||||
|
{
|
||||||
|
float step = ratePerSecond * dt;
|
||||||
|
return current < target ? MathF.Min(target, current + step) : MathF.Max(target, current - step);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lineare → decibel, con −80 dB come silenzio.</summary>
|
||||||
|
public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear);
|
||||||
|
|
||||||
|
/// <summary>Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV).</summary>
|
||||||
|
public static byte[] ToPcm16(float[] samples)
|
||||||
|
{
|
||||||
|
var bytes = new byte[samples.Length * 2];
|
||||||
|
for (int i = 0; i < samples.Length; i++)
|
||||||
|
{
|
||||||
|
short s = (short)Math.Clamp((int)MathF.Round(samples[i] * 32767f), short.MinValue, short.MaxValue);
|
||||||
|
bytes[2 * i] = (byte)s;
|
||||||
|
bytes[2 * i + 1] = (byte)(s >> 8);
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
using Godot;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>Bus audio del client: Master e quattro bus che vi confluiscono.</summary>
|
||||||
|
public static class AudioBuses
|
||||||
|
{
|
||||||
|
public const string Master = "Master";
|
||||||
|
public const string Music = "Music";
|
||||||
|
public const string Ambience = "Ambience";
|
||||||
|
public const string Sfx = "Sfx";
|
||||||
|
public const string Ui = "Ui";
|
||||||
|
|
||||||
|
/// <summary>Nell'ordine dei cursori delle impostazioni.</summary>
|
||||||
|
public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Crea i bus che mancano (idempotente: chiamarla più volte non ne aggiunge altri) e un
|
||||||
|
/// limitatore sul Master, così la somma di musica, ambiente ed effetti non satura.
|
||||||
|
/// </summary>
|
||||||
|
public static void Ensure()
|
||||||
|
{
|
||||||
|
foreach (string name in All)
|
||||||
|
{
|
||||||
|
if (name == Master || AudioServer.GetBusIndex(name) >= 0) continue;
|
||||||
|
int index = AudioServer.BusCount;
|
||||||
|
AudioServer.AddBus(index);
|
||||||
|
AudioServer.SetBusName(index, name);
|
||||||
|
AudioServer.SetBusSend(index, Master);
|
||||||
|
}
|
||||||
|
bool limited = false;
|
||||||
|
for (int i = 0; i < AudioServer.GetBusEffectCount(0); i++)
|
||||||
|
{
|
||||||
|
if (AudioServer.GetBusEffect(0, i) is AudioEffectHardLimiter) limited = true;
|
||||||
|
}
|
||||||
|
if (!limited) AudioServer.AddBusEffect(0, new AudioEffectHardLimiter { CeilingDb = -0.5f });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
|
||||||
|
/// <c>user://settings.cfg</c> (lo stesso file della lingua e del server).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AudioSettings
|
||||||
|
{
|
||||||
|
public const string Path = "user://settings.cfg";
|
||||||
|
private const string Section = "audio";
|
||||||
|
|
||||||
|
private static readonly float[] Defaults = [0.8f, 0.55f, 0.7f, 0.8f, 0.7f];
|
||||||
|
|
||||||
|
/// <summary>Volumi nell'ordine di <see cref="AudioBuses.All"/>.</summary>
|
||||||
|
public float[] Volumes { get; } = (float[])Defaults.Clone();
|
||||||
|
|
||||||
|
public bool Muted { get; set; }
|
||||||
|
|
||||||
|
public static AudioSettings Load()
|
||||||
|
{
|
||||||
|
var s = new AudioSettings();
|
||||||
|
var cfg = new ConfigFile();
|
||||||
|
if (cfg.Load(Path) != Error.Ok) return s;
|
||||||
|
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||||
|
{
|
||||||
|
float v = (float)(double)cfg.GetValue(Section, Key(i), Defaults[i]);
|
||||||
|
s.Volumes[i] = Math.Clamp(v, 0, 1);
|
||||||
|
}
|
||||||
|
s.Muted = (bool)cfg.GetValue(Section, "muted", false);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
var cfg = new ConfigFile();
|
||||||
|
cfg.Load(Path);
|
||||||
|
for (int i = 0; i < AudioBuses.All.Length; i++) cfg.SetValue(Section, Key(i), Volumes[i]);
|
||||||
|
cfg.SetValue(Section, "muted", Muted);
|
||||||
|
cfg.Save(Path);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Key(int i) => AudioBuses.All[i].ToLowerInvariant();
|
||||||
|
|
||||||
|
/// <summary>Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).</summary>
|
||||||
|
public void Apply()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||||
|
{
|
||||||
|
int bus = AudioServer.GetBusIndex(AudioBuses.All[i]);
|
||||||
|
if (bus >= 0) AudioServer.SetBusVolumeDb(bus, AudioMix.LinearToDb(Volumes[i] * Volumes[i]));
|
||||||
|
}
|
||||||
|
AudioServer.SetBusMute(0, Muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
using Godot;
|
||||||
|
using RailEnterprise.Client.App;
|
||||||
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pannello «Audio» sopra a tutto: un cursore per bus (generale, musica, ambiente, effetti,
|
||||||
|
/// interfaccia) e il muto generale. I cambi si sentono subito; quando il pannello esce dall'albero
|
||||||
|
/// (anche chiudendo la finestra del gioco) si salvano in <c>user://settings.cfg</c>. Esc o un clic
|
||||||
|
/// sinistro fuori chiudono.
|
||||||
|
/// </summary>
|
||||||
|
public partial class AudioSettingsPanel : Control
|
||||||
|
{
|
||||||
|
private readonly AudioManager _audio;
|
||||||
|
private readonly List<(HSlider Slider, Label Value)> _rows = [];
|
||||||
|
private readonly CheckBox _mute = new() { Text = T("Muto") };
|
||||||
|
|
||||||
|
private static readonly string[] Captions = ["Volume generale", "Musica", "Ambiente", "Effetti", "Interfaccia"];
|
||||||
|
|
||||||
|
public AudioSettingsPanel(AudioManager audio) => _audio = audio;
|
||||||
|
|
||||||
|
public override void _Ready()
|
||||||
|
{
|
||||||
|
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||||
|
UiTheme.Apply(this);
|
||||||
|
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.5f), MouseFilter = MouseFilterEnum.Stop };
|
||||||
|
shade.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||||
|
shade.GuiInput += e =>
|
||||||
|
{
|
||||||
|
// solo il clic sinistro: la rotella e il tasto destro arrivano anch'essi come pressioni
|
||||||
|
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) Close();
|
||||||
|
};
|
||||||
|
AddChild(shade);
|
||||||
|
var center = new CenterContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||||
|
center.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||||
|
AddChild(center);
|
||||||
|
var panel = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||||
|
center.AddChild(panel);
|
||||||
|
var col = new VBoxContainer();
|
||||||
|
col.AddThemeConstantOverride("separation", 12);
|
||||||
|
panel.AddChild(col);
|
||||||
|
col.AddChild(UiTheme.TitleLabel(T("Audio"), 34));
|
||||||
|
|
||||||
|
for (int i = 0; i < Captions.Length; i++)
|
||||||
|
{
|
||||||
|
int bus = i;
|
||||||
|
var row = new HBoxContainer();
|
||||||
|
row.AddThemeConstantOverride("separation", 12);
|
||||||
|
var caption = UiTheme.Text(T(Captions[i]), 14, Palette.TextSecondary);
|
||||||
|
caption.CustomMinimumSize = new Vector2(150, 0);
|
||||||
|
row.AddChild(caption);
|
||||||
|
var slider = new HSlider
|
||||||
|
{
|
||||||
|
MinValue = 0, MaxValue = 1, Step = 0.05, SizeFlagsHorizontal = SizeFlags.ExpandFill,
|
||||||
|
SizeFlagsVertical = SizeFlags.ShrinkCenter, Value = _audio.Settings.Volumes[i],
|
||||||
|
};
|
||||||
|
var value = UiTheme.Text("", 14, bold: true);
|
||||||
|
value.CustomMinimumSize = new Vector2(48, 0);
|
||||||
|
value.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
slider.ValueChanged += v => _audio.SetVolume(bus, (float)v);
|
||||||
|
row.AddChild(slider);
|
||||||
|
row.AddChild(value);
|
||||||
|
col.AddChild(row);
|
||||||
|
_rows.Add((slider, value));
|
||||||
|
}
|
||||||
|
_mute.ButtonPressed = _audio.Settings.Muted;
|
||||||
|
_mute.Toggled += on => _audio.SetMuted(on);
|
||||||
|
col.AddChild(_mute);
|
||||||
|
var hint = UiTheme.Text(T("Il tasto M attiva e toglie il muto durante la partita."), 13, Palette.TextSecondary);
|
||||||
|
hint.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
col.AddChild(hint);
|
||||||
|
var close = UiTheme.Primary(T("Chiudi"));
|
||||||
|
close.Pressed += Close;
|
||||||
|
col.AddChild(close);
|
||||||
|
_audio.SettingsChanged += Refresh;
|
||||||
|
Refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _ExitTree()
|
||||||
|
{
|
||||||
|
_audio.SettingsChanged -= Refresh;
|
||||||
|
_audio.SaveSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Refresh()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < _rows.Count; i++)
|
||||||
|
{
|
||||||
|
_rows[i].Slider.SetValueNoSignal(_audio.Settings.Volumes[i]);
|
||||||
|
_rows[i].Value.Text = $"{Math.Round(_audio.Settings.Volumes[i] * 100):0} %";
|
||||||
|
}
|
||||||
|
_mute.SetPressedNoSignal(_audio.Settings.Muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Input(InputEvent e)
|
||||||
|
{
|
||||||
|
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
|
||||||
|
{
|
||||||
|
Close();
|
||||||
|
GetViewport().SetInputAsHandled();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Close()
|
||||||
|
{
|
||||||
|
if (IsQueuedForDeletion()) return;
|
||||||
|
QueueFree();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Temi musicali procedurali per era, senza dipendenze da Godot. Ogni era ha uno stile (tempo,
|
||||||
|
/// metro, scala, timbri: valzer da carillon e fisarmonica per il vapore, organo e basso che
|
||||||
|
/// cammina per il diesel, vibrafono e archi per l'elettrico, arpeggi a impulsi per l'alta
|
||||||
|
/// velocità); progressione, arpeggio e melodia escono da un seme fisso (hash dell'id dell'era),
|
||||||
|
/// quindi lo stesso tema a ogni avvio. Forma in 16 battute: introduzione (accompagnamento),
|
||||||
|
/// melodia, melodia variata, coda; le code delle note rientrano dall'inizio, così l'anello si
|
||||||
|
/// ripete senza scatti. Uscita mono a <see cref="Synth.Rate"/> Hz.
|
||||||
|
/// </summary>
|
||||||
|
public static class MusicComposer
|
||||||
|
{
|
||||||
|
public const int Bars = 16;
|
||||||
|
|
||||||
|
public enum Timbre { MusicBox, Accordion, Organ, Vibraphone, Strings, Pulse, Saw, SoftBass, PluckBass }
|
||||||
|
|
||||||
|
public enum Comping { Held, Waltz }
|
||||||
|
|
||||||
|
/// <summary>Stile di un'era.</summary>
|
||||||
|
public sealed record Style(int Bpm, int BeatsPerBar, int[] Scale, int RootMidi, Timbre Pad, Comping Comping,
|
||||||
|
Timbre Arp, int ArpPerBeat, Timbre Lead, Timbre Bass, bool WalkingBass, float Swing);
|
||||||
|
|
||||||
|
private static readonly int[] Major = [0, 2, 4, 5, 7, 9, 11];
|
||||||
|
private static readonly int[] Mixolydian = [0, 2, 4, 5, 7, 9, 10];
|
||||||
|
private static readonly int[] Dorian = [0, 2, 3, 5, 7, 9, 10];
|
||||||
|
|
||||||
|
/// <summary>Progressioni per grado della scala (0 = primo grado), una battuta per accordo.</summary>
|
||||||
|
private static readonly int[][] Progressions =
|
||||||
|
[
|
||||||
|
[0, 3, 4, 0], [0, 5, 3, 4], [0, 4, 5, 3], [1, 4, 0, 5], [5, 3, 0, 4], [0, 3, 1, 4],
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo).</summary>
|
||||||
|
public static Style StyleFor(int eraIndex) => (Math.Max(0, eraIndex) % 4) switch
|
||||||
|
{
|
||||||
|
0 => new Style(116, 3, Major, 62, Timbre.Accordion, Comping.Waltz, Timbre.MusicBox, 0, Timbre.MusicBox, Timbre.SoftBass, false, 0),
|
||||||
|
1 => new Style(96, 4, Mixolydian, 60, Timbre.Organ, Comping.Held, Timbre.Vibraphone, 1, Timbre.Organ, Timbre.PluckBass, true, 0.18f),
|
||||||
|
2 => new Style(104, 4, Major, 65, Timbre.Strings, Comping.Held, Timbre.Vibraphone, 2, Timbre.Vibraphone, Timbre.SoftBass, false, 0),
|
||||||
|
_ => new Style(124, 4, Dorian, 57, Timbre.Saw, Comping.Held, Timbre.Pulse, 4, Timbre.Saw, Timbre.SoftBass, false, 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Seme fisso del tema: hash dell'id dell'era e della sua posizione.</summary>
|
||||||
|
public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL);
|
||||||
|
|
||||||
|
/// <summary>Durata dell'anello in secondi.</summary>
|
||||||
|
public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ timbri
|
||||||
|
|
||||||
|
private sealed class Voice
|
||||||
|
{
|
||||||
|
/// <summary>Ampiezza della n-esima armonica in Harmonics[n−1].</summary>
|
||||||
|
public required float[] Harmonics { get; init; }
|
||||||
|
public float Attack { get; init; } = 0.005f;
|
||||||
|
/// <summary>Decadimento verso il sostegno (s).</summary>
|
||||||
|
public float Decay { get; init; } = 0.3f;
|
||||||
|
public float Sustain { get; init; }
|
||||||
|
public float Release { get; init; } = 0.1f;
|
||||||
|
/// <summary>Copie leggermente scordate (coro).</summary>
|
||||||
|
public float[] Detune { get; init; } = [0];
|
||||||
|
public float TremoloHz { get; init; }
|
||||||
|
public float TremoloDepth { get; init; }
|
||||||
|
public float VibratoDepth { get; init; }
|
||||||
|
|
||||||
|
// tabelle per numero di armoniche tenute (una per registro, costruite al primo uso)
|
||||||
|
private readonly Dictionary<int, float[]> _tables = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto
|
||||||
|
/// <see cref="MaxHarmonicShare"/> della frequenza di campionamento: quelle oltre Nyquist
|
||||||
|
/// tornerebbero indietro come toni stonati.
|
||||||
|
/// </summary>
|
||||||
|
public float[] TableFor(float frequency)
|
||||||
|
{
|
||||||
|
int n = Math.Clamp((int)(MaxHarmonicShare * Synth.Rate / frequency), 1, Harmonics.Length);
|
||||||
|
if (!_tables.TryGetValue(n, out var table))
|
||||||
|
{
|
||||||
|
table = Table(Harmonics, n);
|
||||||
|
_tables[n] = table;
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro).</summary>
|
||||||
|
private const float MaxHarmonicShare = 0.45f;
|
||||||
|
|
||||||
|
private const int TableSize = 2048;
|
||||||
|
|
||||||
|
/// <summary>Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]).</summary>
|
||||||
|
private static float[] Table(float[] harmonics, int count)
|
||||||
|
{
|
||||||
|
var t = new float[TableSize];
|
||||||
|
for (int i = 0; i < TableSize; i++)
|
||||||
|
{
|
||||||
|
float x = MathF.PI * 2 * i / TableSize;
|
||||||
|
float v = 0;
|
||||||
|
for (int h = 0; h < count; h++) v += harmonics[h] * MathF.Sin(x * (h + 1));
|
||||||
|
t[i] = v;
|
||||||
|
}
|
||||||
|
Synth.Normalize(t, 1);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float[] SawHarmonics(int n)
|
||||||
|
{
|
||||||
|
var h = new float[n];
|
||||||
|
for (int i = 0; i < n; i++) h[i] = 1f / (i + 1);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float[] PulseHarmonics(int n, float duty)
|
||||||
|
{
|
||||||
|
var h = new float[n];
|
||||||
|
for (int i = 0; i < n; i++) h[i] = MathF.Abs(MathF.Sin(MathF.PI * (i + 1) * duty)) / (i + 1);
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Voice VoiceFor(Timbre timbre) => timbre switch
|
||||||
|
{
|
||||||
|
Timbre.MusicBox => new Voice { Harmonics = [1, 0.1f, 0.35f, 0, 0.12f], Attack = 0.002f, Decay = 0.7f, Sustain = 0, Release = 0.6f },
|
||||||
|
Timbre.Accordion => new Voice { Harmonics = [1, 0.5f, 0.6f, 0.3f, 0.25f, 0.15f], Attack = 0.03f, Decay = 0.2f, Sustain = 0.8f, Release = 0.08f, Detune = [0, 0.004f], TremoloHz = 5, TremoloDepth = 0.12f },
|
||||||
|
Timbre.Organ => new Voice { Harmonics = [1, 0.8f, 0.6f, 0.4f, 0, 0.3f, 0, 0.2f], Attack = 0.01f, Decay = 0.1f, Sustain = 0.9f, Release = 0.06f, TremoloHz = 6, TremoloDepth = 0.1f },
|
||||||
|
Timbre.Vibraphone => new Voice { Harmonics = [1, 0, 0, 0.25f], Attack = 0.003f, Decay = 1.1f, Sustain = 0, Release = 0.8f, TremoloHz = 5, TremoloDepth = 0.3f },
|
||||||
|
Timbre.Strings => new Voice { Harmonics = SawHarmonics(8), Attack = 0.3f, Decay = 0.5f, Sustain = 0.85f, Release = 0.35f, Detune = [-0.003f, 0, 0.003f], VibratoDepth = 0.003f },
|
||||||
|
Timbre.Pulse => new Voice { Harmonics = PulseHarmonics(9, 0.25f), Attack = 0.004f, Decay = 0.22f, Sustain = 0, Release = 0.15f },
|
||||||
|
Timbre.Saw => new Voice { Harmonics = SawHarmonics(10), Attack = 0.08f, Decay = 0.4f, Sustain = 0.7f, Release = 0.25f, Detune = [-0.005f, 0.005f], VibratoDepth = 0.002f },
|
||||||
|
Timbre.PluckBass => new Voice { Harmonics = [1, 0.5f, 0.25f, 0.1f], Attack = 0.005f, Decay = 0.35f, Sustain = 0.15f, Release = 0.08f },
|
||||||
|
_ => new Voice { Harmonics = [1, 0.3f, 0.1f], Attack = 0.01f, Decay = 0.4f, Sustain = 0.6f, Release = 0.1f },
|
||||||
|
};
|
||||||
|
|
||||||
|
private static float Frequency(float midi) => 440f * MathF.Pow(2, (midi - 69) / 12f);
|
||||||
|
|
||||||
|
/// <summary>Suona una nota nell'anello (con la coda che rientra dall'inizio).</summary>
|
||||||
|
private static void Note(float[] loop, Voice v, float startS, float durS, float midi, float gain)
|
||||||
|
{
|
||||||
|
int rate = Synth.Rate;
|
||||||
|
float f = Frequency(midi);
|
||||||
|
var table = v.TableFor(f);
|
||||||
|
int start = (int)(startS * rate);
|
||||||
|
float total = durS + v.Release;
|
||||||
|
int samples = Math.Min(loop.Length, (int)(total * rate));
|
||||||
|
foreach (float detune in v.Detune)
|
||||||
|
{
|
||||||
|
float inc = f * (1 + detune) * TableSize / rate;
|
||||||
|
float phase = (detune + 0.5f) * 97 % TableSize;
|
||||||
|
float g = gain / v.Detune.Length;
|
||||||
|
for (int i = 0; i < samples; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)rate;
|
||||||
|
float env = t < v.Attack ? t / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(t - v.Attack) / v.Decay);
|
||||||
|
if (t > durS)
|
||||||
|
{
|
||||||
|
// rilascio dal livello raggiunto alla fine della nota
|
||||||
|
float atEnd = durS < v.Attack ? durS / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(durS - v.Attack) / v.Decay);
|
||||||
|
env = atEnd * MathF.Max(0, 1 - (t - durS) / v.Release);
|
||||||
|
}
|
||||||
|
if (v.TremoloDepth > 0) env *= 1 - v.TremoloDepth * (0.5f + 0.5f * MathF.Sin(MathF.PI * 2 * v.TremoloHz * t));
|
||||||
|
float step = v.VibratoDepth > 0 ? inc * (1 + v.VibratoDepth * MathF.Sin(MathF.PI * 2 * 5.5f * t)) : inc;
|
||||||
|
phase += step;
|
||||||
|
if (phase >= TableSize) phase -= TableSize;
|
||||||
|
int i0 = (int)phase;
|
||||||
|
float frac = phase - i0;
|
||||||
|
float s = table[i0] + (table[(i0 + 1) & (TableSize - 1)] - table[i0]) * frac;
|
||||||
|
loop[(start + i) % loop.Length] += s * env * g;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava).</summary>
|
||||||
|
private static int Degree(Style s, int degree)
|
||||||
|
{
|
||||||
|
int n = s.Scale.Length;
|
||||||
|
int octave = (int)Math.Floor(degree / (double)n);
|
||||||
|
int d = degree - octave * n;
|
||||||
|
return s.RootMidi + s.Scale[d] + 12 * octave;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Compone e sintetizza il tema dell'era: campioni mono in [−1, 1].</summary>
|
||||||
|
public static float[] Compose(int eraIndex, string eraId)
|
||||||
|
{
|
||||||
|
var style = StyleFor(eraIndex);
|
||||||
|
var rng = new SynthRng(Seed(eraIndex, eraId));
|
||||||
|
float beat = 60f / style.Bpm;
|
||||||
|
float bar = beat * style.BeatsPerBar;
|
||||||
|
var loop = new float[(int)(LengthSeconds(style) * Synth.Rate)];
|
||||||
|
var progression = Progressions[rng.Next(Progressions.Length)];
|
||||||
|
var pad = VoiceFor(style.Pad);
|
||||||
|
var arp = VoiceFor(style.Arp);
|
||||||
|
var lead = VoiceFor(style.Lead);
|
||||||
|
var bass = VoiceFor(style.Bass);
|
||||||
|
bool arpDown = rng.Next(2) == 0;
|
||||||
|
|
||||||
|
// motivo di quattro battute: un ritmo per battuta (in ottavi) e gradi vicini all'accordo
|
||||||
|
int eighths = style.BeatsPerBar * 2;
|
||||||
|
var motif = new List<(int Bar, int Eighth, int Length, int Degree)>();
|
||||||
|
int current = 7 + progression[0];
|
||||||
|
for (int b = 0; b < 4; b++)
|
||||||
|
{
|
||||||
|
int chord = progression[b];
|
||||||
|
int e = 0;
|
||||||
|
while (e < eighths)
|
||||||
|
{
|
||||||
|
int len = rng.Next(4) switch { 0 => 1, 1 or 2 => 2, _ => 3 };
|
||||||
|
len = Math.Min(len, eighths - e);
|
||||||
|
if (rng.Next(5) == 0 && e > 0)
|
||||||
|
{
|
||||||
|
e += len; // pausa
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
bool strong = e % (style.BeatsPerBar == 3 ? 6 : 4) == 0;
|
||||||
|
if (strong)
|
||||||
|
{
|
||||||
|
// sui tempi forti una nota dell'accordo vicina alla precedente
|
||||||
|
int best = current, bestD = int.MaxValue;
|
||||||
|
for (int k = -1; k <= 2; k++)
|
||||||
|
{
|
||||||
|
foreach (int ct in new[] { 0, 2, 4 })
|
||||||
|
{
|
||||||
|
int cand = chord + ct + 7 * k;
|
||||||
|
int dist = Math.Abs(cand - current);
|
||||||
|
if (cand >= 4 && cand <= 13 && dist < bestD)
|
||||||
|
{
|
||||||
|
bestD = dist;
|
||||||
|
best = cand;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current = best;
|
||||||
|
}
|
||||||
|
else current = Math.Clamp(current + rng.Next(5) - 2, 4, 13);
|
||||||
|
motif.Add((b, e, len, current));
|
||||||
|
e += len;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// l'ultima nota del motivo torna sulla tonica
|
||||||
|
if (motif.Count > 0) motif[^1] = motif[^1] with { Degree = 7 };
|
||||||
|
|
||||||
|
for (int barIndex = 0; barIndex < Bars; barIndex++)
|
||||||
|
{
|
||||||
|
int chord = progression[barIndex % 4];
|
||||||
|
float t0 = barIndex * bar;
|
||||||
|
int[] tones = [Degree(style, chord), Degree(style, chord + 2), Degree(style, chord + 4)];
|
||||||
|
|
||||||
|
// accompagnamento
|
||||||
|
if (style.Comping == Comping.Waltz)
|
||||||
|
{
|
||||||
|
for (int k = 1; k < style.BeatsPerBar; k++)
|
||||||
|
foreach (int m in tones) Note(loop, pad, t0 + k * beat, beat * 0.55f, m, 0.11f);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (int m in tones) Note(loop, pad, t0, bar * 0.95f, m, 0.12f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// basso: fondamentale (e quinta) o basso che cammina sulle note dell'accordo
|
||||||
|
int root = Degree(style, chord) - 24;
|
||||||
|
if (style.WalkingBass)
|
||||||
|
{
|
||||||
|
int next = Degree(style, progression[(barIndex + 1) % 4]) - 24;
|
||||||
|
int[] walk = [root, root + (tones[1] - tones[0]), root + 7, next + (next > root ? -1 : 1)];
|
||||||
|
for (int k = 0; k < style.BeatsPerBar; k++) Note(loop, bass, t0 + k * beat, beat * 0.9f, walk[k % walk.Length], 0.32f);
|
||||||
|
}
|
||||||
|
else if (style.Comping == Comping.Waltz) Note(loop, bass, t0, beat * 0.9f, root, 0.34f);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Note(loop, bass, t0, beat * 1.8f, root, 0.32f);
|
||||||
|
Note(loop, bass, t0 + 2 * beat, beat * 1.8f, root + 7, 0.26f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// arpeggio (in introduzione e coda più presente)
|
||||||
|
if (style.ArpPerBeat > 0)
|
||||||
|
{
|
||||||
|
int steps = style.BeatsPerBar * style.ArpPerBeat;
|
||||||
|
float step = beat / style.ArpPerBeat;
|
||||||
|
float gain = barIndex is < 4 or >= 12 ? 0.13f : 0.08f;
|
||||||
|
for (int k = 0; k < steps; k++)
|
||||||
|
{
|
||||||
|
int idx = arpDown ? 3 - k % 4 : k % 4;
|
||||||
|
int m = idx < 3 ? tones[idx] + 12 : tones[0] + 24;
|
||||||
|
float swing = style.Swing > 0 && k % 2 == 1 ? style.Swing * step : 0;
|
||||||
|
Note(loop, arp, t0 + k * step + swing, step * 0.8f, m, gain);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// melodia nelle battute 4–11 (la seconda volta un'ottava sopra le ultime due battute)
|
||||||
|
if (barIndex is >= 4 and < 12)
|
||||||
|
{
|
||||||
|
int motifBar = barIndex % 4;
|
||||||
|
bool variation = barIndex >= 8;
|
||||||
|
foreach (var n in motif)
|
||||||
|
{
|
||||||
|
if (n.Bar != motifBar) continue;
|
||||||
|
float eighth = beat / 2;
|
||||||
|
float swing = style.Swing > 0 && n.Eighth % 2 == 1 ? style.Swing * eighth : 0;
|
||||||
|
int midi = Degree(style, n.Degree) + (variation && motifBar >= 2 ? 12 : 0);
|
||||||
|
Note(loop, lead, t0 + n.Eighth * eighth + swing, n.Length * eighth * 0.92f, midi, 0.2f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// un po' di spazio: due echi smorzati sull'anello, poi limitazione morbida
|
||||||
|
Echo(loop, 0.27f, 0.22f);
|
||||||
|
Echo(loop, 0.41f, 0.15f);
|
||||||
|
Synth.Normalize(loop, 1);
|
||||||
|
for (int i = 0; i < loop.Length; i++) loop[i] = MathF.Tanh(loop[i] * 1.2f) * 0.7f;
|
||||||
|
return loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Eco con retroazione su un anello (due giri per la continuità all'inizio).</summary>
|
||||||
|
private static void Echo(float[] loop, float delayS, float feedback)
|
||||||
|
{
|
||||||
|
int d = Math.Max(1, (int)(delayS * Synth.Rate));
|
||||||
|
var lp = Biquad.LowPass(2500, 0.7f, Synth.Rate);
|
||||||
|
var wet = new float[loop.Length];
|
||||||
|
for (int pass = 0; pass < 2; pass++)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < loop.Length; i++)
|
||||||
|
{
|
||||||
|
int j = (i - d + loop.Length) % loop.Length;
|
||||||
|
wet[i] = lp.Process(loop[j] + wet[j] * feedback) * feedback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < loop.Length; i++) loop[i] += wet[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using Godot;
|
||||||
|
using RailEnterprise.Client.App;
|
||||||
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo.</summary>
|
||||||
|
public partial class SpeakerButton : Button
|
||||||
|
{
|
||||||
|
public SpeakerButton()
|
||||||
|
{
|
||||||
|
Flat = true;
|
||||||
|
CustomMinimumSize = new Vector2(40, 40);
|
||||||
|
TooltipText = T("Audio (M: muto)");
|
||||||
|
Pressed += () => AudioManager.Instance?.ShowSettings();
|
||||||
|
MouseEntered += QueueRedraw;
|
||||||
|
MouseExited += QueueRedraw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _EnterTree()
|
||||||
|
{
|
||||||
|
if (AudioManager.Instance is { } audio) audio.SettingsChanged += QueueRedraw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _ExitTree()
|
||||||
|
{
|
||||||
|
if (AudioManager.Instance is { } audio) audio.SettingsChanged -= QueueRedraw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Draw()
|
||||||
|
{
|
||||||
|
bool muted = AudioManager.Instance?.Settings.Muted ?? false;
|
||||||
|
var col = IsHovered() ? Palette.AmberLight : muted ? Palette.TextSecondary : Palette.Text;
|
||||||
|
var c = Size / 2;
|
||||||
|
const float w = 2f;
|
||||||
|
// cassa e cono
|
||||||
|
DrawColoredPolygon([c + new Vector2(-10, -4), c + new Vector2(-5, -4), c + new Vector2(1, -10), c + new Vector2(1, 10), c + new Vector2(-5, 4), c + new Vector2(-10, 4)], col);
|
||||||
|
if (muted)
|
||||||
|
{
|
||||||
|
DrawLine(c + new Vector2(5, -5), c + new Vector2(13, 5), Palette.Danger, w);
|
||||||
|
DrawLine(c + new Vector2(13, -5), c + new Vector2(5, 5), Palette.Danger, w);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
DrawArc(c + new Vector2(1, 0), 6, -0.9f, 0.9f, 10, col, w);
|
||||||
|
DrawArc(c + new Vector2(1, 0), 11, -0.9f, 0.9f, 14, col, w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,554 @@
|
|||||||
|
namespace RailEnterprise.Client.Audio;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il <c>Rng</c> della
|
||||||
|
/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client.
|
||||||
|
/// </summary>
|
||||||
|
public struct SynthRng
|
||||||
|
{
|
||||||
|
private ulong _s;
|
||||||
|
|
||||||
|
public SynthRng(ulong seed) => _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed;
|
||||||
|
|
||||||
|
public ulong NextU64()
|
||||||
|
{
|
||||||
|
_s ^= _s >> 12;
|
||||||
|
_s ^= _s << 25;
|
||||||
|
_s ^= _s >> 27;
|
||||||
|
return _s * 2685821657736338717UL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Numero in [0, 1).</summary>
|
||||||
|
public float Next01() => (NextU64() >> 40) * (1f / (1 << 24));
|
||||||
|
|
||||||
|
/// <summary>Numero in [−1, 1).</summary>
|
||||||
|
public float NextSigned() => Next01() * 2f - 1f;
|
||||||
|
|
||||||
|
/// <summary>Intero in [0, n).</summary>
|
||||||
|
public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n);
|
||||||
|
|
||||||
|
/// <summary>Numero in [a, b).</summary>
|
||||||
|
public float Range(float a, float b) => a + (b - a) * Next01();
|
||||||
|
|
||||||
|
/// <summary>FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era).</summary>
|
||||||
|
public static ulong Hash(string text)
|
||||||
|
{
|
||||||
|
ulong h = 14695981039346656037UL;
|
||||||
|
foreach (char c in text)
|
||||||
|
{
|
||||||
|
h ^= c;
|
||||||
|
h *= 1099511628211UL;
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario.</summary>
|
||||||
|
public struct Biquad
|
||||||
|
{
|
||||||
|
private float _b0, _b1, _b2, _a1, _a2, _z1, _z2;
|
||||||
|
|
||||||
|
private static Biquad Make(float b0, float b1, float b2, float a0, float a1, float a2) =>
|
||||||
|
new() { _b0 = b0 / a0, _b1 = b1 / a0, _b2 = b2 / a0, _a1 = a1 / a0, _a2 = a2 / a0 };
|
||||||
|
|
||||||
|
private static (float Cos, float Alpha) W(float freq, float q, int rate)
|
||||||
|
{
|
||||||
|
float w0 = 2 * MathF.PI * Math.Clamp(freq, 1, rate * 0.45f) / rate;
|
||||||
|
return (MathF.Cos(w0), MathF.Sin(w0) / (2 * q));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Biquad LowPass(float freq, float q, int rate)
|
||||||
|
{
|
||||||
|
var (c, a) = W(freq, q, rate);
|
||||||
|
return Make((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + a, -2 * c, 1 - a);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Biquad HighPass(float freq, float q, int rate)
|
||||||
|
{
|
||||||
|
var (c, a) = W(freq, q, rate);
|
||||||
|
return Make((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + a, -2 * c, 1 - a);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Biquad BandPass(float freq, float q, int rate)
|
||||||
|
{
|
||||||
|
var (c, a) = W(freq, q, rate);
|
||||||
|
return Make(a, 0, -a, 1 + a, -2 * c, 1 - a);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile).</summary>
|
||||||
|
public void Retune(Biquad coefficients)
|
||||||
|
{
|
||||||
|
_b0 = coefficients._b0;
|
||||||
|
_b1 = coefficients._b1;
|
||||||
|
_b2 = coefficients._b2;
|
||||||
|
_a1 = coefficients._a1;
|
||||||
|
_a2 = coefficients._a2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float Process(float x)
|
||||||
|
{
|
||||||
|
float y = _b0 * x + _z1;
|
||||||
|
_z1 = _b1 * x - _a1 * y + _z2;
|
||||||
|
_z2 = _b2 * x - _a2 * y;
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione
|
||||||
|
/// restituisce campioni mono in virgola mobile a <see cref="Rate"/> Hz, da convertire in PCM a
|
||||||
|
/// 16 bit con <see cref="AudioMix.ToPcm16"/>. Gli anelli («Loop») si ripetono senza scatti: i
|
||||||
|
/// filtri girano due volte sullo stesso rumore (la seconda passata parte dallo stato della fine),
|
||||||
|
/// le modulazioni hanno un numero intero di periodi nell'anello e le code degli eventi brevi
|
||||||
|
/// rientrano dall'inizio. Semi fissi: stesso suono a ogni avvio.
|
||||||
|
/// </summary>
|
||||||
|
public static class Synth
|
||||||
|
{
|
||||||
|
/// <summary>Frequenza di campionamento di tutti i suoni (Hz).</summary>
|
||||||
|
public const int Rate = 22050;
|
||||||
|
|
||||||
|
private const float Tau = MathF.PI * 2;
|
||||||
|
|
||||||
|
public static float[] Buffer(float seconds) => new float[Math.Max(1, (int)(seconds * Rate))];
|
||||||
|
|
||||||
|
/// <summary>Inviluppo attacco lineare e decadimento esponenziale.</summary>
|
||||||
|
public static float Env(float t, float attack, float decay) =>
|
||||||
|
t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay);
|
||||||
|
|
||||||
|
/// <summary>Porta il picco al valore indicato.</summary>
|
||||||
|
public static void Normalize(float[] buffer, float peak)
|
||||||
|
{
|
||||||
|
float max = 0;
|
||||||
|
foreach (float s in buffer) max = Math.Max(max, Math.Abs(s));
|
||||||
|
if (max < 1e-6f) return;
|
||||||
|
float k = peak / max;
|
||||||
|
for (int i = 0; i < buffer.Length; i++) buffer[i] *= k;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine).</summary>
|
||||||
|
public static void FadeOut(float[] buffer, float seconds = 0.01f)
|
||||||
|
{
|
||||||
|
int n = Math.Min(buffer.Length, (int)(seconds * Rate));
|
||||||
|
for (int i = 0; i < n; i++) buffer[buffer.Length - 1 - i] *= i / (float)n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rumore bianco ripetibile.</summary>
|
||||||
|
public static float[] Noise(int length, ulong seed)
|
||||||
|
{
|
||||||
|
var rng = new SynthRng(seed);
|
||||||
|
var n = new float[length];
|
||||||
|
for (int i = 0; i < length; i++) n[i] = rng.NextSigned();
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima.</summary>
|
||||||
|
public static float[] LoopFilter(float[] input, Biquad filter)
|
||||||
|
{
|
||||||
|
var output = new float[input.Length];
|
||||||
|
for (int pass = 0; pass < 2; pass++)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < input.Length; i++) output[i] = filter.Process(input[i]);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate.</summary>
|
||||||
|
public static float[] BrownLoop(int length, ulong seed, float leak)
|
||||||
|
{
|
||||||
|
var white = Noise(length, seed);
|
||||||
|
var brown = new float[length];
|
||||||
|
float acc = 0;
|
||||||
|
for (int pass = 0; pass < 2; pass++)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
acc = acc * leak + white[i] * (1 - leak) * 10;
|
||||||
|
brown[i] = acc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return brown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio.</summary>
|
||||||
|
public static void MixWrapped(float[] loop, float[] sound, int at, float gain)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < sound.Length; i++) loop[(at + i) % loop.Length] += sound[i] * gain;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ interfaccia
|
||||||
|
|
||||||
|
/// <summary>Clic dell'interfaccia: un colpetto secco e brillante.</summary>
|
||||||
|
public static float[] Click()
|
||||||
|
{
|
||||||
|
var b = Buffer(0.035f);
|
||||||
|
var noise = Noise(b.Length, 11);
|
||||||
|
var hp = Biquad.HighPass(2500, 0.7f, Rate);
|
||||||
|
for (int i = 0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
b[i] = MathF.Sin(Tau * 1800 * t) * MathF.Exp(-t / 0.006f) * 0.6f + hp.Process(noise[i]) * MathF.Exp(-t / 0.003f) * 0.5f;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.5f);
|
||||||
|
FadeOut(b, 0.005f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale.</summary>
|
||||||
|
private static void Tone(float[] b, float start, float freq, float decay, float gain, float[] harmonics)
|
||||||
|
{
|
||||||
|
int s0 = (int)(start * Rate);
|
||||||
|
for (int i = s0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = (i - s0) / (float)Rate;
|
||||||
|
float env = Env(t, 0.005f, decay);
|
||||||
|
if (env < 1e-4f && t > 0.01f) break;
|
||||||
|
float v = 0;
|
||||||
|
for (int h = 0; h < harmonics.Length; h++)
|
||||||
|
{
|
||||||
|
float f = freq * (h + 1);
|
||||||
|
if (harmonics[h] != 0 && f < Rate * 0.45f) v += harmonics[h] * MathF.Sin(Tau * f * t);
|
||||||
|
}
|
||||||
|
b[i] += v * env * gain;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Esito positivo di un comando: due note ascendenti (la, mi).</summary>
|
||||||
|
public static float[] Confirm()
|
||||||
|
{
|
||||||
|
var b = Buffer(0.32f);
|
||||||
|
float[] h = [1, 0.3f];
|
||||||
|
Tone(b, 0, 880, 0.09f, 1, h);
|
||||||
|
Tone(b, 0.07f, 1318.5f, 0.11f, 0.9f, h);
|
||||||
|
Normalize(b, 0.42f);
|
||||||
|
FadeOut(b);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Comando rifiutato: due note scure discendenti.</summary>
|
||||||
|
public static float[] Error()
|
||||||
|
{
|
||||||
|
var b = Buffer(0.38f);
|
||||||
|
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||||
|
Tone(b, 0, 330, 0.12f, 1, h);
|
||||||
|
Tone(b, 0.1f, 247, 0.14f, 1, h);
|
||||||
|
var lp = Biquad.LowPass(1800, 0.7f, Rate);
|
||||||
|
for (int i = 0; i < b.Length; i++) b[i] = lp.Process(b[i]);
|
||||||
|
Normalize(b, 0.45f);
|
||||||
|
FadeOut(b);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade).</summary>
|
||||||
|
private static void Bell(float[] b, float start, float freq, float gain, float decay = 0.6f)
|
||||||
|
{
|
||||||
|
int s0 = (int)(start * Rate);
|
||||||
|
for (int i = s0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = (i - s0) / (float)Rate;
|
||||||
|
float index = 2.5f * MathF.Exp(-t / 0.3f);
|
||||||
|
b[i] += MathF.Sin(Tau * freq * t + index * MathF.Sin(Tau * freq * 1.4f * t)) * Env(t, 0.003f, decay) * gain;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica.</summary>
|
||||||
|
public static float[] Notify(int level)
|
||||||
|
{
|
||||||
|
float[] b;
|
||||||
|
switch (level)
|
||||||
|
{
|
||||||
|
case <= 0:
|
||||||
|
b = Buffer(1.0f);
|
||||||
|
Bell(b, 0, 1046.5f, 1);
|
||||||
|
Bell(b, 0.12f, 1568f, 0.6f);
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
b = Buffer(1.2f);
|
||||||
|
Bell(b, 0, 784f, 1, 0.7f);
|
||||||
|
Bell(b, 0.18f, 622.3f, 1, 0.7f);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// tre impulsi dissonanti: si distinguono anche sopra la musica
|
||||||
|
b = Buffer(1.0f);
|
||||||
|
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||||
|
for (int k = 0; k < 3; k++)
|
||||||
|
{
|
||||||
|
Tone(b, k * 0.22f, 523.3f, 0.09f, 0.8f, h);
|
||||||
|
Tone(b, k * 0.22f, 554.4f, 0.09f, 0.6f, h);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.55f);
|
||||||
|
FadeOut(b);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cantiere completato: due colpi metallici e un arpeggio maggiore.</summary>
|
||||||
|
public static float[] BuildComplete()
|
||||||
|
{
|
||||||
|
var b = Buffer(1.5f);
|
||||||
|
var noise = Noise(b.Length, 23);
|
||||||
|
foreach (var (at, gain) in new[] { (0f, 1f), (0.16f, 0.7f) })
|
||||||
|
{
|
||||||
|
int s0 = (int)(at * Rate);
|
||||||
|
var bp = Biquad.BandPass(2500, 4, Rate);
|
||||||
|
for (int i = s0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = (i - s0) / (float)Rate;
|
||||||
|
float metal = MathF.Sin(Tau * 420 * t + 3 * MathF.Exp(-t / 0.08f) * MathF.Sin(Tau * 420 * 2.76f * t));
|
||||||
|
b[i] += (bp.Process(noise[i]) * 2 * Env(t, 0.001f, 0.04f) + metal * Env(t, 0.002f, 0.25f)) * gain * 0.6f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
float[] pluck = [1, 0.4f, 0.15f];
|
||||||
|
float[] notes = [523.3f, 659.3f, 784f, 1046.5f];
|
||||||
|
for (int k = 0; k < notes.Length; k++) Tone(b, 0.32f + k * 0.08f, notes[k], k == notes.Length - 1 ? 0.35f : 0.15f, 0.7f, pluck);
|
||||||
|
Normalize(b, 0.55f);
|
||||||
|
FadeOut(b, 0.05f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ treni
|
||||||
|
|
||||||
|
/// <summary>Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio.</summary>
|
||||||
|
public static float[] SteamWhistle()
|
||||||
|
{
|
||||||
|
var b = Buffer(1.35f);
|
||||||
|
var noise = Noise(b.Length, 31);
|
||||||
|
var bp = Biquad.BandPass(1500, 1.2f, Rate);
|
||||||
|
float[] freqs = [520, 650, 780];
|
||||||
|
float[] phase = new float[freqs.Length];
|
||||||
|
for (int i = 0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
float amp = t < 0.06f ? t / 0.06f : t < 1.05f ? 1 : MathF.Max(0, 1 - (t - 1.05f) / 0.3f);
|
||||||
|
float bend = 0.94f + 0.06f * MathF.Min(1, t / 0.08f) - (t > 1.0f ? 0.03f * (t - 1.0f) : 0);
|
||||||
|
float vib = 1 + 0.004f * MathF.Sin(Tau * 5.5f * t);
|
||||||
|
float v = 0;
|
||||||
|
for (int k = 0; k < freqs.Length; k++)
|
||||||
|
{
|
||||||
|
phase[k] += Tau * freqs[k] * bend * vib / Rate;
|
||||||
|
v += MathF.Sin(phase[k]) / (k + 1.5f);
|
||||||
|
}
|
||||||
|
b[i] = (v + bp.Process(noise[i]) * 0.25f) * amp;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.6f);
|
||||||
|
FadeOut(b);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Tromba bitonale delle locomotive diesel ed elettriche.</summary>
|
||||||
|
public static float[] Horn()
|
||||||
|
{
|
||||||
|
var b = Buffer(0.95f);
|
||||||
|
float[] freqs = [311.1f, 370f];
|
||||||
|
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||||
|
for (int i = 0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
float amp = t < 0.03f ? t / 0.03f : t < 0.78f ? 1 : MathF.Max(0, 1 - (t - 0.78f) / 0.15f);
|
||||||
|
float v = 0;
|
||||||
|
foreach (float f in freqs)
|
||||||
|
{
|
||||||
|
for (int h = 1; h <= 6; h++) v += MathF.Sin(Tau * f * h * t) / h;
|
||||||
|
}
|
||||||
|
b[i] = lp.Process(v) * amp;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.55f);
|
||||||
|
FadeOut(b);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sbuffo del vapore: rumore filtrato a banda con un tonfo grave.</summary>
|
||||||
|
public static float[] Chuff()
|
||||||
|
{
|
||||||
|
var b = Buffer(0.17f);
|
||||||
|
var noise = Noise(b.Length, 41);
|
||||||
|
var bp = Biquad.BandPass(900, 0.8f, Rate);
|
||||||
|
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||||
|
for (int i = 0; i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
b[i] = lp.Process(bp.Process(noise[i])) * Env(t, 0.004f, 0.05f) + MathF.Sin(Tau * 70 * t) * Env(t, 0.002f, 0.04f) * 0.5f;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.6f);
|
||||||
|
FadeOut(b, 0.02f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti.</summary>
|
||||||
|
public static float[] RailRumbleLoop()
|
||||||
|
{
|
||||||
|
int n = (int)(1.6f * Rate);
|
||||||
|
var loop = LoopFilter(BrownLoop(n, 53, 0.995f), Biquad.LowPass(300, 0.7f, Rate));
|
||||||
|
Normalize(loop, 0.5f);
|
||||||
|
var clack = Buffer(0.08f);
|
||||||
|
var cn = Noise(clack.Length, 59);
|
||||||
|
var bp = Biquad.BandPass(1800, 2, Rate);
|
||||||
|
for (int i = 0; i < clack.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
clack[i] = bp.Process(cn[i]) * 1.5f * Env(t, 0.001f, 0.012f) + MathF.Sin(Tau * 90 * t) * Env(t, 0.002f, 0.03f) * 0.6f;
|
||||||
|
}
|
||||||
|
MixWrapped(loop, clack, (int)(0.20f * Rate), 0.8f);
|
||||||
|
MixWrapped(loop, clack, (int)(0.32f * Rate), 0.7f);
|
||||||
|
MixWrapped(loop, clack, (int)(1.00f * Rate), 0.75f);
|
||||||
|
MixWrapped(loop, clack, (int)(1.12f * Rate), 0.65f);
|
||||||
|
Normalize(loop, 0.6f);
|
||||||
|
return loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz.</summary>
|
||||||
|
public static float[] DieselDroneLoop()
|
||||||
|
{
|
||||||
|
int n = Rate;
|
||||||
|
var b = new float[n];
|
||||||
|
var noise = LoopFilter(Noise(n, 61), Biquad.LowPass(900, 0.7f, Rate));
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
float v = 0;
|
||||||
|
for (int h = 1; h <= 10; h++) v += MathF.Sin(Tau * 48 * h * t) / h;
|
||||||
|
float firing = 0.7f + 0.3f * MathF.Sin(Tau * 8 * t);
|
||||||
|
b[i] = v * firing * 0.5f + noise[i] * 0.4f;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.6f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori.</summary>
|
||||||
|
public static float[] ElectricHumLoop()
|
||||||
|
{
|
||||||
|
int n = Rate;
|
||||||
|
var b = new float[n];
|
||||||
|
var hiss = LoopFilter(Noise(n, 67), Biquad.LowPass(3000, 0.7f, Rate));
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
b[i] = 0.4f * MathF.Sin(Tau * 100 * t) + 0.2f * MathF.Sin(Tau * 200 * t) + 0.25f * MathF.Sin(Tau * 300 * t)
|
||||||
|
+ 0.06f * MathF.Sin(Tau * 1150 * t) * (0.6f + 0.4f * MathF.Sin(Tau * t)) + hiss[i] * 0.12f;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.5f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ ambiente
|
||||||
|
|
||||||
|
/// <summary>Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche.</summary>
|
||||||
|
public static float[] WindLoop()
|
||||||
|
{
|
||||||
|
const float seconds = 8;
|
||||||
|
int n = (int)(seconds * Rate);
|
||||||
|
var white = Noise(n, 71);
|
||||||
|
var b = new float[n];
|
||||||
|
var f = Biquad.LowPass(400, 0.9f, Rate);
|
||||||
|
for (int pass = 0; pass < 2; pass++)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
float g = 0.55f + 0.25f * MathF.Sin(Tau * t / seconds) + 0.2f * MathF.Sin(Tau * 3 * t / seconds + 1.3f);
|
||||||
|
if ((i & 127) == 0) f.Retune(Biquad.LowPass(250 + 550 * g, 0.9f, Rate));
|
||||||
|
b[i] = f.Process(white[i]) * g;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Normalize(b, 0.5f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle.</summary>
|
||||||
|
public static float[] RiverLoop()
|
||||||
|
{
|
||||||
|
const float seconds = 6;
|
||||||
|
int n = (int)(seconds * Rate);
|
||||||
|
var main = LoopFilter(Noise(n, 73), Biquad.BandPass(1200, 0.7f, Rate));
|
||||||
|
var mod = LoopFilter(Noise(n, 79), Biquad.LowPass(6, 0.7f, Rate));
|
||||||
|
Normalize(mod, 1);
|
||||||
|
var b = new float[n];
|
||||||
|
for (int i = 0; i < n; i++) b[i] = main[i] * (0.6f + 0.4f * mod[i]);
|
||||||
|
Normalize(b, 1);
|
||||||
|
var rng = new SynthRng(83);
|
||||||
|
var bubble = Buffer(0.05f);
|
||||||
|
for (int k = 0; k < 60; k++)
|
||||||
|
{
|
||||||
|
float f0 = rng.Range(400, 1000);
|
||||||
|
for (int i = 0; i < bubble.Length; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
bubble[i] = MathF.Sin(Tau * f0 * (1 + 4 * t) * t) * Env(t, 0.002f, 0.012f);
|
||||||
|
}
|
||||||
|
MixWrapped(b, bubble, rng.Next(n), rng.Range(0.1f, 0.3f));
|
||||||
|
}
|
||||||
|
Normalize(b, 0.45f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Mare in anello (10 s): due onde con risacca e schiuma.</summary>
|
||||||
|
public static float[] SeaLoop()
|
||||||
|
{
|
||||||
|
const float seconds = 10;
|
||||||
|
int n = (int)(seconds * Rate);
|
||||||
|
var low = LoopFilter(Noise(n, 89), Biquad.LowPass(700, 0.7f, Rate));
|
||||||
|
var foam = LoopFilter(Noise(n, 97), Biquad.HighPass(3000, 0.7f, Rate));
|
||||||
|
var b = new float[n];
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
float t = i / (float)Rate;
|
||||||
|
float s = 0.5f + 0.5f * MathF.Sin(Tau * 2 * t / seconds - MathF.PI / 2);
|
||||||
|
float swell = 0.35f + 0.65f * s * s;
|
||||||
|
b[i] = low[i] * swell + foam[i] * swell * swell * 0.3f;
|
||||||
|
}
|
||||||
|
Normalize(b, 0.5f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte.</summary>
|
||||||
|
public static float[] CityLoop()
|
||||||
|
{
|
||||||
|
const float seconds = 8;
|
||||||
|
int n = (int)(seconds * Rate);
|
||||||
|
var rumble = LoopFilter(BrownLoop(n, 101, 0.996f), Biquad.LowPass(200, 0.7f, Rate));
|
||||||
|
Normalize(rumble, 1);
|
||||||
|
var murmur = LoopFilter(Noise(n, 103), Biquad.BandPass(500, 1, Rate));
|
||||||
|
Normalize(murmur, 1);
|
||||||
|
var mod = LoopFilter(Noise(n, 107), Biquad.LowPass(3, 0.7f, Rate));
|
||||||
|
Normalize(mod, 1);
|
||||||
|
var b = new float[n];
|
||||||
|
for (int i = 0; i < n; i++) b[i] = rumble[i] * 0.5f + murmur[i] * (0.2f + 0.15f * mod[i]);
|
||||||
|
var rng = new SynthRng(109);
|
||||||
|
var knock = Buffer(0.06f);
|
||||||
|
for (int k = 0; k < 24; k++)
|
||||||
|
{
|
||||||
|
var kn = Noise(knock.Length, 200 + (ulong)k);
|
||||||
|
var bp = Biquad.BandPass(rng.Range(1500, 3000), 3, Rate);
|
||||||
|
float decay = rng.Range(0.01f, 0.03f);
|
||||||
|
for (int i = 0; i < knock.Length; i++) knock[i] = bp.Process(kn[i]) * 3 * Env(i / (float)Rate, 0.001f, decay);
|
||||||
|
MixWrapped(b, knock, rng.Next(n), rng.Range(0.2f, 0.5f));
|
||||||
|
}
|
||||||
|
Normalize(b, 0.45f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cinguettio (varianti per numero): due–quattro brevi glissati acuti.</summary>
|
||||||
|
public static float[] Bird(int variant)
|
||||||
|
{
|
||||||
|
var rng = new SynthRng(300 + (ulong)variant);
|
||||||
|
int chirps = 2 + rng.Next(3);
|
||||||
|
float chirp = rng.Range(0.05f, 0.08f);
|
||||||
|
float gap = rng.Range(0.03f, 0.07f);
|
||||||
|
var b = Buffer(chirps * (chirp + gap) + 0.02f);
|
||||||
|
float f0 = rng.Range(2800, 3600), f1 = f0 * rng.Range(1.15f, 1.45f);
|
||||||
|
if (rng.Next(2) == 0) (f0, f1) = (f1, f0);
|
||||||
|
for (int k = 0; k < chirps; k++)
|
||||||
|
{
|
||||||
|
int s0 = (int)(k * (chirp + gap) * Rate);
|
||||||
|
float phase = 0;
|
||||||
|
for (int i = 0; i < (int)(chirp * Rate) && s0 + i < b.Length; i++)
|
||||||
|
{
|
||||||
|
float u = i / (chirp * Rate);
|
||||||
|
phase += Tau * (f0 + (f1 - f0) * u) / Rate;
|
||||||
|
b[s0 + i] += MathF.Sin(phase) * MathF.Sin(MathF.PI * u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Normalize(b, 0.5f);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-5
@@ -1,10 +1,10 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Map;
|
using RailEnterprise.Client.Map;
|
||||||
using ViaFerrea.Core.Map;
|
using RailEnterprise.Core.Map;
|
||||||
using ViaFerrea.Protocol.Client;
|
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>
|
/// <summary>Minimappa: terreno ridotto, linee, città e rettangolo della vista; un clic centra la mappa.</summary>
|
||||||
public partial class Minimap : Control
|
public partial class Minimap : Control
|
||||||
File renamed without changes.
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
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>
|
/// <summary>Notiziario in basso (immagine 01): «Notizie» e gli ultimi eventi che scorrono.</summary>
|
||||||
public partial class Ticker : PanelContainer
|
public partial class Ticker : PanelContainer
|
||||||
File renamed without changes.
+15
-5
@@ -1,11 +1,11 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Hud;
|
namespace RailEnterprise.Client.Hud;
|
||||||
|
|
||||||
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
|
/// <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 }
|
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Climb, Finance, Demolish }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
|
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
|
||||||
@@ -37,7 +37,7 @@ public partial class Toolbar : PanelContainer
|
|||||||
{
|
{
|
||||||
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
|
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
|
||||||
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
|
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
|
||||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
|
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Climb, "Scalata"), (Tool.Finance, "Finanze"),
|
||||||
(Tool.Demolish, "Demolisci"),
|
(Tool.Demolish, "Demolisci"),
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
@@ -48,6 +48,9 @@ public partial class Toolbar : PanelContainer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Pulsante di uno strumento (per l'evidenziazione del tutorial).</summary>
|
||||||
|
public Control? ButtonFor(Tool tool) => _buttons.GetValueOrDefault(tool);
|
||||||
|
|
||||||
public void Select(Tool tool)
|
public void Select(Tool tool)
|
||||||
{
|
{
|
||||||
Current = tool;
|
Current = tool;
|
||||||
@@ -159,6 +162,13 @@ public partial class Toolbar : PanelContainer
|
|||||||
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
|
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
|
||||||
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
|
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
|
||||||
break;
|
break;
|
||||||
|
case Tool.Climb:
|
||||||
|
// gradini che salgono verso una bandierina
|
||||||
|
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, 5), c + new Vector2(-4, 5), c + new Vector2(-4, -1),
|
||||||
|
c + new Vector2(3, -1), c + new Vector2(3, -7), c + new Vector2(10, -7), c + new Vector2(10, 11), c + new Vector2(-11, 11)], col, w);
|
||||||
|
DrawLine(c + new Vector2(10, -7), c + new Vector2(10, -13), col, w);
|
||||||
|
DrawColoredPolygon([c + new Vector2(10, -13), c + new Vector2(4, -11), c + new Vector2(10, -9)], col);
|
||||||
|
break;
|
||||||
case Tool.Finance:
|
case Tool.Finance:
|
||||||
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
|
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
|
||||||
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
|
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
|
||||||
File renamed without changes.
+75
-9
@@ -1,16 +1,26 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using RailEnterprise.Client.Panels;
|
||||||
|
using RailEnterprise.Core.Common;
|
||||||
|
using RailEnterprise.Core.Economy;
|
||||||
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
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>
|
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio.</summary>
|
||||||
public partial class TopBar : PanelContainer
|
public partial class TopBar : PanelContainer
|
||||||
{
|
{
|
||||||
private GameSession? _session;
|
private GameSession? _session;
|
||||||
private readonly Label _company = UiTheme.TitleLabel("", 30);
|
private readonly Label _company = UiTheme.TitleLabel("", 30);
|
||||||
private readonly PanelContainer _tier = UiTheme.Badge("");
|
private readonly PanelContainer _tier = UiTheme.Badge("");
|
||||||
|
private readonly Label _climb = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||||
|
private long _climbRequestedMonth = long.MinValue;
|
||||||
|
private double _sinceClimbRequest = double.MaxValue;
|
||||||
|
|
||||||
|
/// <summary>Clic sul livello: apre «La tua scalata».</summary>
|
||||||
|
public event Action? ClimbRequested;
|
||||||
private readonly Label _date = UiTheme.Text("", 17, bold: true);
|
private readonly Label _date = UiTheme.Text("", 17, bold: true);
|
||||||
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
|
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
|
||||||
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
|
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
|
||||||
@@ -18,6 +28,14 @@ public partial class TopBar : PanelContainer
|
|||||||
private readonly Label _server = UiTheme.Text("", 14);
|
private readonly Label _server = UiTheme.Text("", 14);
|
||||||
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
||||||
private readonly List<Button> _speeds = [];
|
private readonly List<Button> _speeds = [];
|
||||||
|
private VBoxContainer? _tierBox;
|
||||||
|
private HBoxContainer? _speedBox;
|
||||||
|
|
||||||
|
/// <summary>Pulsanti della velocità (per l'evidenziazione del tutorial).</summary>
|
||||||
|
public Control? SpeedBox => _speedBox;
|
||||||
|
|
||||||
|
/// <summary>Livello e avanzamento (per l'evidenziazione del tutorial).</summary>
|
||||||
|
public Control? TierBox => _tierBox;
|
||||||
|
|
||||||
public override void _Ready()
|
public override void _Ready()
|
||||||
{
|
{
|
||||||
@@ -28,8 +46,20 @@ public partial class TopBar : PanelContainer
|
|||||||
AddChild(row);
|
AddChild(row);
|
||||||
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
|
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
|
||||||
row.AddChild(_company);
|
row.AddChild(_company);
|
||||||
var tierBox = new CenterContainer();
|
// livello attuale e avanzamento verso il prossimo (dal quadro della scalata): un clic apre il pannello
|
||||||
tierBox.AddChild(_tier);
|
var tierBox = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.Center, MouseFilter = MouseFilterEnum.Stop };
|
||||||
|
tierBox.AddThemeConstantOverride("separation", 2);
|
||||||
|
tierBox.MouseDefaultCursorShape = CursorShape.PointingHand;
|
||||||
|
var badgeRow = new HBoxContainer();
|
||||||
|
badgeRow.AddChild(_tier);
|
||||||
|
tierBox.AddChild(badgeRow);
|
||||||
|
tierBox.AddChild(_climb);
|
||||||
|
tierBox.GuiInput += e =>
|
||||||
|
{
|
||||||
|
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) ClimbRequested?.Invoke();
|
||||||
|
};
|
||||||
|
_tier.MouseFilter = MouseFilterEnum.Pass;
|
||||||
|
_climb.MouseFilter = MouseFilterEnum.Pass;
|
||||||
row.AddChild(tierBox);
|
row.AddChild(tierBox);
|
||||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||||
row.AddChild(_date);
|
row.AddChild(_date);
|
||||||
@@ -44,10 +74,17 @@ public partial class TopBar : PanelContainer
|
|||||||
speeds.AddChild(b);
|
speeds.AddChild(b);
|
||||||
}
|
}
|
||||||
row.AddChild(speeds);
|
row.AddChild(speeds);
|
||||||
|
_speedBox = speeds;
|
||||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||||
row.AddChild(Stat(T("Cassa"), _cash));
|
row.AddChild(Stat(T("Cassa"), _cash));
|
||||||
row.AddChild(Stat(T("Patrimonio netto"), _worth));
|
row.AddChild(Stat(T("Patrimonio netto"), _worth));
|
||||||
row.AddChild(Stat(T("Rating"), _rating));
|
row.AddChild(Stat(T("Rating"), _rating));
|
||||||
|
// tooltip «perché» (ADR 0024): cassa con i movimenti del mese, rating, avanzamento del livello
|
||||||
|
// la cassa della barra è quella dell'ultimo aggiornamento delle entità (inizio giornata o dopo un comando),
|
||||||
|
// la spiegazione è di adesso: se differiscono il tooltip lo dice
|
||||||
|
WhyTooltip.Attach(_cash, () => new ExplainTarget(ExplainSubject.Cash), shown: () => ShownCash()?.Cents);
|
||||||
|
WhyTooltip.Attach(_rating, () => new ExplainTarget(ExplainSubject.Rating));
|
||||||
|
WhyTooltip.Attach(tierBox, () => new ExplainTarget(ExplainSubject.TierProgress), T("Clic per aprire «La tua scalata»"));
|
||||||
var chip = new PanelContainer();
|
var chip = new PanelContainer();
|
||||||
chip.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 16, 12));
|
chip.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 16, 12));
|
||||||
var chipRow = new HBoxContainer();
|
var chipRow = new HBoxContainer();
|
||||||
@@ -60,6 +97,9 @@ public partial class TopBar : PanelContainer
|
|||||||
var chipCenter = new CenterContainer();
|
var chipCenter = new CenterContainer();
|
||||||
chipCenter.AddChild(chip);
|
chipCenter.AddChild(chip);
|
||||||
row.AddChild(chipCenter);
|
row.AddChild(chipCenter);
|
||||||
|
var audio = new CenterContainer();
|
||||||
|
audio.AddChild(new Audio.SpeakerButton());
|
||||||
|
row.AddChild(audio);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static VBoxContainer Stat(string caption, Label value)
|
private static VBoxContainer Stat(string caption, Label value)
|
||||||
@@ -76,6 +116,17 @@ public partial class TopBar : PanelContainer
|
|||||||
|
|
||||||
public void Bind(GameSession session) => _session = session;
|
public void Bind(GameSession session) => _session = session;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cassa mostrata: quella della compagnia nelle entità, aggiornata a inizio giornata e dopo ogni comando
|
||||||
|
/// (un prestito, un acquisto), altrimenti quella del resoconto del giorno.
|
||||||
|
/// </summary>
|
||||||
|
private Money? ShownCash()
|
||||||
|
{
|
||||||
|
var w = _session?.World;
|
||||||
|
if (w?.Summary is null) return null;
|
||||||
|
return w.Companies.GetValueOrDefault(w.Summary.CompanyId)?.Cash ?? w.LastDigest?.Cash;
|
||||||
|
}
|
||||||
|
|
||||||
public override void _Process(double delta)
|
public override void _Process(double delta)
|
||||||
{
|
{
|
||||||
var w = _session?.World;
|
var w = _session?.World;
|
||||||
@@ -83,9 +134,24 @@ public partial class TopBar : PanelContainer
|
|||||||
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||||
_company.Text = me?.Name ?? w.Summary.CompanyName;
|
_company.Text = me?.Name ?? w.Summary.CompanyName;
|
||||||
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
|
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
|
||||||
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
|
((Label)_tier.GetChild(0)).Text = $"{tier} · {Fmt.Tier(w, tier)}";
|
||||||
|
// il quadro della scalata si chiede una volta al mese di gioco (il pannello lo chiede ogni giorno), e
|
||||||
|
// di nuovo dopo 5 s se manca: uno stato completo (ripresa della sessione, nuova partita) lo azzera
|
||||||
|
_sinceClimbRequest += delta;
|
||||||
|
long month = w.Calendar is { } cal ? Fmt.Today(w) / cal.DaysPerMonth : 0;
|
||||||
|
if ((month != _climbRequestedMonth || (w.Climb is null && _sinceClimbRequest > 5)) && _session!.IsOpen)
|
||||||
|
{
|
||||||
|
_climbRequestedMonth = month;
|
||||||
|
_sinceClimbRequest = 0;
|
||||||
|
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||||
|
}
|
||||||
|
var climb = w.Climb;
|
||||||
|
bool top = tier >= w.Data.Tiers.Tiers.Count;
|
||||||
|
_climb.Text = top ? T("livello più alto")
|
||||||
|
: climb is not null && climb.Tier == tier ? $"{Fmt.Progress(climb.Progress)} {T("verso")} {Fmt.Tier(w, tier + 1)}"
|
||||||
|
: $"{T("prossimo")}: {Fmt.Tier(w, tier + 1)}";
|
||||||
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
|
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
|
||||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
_cash.Text = (ShownCash() ?? default).ToString();
|
||||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
|
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
|
||||||
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
|
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
|
||||||
byte speed = _session!.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
|
byte speed = _session!.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
|
||||||
File renamed without changes.
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
using Godot;
|
||||||
|
using RailEnterprise.Client.App;
|
||||||
|
using RailEnterprise.Client.Audio;
|
||||||
|
using RailEnterprise.Client.Net;
|
||||||
|
using RailEnterprise.Client.Screens;
|
||||||
|
using RailEnterprise.Client.Tutorial;
|
||||||
|
using RailEnterprise.Core.Data;
|
||||||
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
|
||||||
|
/// alla chiusura termina la sessione e l'eventuale server locale.
|
||||||
|
/// </summary>
|
||||||
|
public partial class Main : Node
|
||||||
|
{
|
||||||
|
private const string SettingsPath = "user://settings.cfg";
|
||||||
|
// cartelle del server locale: la partita del giocatore (la apre la schermata di connessione), la
|
||||||
|
// partita di prova del tutorial e quella del collaudo (queste due ripartono sempre da una partita nuova)
|
||||||
|
private const string LocalDataDir = "user://server";
|
||||||
|
private const string TutorialDataDir = "user://tutorial-server";
|
||||||
|
private const string AutopilotDataDir = "user://autopilot-server";
|
||||||
|
private GameData? _data;
|
||||||
|
private Node? _screen;
|
||||||
|
private GameSession? _session;
|
||||||
|
private string? _autopilot;
|
||||||
|
// tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo)
|
||||||
|
private bool _tutorialRequested, _tutorialRestart;
|
||||||
|
|
||||||
|
public override void _Ready()
|
||||||
|
{
|
||||||
|
var cfg = new ConfigFile();
|
||||||
|
cfg.Load(SettingsPath);
|
||||||
|
string locale = (string)cfg.GetValue("ui", "locale", "it");
|
||||||
|
Localization.Load(locale);
|
||||||
|
GetWindow().Theme = UiTheme.Build();
|
||||||
|
GetWindow().Title = "Rail Enterprise";
|
||||||
|
var args = OS.GetCmdlineUserArgs();
|
||||||
|
int i = Array.IndexOf(args, "--autopilot");
|
||||||
|
// audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo)
|
||||||
|
var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless");
|
||||||
|
AddChild(audio);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_data = GodotDataSource.LoadGameData();
|
||||||
|
audio.SetEras(_data.Eras.Eras);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
|
||||||
|
}
|
||||||
|
if (i >= 0 && _data is not null)
|
||||||
|
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||||
|
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
|
||||||
|
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null);
|
||||||
|
if (_autopilot is not null)
|
||||||
|
{
|
||||||
|
// collaudo: mappa piccola e seme fisso per il server locale
|
||||||
|
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
|
||||||
|
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
|
||||||
|
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
|
||||||
|
StartLocal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Swap(Node screen)
|
||||||
|
{
|
||||||
|
_screen?.QueueFree();
|
||||||
|
_screen = screen;
|
||||||
|
AddChild(screen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
|
||||||
|
/// <param name="autoStart">Avvia subito la strada scelta l'ultima volta (server locale o in rete).</param>
|
||||||
|
/// <param name="handover">Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).</param>
|
||||||
|
private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
|
||||||
|
{
|
||||||
|
if (_data is null)
|
||||||
|
{
|
||||||
|
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
|
||||||
|
var label = UiTheme.Text(status, 16, Palette.Danger);
|
||||||
|
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
|
||||||
|
Swap(label);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// chi aggiorna con una partita locale già salvata non è alla prima partita: casella spenta
|
||||||
|
if (!TutorialSettings.Played && HasLocalSaves()) TutorialSettings.Played = true;
|
||||||
|
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
|
||||||
|
screen.PlayRequested += session =>
|
||||||
|
{
|
||||||
|
SetTutorial(screen.ShowTutorial, restart: false);
|
||||||
|
ShowGame(session, screen.GameScope);
|
||||||
|
};
|
||||||
|
screen.TutorialRequested += async () =>
|
||||||
|
{
|
||||||
|
// la partita di prova ha un suo server: quello della sessione di prova della schermata si chiude
|
||||||
|
var trial = screen.TakeSession();
|
||||||
|
if (trial is not null) await trial.DisposeAsync();
|
||||||
|
SetTutorial(true, restart: true);
|
||||||
|
StartLocal(tutorial: true);
|
||||||
|
};
|
||||||
|
screen.AudioRequested += () => AudioManager.Instance?.ShowSettings();
|
||||||
|
screen.LanguageChanged += code =>
|
||||||
|
{
|
||||||
|
var cfg = new ConfigFile();
|
||||||
|
cfg.Load(SettingsPath);
|
||||||
|
cfg.SetValue("ui", "locale", code);
|
||||||
|
cfg.Save(SettingsPath);
|
||||||
|
TranslationServer.SetLocale(code);
|
||||||
|
// la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
|
||||||
|
ShowMenu(handover: screen.TakeSession());
|
||||||
|
};
|
||||||
|
Swap(screen);
|
||||||
|
if (status.Length > 0) screen.SetStatus(status, error: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetTutorial(bool requested, bool restart)
|
||||||
|
{
|
||||||
|
_tutorialRequested = requested;
|
||||||
|
_tutorialRestart = restart;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Vero se la partita locale del giocatore ha già dei salvataggi (file <c>.vfsave</c> del server).</summary>
|
||||||
|
private static bool HasLocalSaves()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves");
|
||||||
|
return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any();
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server locale da zero e subito in partita, senza la schermata di connessione: il collaudo e la partita
|
||||||
|
/// di prova del tutorial, ciascuno nella sua cartella; la partita del giocatore non si tocca.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tutorial">pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo</param>
|
||||||
|
private async void StartLocal(bool tutorial = false)
|
||||||
|
{
|
||||||
|
if (_data is null) return;
|
||||||
|
string? server = LocalServerLauncher.FindServer();
|
||||||
|
if (server is null)
|
||||||
|
{
|
||||||
|
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tutorial && _screen is ConnectScreen connect) connect.SetStatus(T("Avvio della partita di prova del tutorial…"));
|
||||||
|
var launcher = new LocalServerLauncher();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string dataDir = ProjectSettings.GlobalizePath(tutorial ? TutorialDataDir : AutopilotDataDir);
|
||||||
|
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
|
||||||
|
int port = await launcher.StartAsync(server, dataDir, TimeSpan.FromSeconds(60));
|
||||||
|
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
|
||||||
|
session.LocalServer = launcher;
|
||||||
|
ShowGame(session, tutorial ? "tutorial" : "autopilot");
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
launcher.Dispose();
|
||||||
|
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <param name="scope">origine della partita (locale, tutorial, server in rete) per la voce del tutorial</param>
|
||||||
|
private void ShowGame(GameSession session, string scope)
|
||||||
|
{
|
||||||
|
_session = session;
|
||||||
|
var game = new GameScreen(session);
|
||||||
|
game.Exit += async () =>
|
||||||
|
{
|
||||||
|
// prima si chiude la partita (e il server locale), poi la schermata di connessione ne
|
||||||
|
// avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono
|
||||||
|
var s = _session;
|
||||||
|
_session = null;
|
||||||
|
if (s is not null) await s.DisposeAsync();
|
||||||
|
ShowMenu();
|
||||||
|
};
|
||||||
|
Swap(game);
|
||||||
|
// il pilota automatico non mostra il tutorial: le sue schermate di partita restano quelle di sempre
|
||||||
|
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
|
||||||
|
else
|
||||||
|
{
|
||||||
|
game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart));
|
||||||
|
TutorialSettings.Played = true;
|
||||||
|
_tutorialRestart = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Notification(int what)
|
||||||
|
{
|
||||||
|
if (what != NotificationWMCloseRequest) return;
|
||||||
|
// anche la sessione di prova della schermata di connessione chiude il suo server locale
|
||||||
|
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
|
||||||
|
_session = null;
|
||||||
|
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
+5
-5
@@ -1,10 +1,10 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Core.Map;
|
using RailEnterprise.Core.Map;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
|
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
|
||||||
File renamed without changes.
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
|
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
|
||||||
File renamed without changes.
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
|
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
|
||||||
File renamed without changes.
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
|
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
|
||||||
File renamed without changes.
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Core.Map;
|
using RailEnterprise.Core.Map;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
|
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
|
||||||
File renamed without changes.
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using ViaFerrea.Protocol.Client;
|
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>
|
/// <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
|
public partial class ToolOverlay : Node2D
|
||||||
File renamed without changes.
+5
-5
@@ -1,10 +1,10 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
|
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
|
||||||
File renamed without changes.
+7
-7
@@ -1,12 +1,12 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Data;
|
using RailEnterprise.Core.Data;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Map;
|
namespace RailEnterprise.Client.Map;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
|
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
|
||||||
File renamed without changes.
+10
-6
@@ -1,11 +1,11 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Data;
|
using RailEnterprise.Core.Data;
|
||||||
using ViaFerrea.Protocol;
|
using RailEnterprise.Protocol;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Net;
|
namespace RailEnterprise.Client.Net;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
|
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
|
||||||
@@ -134,9 +134,13 @@ public sealed class GameSession : IAsyncDisposable
|
|||||||
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
|
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
|
||||||
public byte? RequestedSpeed { get; private set; }
|
public byte? RequestedSpeed { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Velocità chieste finora da questo client (il tutorial non conta i cambi fatti da altri giocatori).</summary>
|
||||||
|
public int SpeedRequests { get; private set; }
|
||||||
|
|
||||||
public void SetSpeed(byte speed)
|
public void SetSpeed(byte speed)
|
||||||
{
|
{
|
||||||
RequestedSpeed = speed;
|
RequestedSpeed = speed;
|
||||||
|
SpeedRequests++;
|
||||||
Send(new SetSpeed { Speed = speed });
|
Send(new SetSpeed { Speed = speed });
|
||||||
}
|
}
|
||||||
|
|
||||||
File renamed without changes.
+6
-6
@@ -1,7 +1,7 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using Godot;
|
using Godot;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Net;
|
namespace RailEnterprise.Client.Net;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
|
/// 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 int Port { get; private set; }
|
||||||
public string Token { get; } = Guid.NewGuid().ToString("N");
|
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()
|
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;
|
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
|
||||||
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
|
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);
|
string candidate = Path.Combine(exeDir, "server", name);
|
||||||
if (File.Exists(candidate)) return candidate;
|
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://");
|
string project = ProjectSettings.GlobalizePath("res://");
|
||||||
foreach (string config in new[] { "Release", "Debug" })
|
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;
|
if (File.Exists(candidate)) return candidate;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
File renamed without changes.
@@ -0,0 +1,470 @@
|
|||||||
|
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;
|
||||||
|
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||||
|
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «La tua scalata» a tutto schermo (immagine di riferimento 08): in alto il binario dei livelli con
|
||||||
|
/// il treno che avanza verso il prossimo, sotto ogni stazione il nome, quando è stato raggiunto (o
|
||||||
|
/// l'avanzamento, o il patrimonio richiesto) e gli sblocchi; a sinistra lo storico del patrimonio
|
||||||
|
/// netto con i livelli raggiunti e i requisiti del prossimo livello; a destra lo stato patrimoniale,
|
||||||
|
/// il conto economico e i prestiti. Tutti i numeri arrivano dal server (ClimbReport, ADR 0018): il
|
||||||
|
/// pannello li chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e li mostra com'è.
|
||||||
|
/// </summary>
|
||||||
|
public partial class ClimbPanel : VBoxContainer
|
||||||
|
{
|
||||||
|
private readonly GameSession _session;
|
||||||
|
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||||
|
private readonly Label _worth = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||||
|
private readonly TierTrack _track = new();
|
||||||
|
private readonly HBoxContainer _stations = PanelKit.Row(8);
|
||||||
|
private readonly Label _historyCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private readonly SeriesChart _chart = new(250);
|
||||||
|
private readonly Label _nextTitle = UiTheme.Text("", 16, bold: true);
|
||||||
|
private readonly HBoxContainer _requirements = PanelKit.Row(24);
|
||||||
|
private readonly VBoxContainer _balance = PanelKit.Column(6);
|
||||||
|
private readonly Label _incomeTitle = UiTheme.Text("", 20, bold: true);
|
||||||
|
private readonly VBoxContainer _income = PanelKit.Column(6);
|
||||||
|
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||||
|
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
private readonly Button _repay = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||||
|
private ClimbReport? _shown;
|
||||||
|
private long _requestedDay = long.MinValue;
|
||||||
|
private double _sinceRequest = double.MaxValue;
|
||||||
|
|
||||||
|
public event Action? CloseRequested;
|
||||||
|
|
||||||
|
public ClimbPanel(GameSession session)
|
||||||
|
{
|
||||||
|
_session = session;
|
||||||
|
AddThemeConstantOverride("separation", 16);
|
||||||
|
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
|
||||||
|
var header = PanelKit.Row(24);
|
||||||
|
var titles = PanelKit.Column(0);
|
||||||
|
titles.AddChild(UiTheme.TitleLabel(T("La tua scalata"), 44));
|
||||||
|
titles.AddChild(_subtitle);
|
||||||
|
header.AddChild(titles);
|
||||||
|
var worth = PanelKit.Column(0);
|
||||||
|
worth.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||||
|
worth.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
var worthCaption = UiTheme.Text(T("Patrimonio netto"), 13, Palette.TextSecondary);
|
||||||
|
worthCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
_worth.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
worth.AddChild(worthCaption);
|
||||||
|
worth.AddChild(_worth);
|
||||||
|
header.AddChild(worth);
|
||||||
|
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||||
|
close.Pressed += () => CloseRequested?.Invoke();
|
||||||
|
header.AddChild(close);
|
||||||
|
AddChild(header);
|
||||||
|
|
||||||
|
// binario dei livelli
|
||||||
|
var trackCard = Card();
|
||||||
|
var trackCol = (VBoxContainer)trackCard.GetChild(0);
|
||||||
|
trackCol.AddChild(_track);
|
||||||
|
// tooltip «perché» dell'avanzamento verso il prossimo livello (ADR 0024)
|
||||||
|
WhyTooltip.Attach(_track, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||||
|
WhyTooltip.Attach(_nextTitle, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||||
|
trackCol.AddChild(_stations);
|
||||||
|
AddChild(trackCard);
|
||||||
|
|
||||||
|
var body = PanelKit.Row(20);
|
||||||
|
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
AddChild(body);
|
||||||
|
|
||||||
|
var left = Column(body, 1.15f);
|
||||||
|
var historyHeader = PanelKit.Row(8);
|
||||||
|
var historyTitle = UiTheme.Text(T("Patrimonio netto"), 20, bold: true);
|
||||||
|
historyTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
historyHeader.AddChild(historyTitle);
|
||||||
|
_historyCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
historyHeader.AddChild(_historyCaption);
|
||||||
|
left.AddChild(historyHeader);
|
||||||
|
left.AddChild(_chart);
|
||||||
|
left.AddChild(_nextTitle);
|
||||||
|
left.AddChild(_requirements);
|
||||||
|
|
||||||
|
var right = Column(body, 0.85f);
|
||||||
|
right.AddChild(UiTheme.Text(T("Stato patrimoniale"), 20, bold: true));
|
||||||
|
right.AddChild(_balance);
|
||||||
|
right.AddChild(new Control { CustomMinimumSize = new Vector2(0, 6) });
|
||||||
|
right.AddChild(_incomeTitle);
|
||||||
|
right.AddChild(_income);
|
||||||
|
right.AddChild(new Control { SizeFlagsVertical = SizeFlags.ExpandFill });
|
||||||
|
var loanRow = PanelKit.Row(10);
|
||||||
|
loanRow.AddChild(_amount);
|
||||||
|
loanRow.AddChild(_borrow);
|
||||||
|
loanRow.AddChild(_repay);
|
||||||
|
right.AddChild(loanRow);
|
||||||
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
right.AddChild(_status);
|
||||||
|
_borrow.Text = T("Chiedi un prestito");
|
||||||
|
_borrow.Pressed += Borrow;
|
||||||
|
_repay.Pressed += Repay;
|
||||||
|
_amount.ValueChanged += _ => UpdateLoanButtons();
|
||||||
|
|
||||||
|
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PanelContainer Card()
|
||||||
|
{
|
||||||
|
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||||
|
card.AddChild(PanelKit.Column(10));
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
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, 12, 24));
|
||||||
|
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||||
|
frame.AddChild(scroll);
|
||||||
|
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||||
|
margin.AddThemeConstantOverride("margin_right", 10);
|
||||||
|
scroll.AddChild(margin);
|
||||||
|
var col = PanelKit.Column(12);
|
||||||
|
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
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.Climb is null && _sinceRequest > 5)) Request(today);
|
||||||
|
if (w.Climb is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Request(long day)
|
||||||
|
{
|
||||||
|
_requestedDay = day;
|
||||||
|
_sinceRequest = 0;
|
||||||
|
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||||||
|
|
||||||
|
private static int YearOf(ClientWorld w, long day) =>
|
||||||
|
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).Year : 0;
|
||||||
|
|
||||||
|
private static string TierName(TierInfo t) =>
|
||||||
|
TranslationServer.GetLocale().StartsWith("en") ? t.NameEn : t.NameIt;
|
||||||
|
|
||||||
|
private static string Short(Money m) => m.ToString("short");
|
||||||
|
|
||||||
|
/// <summary>Sblocco nella lingua dell'interfaccia (i valori arrivano dal server).</summary>
|
||||||
|
public static string UnlockText(UnlockInfo u) => u.Kind switch
|
||||||
|
{
|
||||||
|
UnlockInfo.LoanLimit => $"{T("Fido fino a")} {Short(new Money(u.Value))}",
|
||||||
|
UnlockInfo.Crews => $"{u.Value} {T("squadre di cantiere")}",
|
||||||
|
UnlockInfo.Trading => T("Compravendita in proprio"),
|
||||||
|
UnlockInfo.BuyIndustry => T("Acquisto di industrie"),
|
||||||
|
UnlockInfo.Ipo => T("Quotazione in borsa"),
|
||||||
|
UnlockInfo.HostileTakeover => T("Scalate ai concorrenti"),
|
||||||
|
UnlockInfo.Concessions => T("Concessioni"),
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ aggiornamento
|
||||||
|
|
||||||
|
private void Refresh(ClientWorld w, ClimbReport report)
|
||||||
|
{
|
||||||
|
_shown = report;
|
||||||
|
string company = Fmt.Company(w, report.Company);
|
||||||
|
_subtitle.Text = $"{company}, {T("fondata nel")} {YearOf(w, report.FoundedDay)} {T("con")} {report.InitialCapital}";
|
||||||
|
_worth.Text = report.BalanceNetWorth.ToString();
|
||||||
|
RefreshTrack(w, report);
|
||||||
|
RefreshHistory(w, report);
|
||||||
|
RefreshRequirements(report);
|
||||||
|
RefreshBalance(report);
|
||||||
|
RefreshIncome(report);
|
||||||
|
UpdateLoanButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshTrack(ClientWorld w, ClimbReport report)
|
||||||
|
{
|
||||||
|
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||||
|
_track.Set(report.Tiers.Count, report.Tier, report.NextTier > 0 ? report.Progress : 1,
|
||||||
|
next is null ? "" : $"{Fmt.Progress(report.Progress)} {T("verso")} {TierName(next)}");
|
||||||
|
foreach (var c in _stations.GetChildren()) c.QueueFree();
|
||||||
|
foreach (var t in report.Tiers)
|
||||||
|
{
|
||||||
|
bool current = t.Level == report.Tier, isNext = t.Level == report.NextTier;
|
||||||
|
var col = PanelKit.Column(2);
|
||||||
|
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
var name = UiTheme.TitleLabel(TierName(t), 30, current ? Palette.AmberLight : t.Reached || isNext ? Palette.Text : Palette.TextSecondary);
|
||||||
|
name.HorizontalAlignment = HorizontalAlignment.Center;
|
||||||
|
col.AddChild(name);
|
||||||
|
string status = t.Level == 1 ? $"{T("dal")} {YearOf(w, t.ReachedDay)}"
|
||||||
|
: t.Reached ? (t.ReachedDay >= 0 ? $"{T("raggiunta nel")} {YearOf(w, t.ReachedDay)}" : T("raggiunta"))
|
||||||
|
: isNext ? $"{T("avanzamento")} {Fmt.Progress(report.Progress)}"
|
||||||
|
: $"{T("patrimonio")} {Short(t.NetWorthRequired)}";
|
||||||
|
var statusLabel = UiTheme.Text(status, 14, current ? Palette.AmberLight : Palette.Text, bold: true);
|
||||||
|
statusLabel.HorizontalAlignment = HorizontalAlignment.Center;
|
||||||
|
col.AddChild(statusLabel);
|
||||||
|
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 8) });
|
||||||
|
foreach (var u in t.Unlocks)
|
||||||
|
{
|
||||||
|
var l = UiTheme.Text(UnlockText(u), 13, Palette.TextSecondary);
|
||||||
|
l.HorizontalAlignment = HorizontalAlignment.Center;
|
||||||
|
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
col.AddChild(l);
|
||||||
|
}
|
||||||
|
_stations.AddChild(col);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshHistory(ClientWorld w, ClimbReport report)
|
||||||
|
{
|
||||||
|
var values = report.History.Select(p => (double)p.Value.Cents).ToList();
|
||||||
|
var labels = report.History.Select(p => YearOf(w, p.Day).ToString()).ToList();
|
||||||
|
_chart.Show(values, labels, v => new Money((long)v).ToString("short"), SeriesChart.Style.Line, Palette.Amber, T("Lo storico cresce anno dopo anno"));
|
||||||
|
// i livelli raggiunti si segnano sul punto dell'anno della promozione (un punto per anno di
|
||||||
|
// calendario, l'ultimo è oggi); in mancanza sul primo punto dopo la promozione
|
||||||
|
var markers = new List<(int Index, string Label)>();
|
||||||
|
foreach (var t in report.Tiers.Where(t => t.Level > 1 && t.Reached && t.ReachedDay >= 0))
|
||||||
|
{
|
||||||
|
int year = YearOf(w, t.ReachedDay);
|
||||||
|
int index = report.History.FindIndex(p => YearOf(w, p.Day) == year);
|
||||||
|
if (index < 0) index = report.History.FindIndex(p => p.Day >= t.ReachedDay);
|
||||||
|
if (index >= 0) markers.Add((index, TierName(t)));
|
||||||
|
}
|
||||||
|
_chart.SetMarkers(markers);
|
||||||
|
if (report.History.Count >= 2)
|
||||||
|
{
|
||||||
|
var first = report.History[0];
|
||||||
|
var last = report.History[^1];
|
||||||
|
int years = Math.Max(0, YearOf(w, last.Day) - YearOf(w, first.Day));
|
||||||
|
_historyCaption.Text = $"{T("da")} {first.Value} {T("a")} {Short(last.Value)} {T("in")} {years} {(years == 1 ? T("anno") : T("anni"))}";
|
||||||
|
}
|
||||||
|
else _historyCaption.Text = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshRequirements(ClimbReport report)
|
||||||
|
{
|
||||||
|
foreach (var c in _requirements.GetChildren()) c.QueueFree();
|
||||||
|
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||||
|
if (next is null)
|
||||||
|
{
|
||||||
|
_nextTitle.Text = T("Hai raggiunto il livello più alto");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_nextTitle.Text = $"{T("Per diventare")} {TierName(next)}";
|
||||||
|
_requirements.AddChild(Requirement($"{T("Patrimonio netto di")} {Short(report.NetWorthRequired)}", report.NetWorthFraction, report.NetWorthMet,
|
||||||
|
$"{Short(report.NetWorth)}, {Fmt.Progress(report.NetWorthFraction)}"));
|
||||||
|
_requirements.AddChild(Requirement($"{report.TownsRequired} {T("città oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}",
|
||||||
|
report.TownsFraction, report.TownsMet, $"{report.Towns} {(report.Towns == 1 ? T("collegata su") : T("collegate su"))} {report.TownsRequired}"));
|
||||||
|
_requirements.AddChild(Requirement($"{T("Rating creditizio")} {report.RatingRequired}", report.RatingFraction, report.RatingMet,
|
||||||
|
$"{T("attuale")} {report.Rating}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Control Requirement(string caption, float fraction, bool met, string value)
|
||||||
|
{
|
||||||
|
var col = PanelKit.Column(6);
|
||||||
|
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
col.AddChild(UiTheme.Text(caption, 14));
|
||||||
|
var color = met ? Palette.Ok : Palette.Amber;
|
||||||
|
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));
|
||||||
|
col.AddChild(bar);
|
||||||
|
col.AddChild(UiTheme.Text((met ? "✓ " : "") + value, 13, met ? Palette.Ok : Palette.TextSecondary));
|
||||||
|
WhyTooltip.Attach(col, () => new ExplainTarget(ExplainSubject.TierProgress));
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AssetName(byte kind) => kind switch
|
||||||
|
{
|
||||||
|
ClimbReport.AssetTrack => T("Binari e opere"),
|
||||||
|
ClimbReport.AssetStations => T("Stazioni e depositi"),
|
||||||
|
ClimbReport.AssetVehicles => T("Materiale rotabile"),
|
||||||
|
ClimbReport.AssetIndustries => T("Industrie possedute"),
|
||||||
|
ClimbReport.AssetGoods => T("Merce propria"),
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
|
||||||
|
private void RefreshBalance(ClimbReport report)
|
||||||
|
{
|
||||||
|
foreach (var c in _balance.GetChildren()) c.QueueFree();
|
||||||
|
foreach (var a in report.Assets)
|
||||||
|
{
|
||||||
|
// le voci di base si vedono sempre, industrie e merce solo se ci sono
|
||||||
|
bool always = a.Kind is ClimbReport.AssetTrack or ClimbReport.AssetStations or ClimbReport.AssetVehicles;
|
||||||
|
if (always || a.Value.Cents != 0) _balance.AddChild(Line(AssetName(a.Kind), a.Value.ToString()));
|
||||||
|
}
|
||||||
|
if (report.Portfolio.Cents != 0) _balance.AddChild(Line(T("Partecipazioni"), report.Portfolio.ToString()));
|
||||||
|
_balance.AddChild(Line(T("Cassa"), report.Cash.ToString()));
|
||||||
|
_balance.AddChild(PanelKit.Separator());
|
||||||
|
_balance.AddChild(Line(T("Totale attivo"), report.TotalAssets.ToString(), bold: true));
|
||||||
|
string loans = report.Loans.Cents > 0 ? $"{T("Prestiti al")} {Fmt.Pct(report.LoansRate, 1)}" : T("Prestiti");
|
||||||
|
_balance.AddChild(Line(loans, report.Loans.ToString()));
|
||||||
|
if (report.Overdraft.Cents > 0) _balance.AddChild(Line(T("Scoperto di cassa"), report.Overdraft.ToString(), color: Palette.Danger));
|
||||||
|
_balance.AddChild(Line(T("Patrimonio netto"), report.BalanceNetWorth.ToString(), bold: true, color: Palette.AmberLight));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshIncome(ClimbReport report)
|
||||||
|
{
|
||||||
|
_incomeTitle.Text = $"{T("Conto economico")} {report.IncomeYear}{(report.IncomePartial ? " " + T("(finora)") : "")}";
|
||||||
|
foreach (var c in _income.GetChildren()) c.QueueFree();
|
||||||
|
foreach (var i in report.Income)
|
||||||
|
{
|
||||||
|
string name = i.Kind switch
|
||||||
|
{
|
||||||
|
ClimbReport.IncomeFares => T("Ricavi da tariffe e noli"),
|
||||||
|
ClimbReport.IncomeOther => T("Altri ricavi"),
|
||||||
|
ClimbReport.IncomeOperating => T("Costi operativi"),
|
||||||
|
ClimbReport.IncomeMaintenance => T("Manutenzione"),
|
||||||
|
ClimbReport.IncomeInterest => T("Interessi"),
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
if (i.Kind == ClimbReport.IncomeOther && i.Value.Cents == 0) continue;
|
||||||
|
// i costi si mostrano in valore assoluto: l'etichetta dice già che sono costi
|
||||||
|
bool cost = i.Kind is ClimbReport.IncomeOperating or ClimbReport.IncomeMaintenance or ClimbReport.IncomeInterest;
|
||||||
|
var value = cost ? new Money(Math.Abs(i.Value.Cents)) : i.Value;
|
||||||
|
_income.AddChild(Line(name, value.ToString()));
|
||||||
|
}
|
||||||
|
_income.AddChild(PanelKit.Separator());
|
||||||
|
_income.AddChild(Line(T("Utile netto"), report.Profit.ToString(), bold: true, color: report.Profit.IsNegative ? Palette.Danger : Palette.AmberLight));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Control Line(string caption, string value, bool bold = false, Color? color = null)
|
||||||
|
{
|
||||||
|
var row = PanelKit.Row(8);
|
||||||
|
var c = UiTheme.Text(caption, 14, bold ? Palette.Text : Palette.TextSecondary, bold);
|
||||||
|
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
var v = UiTheme.Text(value, 14, color ?? Palette.Text, bold);
|
||||||
|
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
row.AddChild(c);
|
||||||
|
row.AddChild(v);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||||
|
|
||||||
|
/// <summary>Prestito da rimborsare per primo: quello con il tasso più alto (scelta dell'interfaccia).</summary>
|
||||||
|
private LoanInfo? LoanToRepay() => _shown?.LoanList.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Loan).FirstOrDefault();
|
||||||
|
|
||||||
|
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||||
|
|
||||||
|
private void UpdateLoanButtons()
|
||||||
|
{
|
||||||
|
var report = _shown;
|
||||||
|
var loan = LoanToRepay();
|
||||||
|
var repay = loan is null ? Amount : Money.Min(Amount, loan.Remaining);
|
||||||
|
_repay.Text = $"{T("Rimborsa")} {repay}";
|
||||||
|
_repay.Disabled = loan is null;
|
||||||
|
_borrow.Disabled = report is null || !report.LoansAllowed;
|
||||||
|
bool bankrupt = report is not null && _session.World.Companies.TryGetValue(report.Company, out var me) && me.Bankrupt;
|
||||||
|
_borrow.TooltipText = report is null ? "" : report.LoansAllowed
|
||||||
|
? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}"
|
||||||
|
: bankrupt ? T("In bancarotta non si possono chiedere prestiti") : T("In amministrazione controllata non si possono chiedere prestiti");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Borrow() =>
|
||||||
|
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||||
|
{
|
||||||
|
_status.Text = r.Message;
|
||||||
|
Request(Fmt.Today(_session.World));
|
||||||
|
});
|
||||||
|
|
||||||
|
private void Repay()
|
||||||
|
{
|
||||||
|
var loan = LoanToRepay();
|
||||||
|
if (loan is null) return;
|
||||||
|
_session.Command(new RepayLoanCommand(new LoanId(loan.Loan), Money.Min(Amount, loan.Remaining)), r =>
|
||||||
|
{
|
||||||
|
_status.Text = r.Message;
|
||||||
|
Request(Fmt.Today(_session.World));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Binario dei livelli (immagine 08): rotaie e traversine da una stazione all'altra, ambra fino al
|
||||||
|
/// treno, cerchi pieni per i livelli raggiunti, anello per quello attuale, il treno e la sua etichetta.
|
||||||
|
/// </summary>
|
||||||
|
private sealed partial class TierTrack : Control
|
||||||
|
{
|
||||||
|
private int _count = 5, _tier = 1;
|
||||||
|
private float _progress;
|
||||||
|
private string _label = "";
|
||||||
|
|
||||||
|
public TierTrack()
|
||||||
|
{
|
||||||
|
CustomMinimumSize = new Vector2(0, 112);
|
||||||
|
MouseFilter = MouseFilterEnum.Ignore;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Set(int count, int tier, float progress, string label)
|
||||||
|
{
|
||||||
|
_count = Math.Max(1, count);
|
||||||
|
_tier = Math.Clamp(tier, 1, _count);
|
||||||
|
_progress = Math.Clamp(progress, 0, 1);
|
||||||
|
_label = label;
|
||||||
|
QueueRedraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
private float X(int level) => (level - 0.5f) * Size.X / _count;
|
||||||
|
|
||||||
|
public override void _Draw()
|
||||||
|
{
|
||||||
|
const float y = 78;
|
||||||
|
float x0 = X(1), x1 = X(_count);
|
||||||
|
float trainX = _tier >= _count ? x1 : X(_tier) + (X(_tier + 1) - X(_tier)) * _progress;
|
||||||
|
var dim = Palette.Rails.Lerp(Palette.Border, 0.4f);
|
||||||
|
// traversine, poi le due rotaie
|
||||||
|
for (float x = x0; x <= x1; x += 12)
|
||||||
|
DrawLine(new Vector2(x, y - 9), new Vector2(x, y + 9), x <= trainX ? Palette.WithAlpha(Palette.Amber, 0.45f) : Palette.Border, 3);
|
||||||
|
foreach (float dy in new[] { -5f, 5f })
|
||||||
|
{
|
||||||
|
DrawLine(new Vector2(x0, y + dy), new Vector2(trainX, y + dy), Palette.Amber, 3);
|
||||||
|
if (trainX < x1) DrawLine(new Vector2(trainX, y + dy), new Vector2(x1, y + dy), dim, 3);
|
||||||
|
}
|
||||||
|
for (int level = 1; level <= _count; level++)
|
||||||
|
{
|
||||||
|
var c = new Vector2(X(level), y);
|
||||||
|
bool reached = level <= _tier;
|
||||||
|
if (level == _tier)
|
||||||
|
{
|
||||||
|
DrawCircle(c, 32, Palette.Panel);
|
||||||
|
DrawArc(c, 31, 0, MathF.Tau, 48, Palette.Amber, 2.5f, true);
|
||||||
|
}
|
||||||
|
DrawCircle(c, 21, reached ? Palette.Amber : Palette.Panel);
|
||||||
|
DrawArc(c, 21, 0, MathF.Tau, 40, reached ? Palette.AppBackground : Palette.Border.Lerp(Palette.TextSecondary, 0.35f), 3, true);
|
||||||
|
}
|
||||||
|
if (_label.Length > 0 && _tier < _count) DrawTrain(new Vector2(trainX, y - 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Locomotiva stilizzata con l'etichetta dell'avanzamento sopra.</summary>
|
||||||
|
private void DrawTrain(Vector2 at)
|
||||||
|
{
|
||||||
|
var body = Palette.AmberLight;
|
||||||
|
DrawRect(new Rect2(at.X - 30, at.Y - 22, 46, 20), body);
|
||||||
|
DrawRect(new Rect2(at.X + 10, at.Y - 34, 20, 32), body);
|
||||||
|
DrawRect(new Rect2(at.X - 24, at.Y - 32, 8, 10), body);
|
||||||
|
foreach (float dx in new[] { -18f, -2f, 14f })
|
||||||
|
{
|
||||||
|
DrawCircle(new Vector2(at.X + dx, at.Y + 4), 6, Palette.AppBackground);
|
||||||
|
DrawArc(new Vector2(at.X + dx, at.Y + 4), 6, 0, MathF.Tau, 16, body, 2.5f, true);
|
||||||
|
}
|
||||||
|
var font = UiTheme.BodyBold;
|
||||||
|
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 15);
|
||||||
|
float x = Math.Clamp(at.X - dims.X / 2, 4, Size.X - dims.X - 4);
|
||||||
|
DrawString(font, new Vector2(x, at.Y - 44), _label, HorizontalAlignment.Left, -1, 15, Palette.AmberLight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-9
@@ -1,14 +1,14 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Core.Economy;
|
using RailEnterprise.Core.Economy;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Panels;
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
|
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
|
||||||
File renamed without changes.
+8
-8
@@ -1,13 +1,13 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Protocol.Messages;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Panels;
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Registro degli impieghi (sezione 9): convenzioni proposte dalle industrie (accetta o rifiuta),
|
/// Registro degli impieghi (sezione 9): convenzioni proposte dalle industrie (accetta o rifiuta),
|
||||||
File renamed without changes.
@@ -0,0 +1,491 @@
|
|||||||
|
using Godot;
|
||||||
|
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;
|
||||||
|
using RailEnterprise.Client.App;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Finanze» a tutto schermo (palette 05, stile del pannello 08): a sinistra il conto economico per
|
||||||
|
/// voce con le colonne del mese in corso, dei mesi chiusi e dell'anno (o degli anni chiusi); a destra
|
||||||
|
/// il rating con la sua spiegazione, i prestiti con rimborso e richiesta, e, se la cassa è negativa, la
|
||||||
|
/// barra dei giorni che restano prima della bancarotta. Tutti i numeri arrivano dal server
|
||||||
|
/// (FinanceReport, ADR 0019): il pannello li chiede all'apertura, a ogni nuovo giorno e dopo un
|
||||||
|
/// comando, e li mostra com'è, senza calcolare utili, rating o rate.
|
||||||
|
/// </summary>
|
||||||
|
public partial class FinancePanel : VBoxContainer
|
||||||
|
{
|
||||||
|
/// <summary>Mesi chiusi e anni chiusi mostrati accanto alla colonna in corso.</summary>
|
||||||
|
private const int ClosedColumns = 5;
|
||||||
|
|
||||||
|
private readonly GameSession _session;
|
||||||
|
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||||
|
private readonly Label _cash = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||||
|
private readonly PanelContainer _danger = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Visible = false };
|
||||||
|
private readonly Label _dangerText = UiTheme.Text("", 15, Palette.Danger, bold: true);
|
||||||
|
private readonly ProgressBar _dangerBar = new() { MinValue = 0, MaxValue = 1, Step = 0.001, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||||
|
private readonly Label _dangerDetail = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private readonly Button _months = new() { Text = "", ToggleMode = true, ButtonPressed = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||||
|
private readonly Button _years = new() { Text = "", ToggleMode = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||||
|
private readonly GridContainer _table = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
private readonly Label _tableNote = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||||
|
private readonly Label _rating = UiTheme.TitleLabel("", 56, Palette.AmberLight);
|
||||||
|
private readonly Label _ratingCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private readonly VBoxContainer _ratingBody = PanelKit.Column(6);
|
||||||
|
private readonly VBoxContainer _loans = PanelKit.Column(8);
|
||||||
|
private readonly Label _credit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||||
|
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 44), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||||
|
private FinanceReport? _shown;
|
||||||
|
private long _requestedDay = long.MinValue;
|
||||||
|
private double _sinceRequest = double.MaxValue;
|
||||||
|
|
||||||
|
public event Action? CloseRequested;
|
||||||
|
|
||||||
|
public FinancePanel(GameSession session)
|
||||||
|
{
|
||||||
|
_session = session;
|
||||||
|
AddThemeConstantOverride("separation", 16);
|
||||||
|
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
|
||||||
|
var header = PanelKit.Row(24);
|
||||||
|
var titles = PanelKit.Column(0);
|
||||||
|
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
titles.AddChild(UiTheme.TitleLabel(T("Finanze"), 44));
|
||||||
|
titles.AddChild(_subtitle);
|
||||||
|
header.AddChild(titles);
|
||||||
|
var cash = PanelKit.Column(0);
|
||||||
|
cash.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
var cashCaption = UiTheme.Text(T("Cassa"), 13, Palette.TextSecondary);
|
||||||
|
cashCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
_cash.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
cash.AddChild(cashCaption);
|
||||||
|
cash.AddChild(_cash);
|
||||||
|
WhyTooltip.Attach(_cash, () => new ExplainTarget(ExplainSubject.Cash), shown: () => _session.World.Finance?.Cash.Cents);
|
||||||
|
header.AddChild(cash);
|
||||||
|
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||||
|
close.Pressed += () => CloseRequested?.Invoke();
|
||||||
|
header.AddChild(close);
|
||||||
|
AddChild(header);
|
||||||
|
|
||||||
|
// barra della cassa negativa: giorni passati sul limite della difficoltà
|
||||||
|
_danger.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Danger, 12, 18));
|
||||||
|
var dangerCol = PanelKit.Column(8);
|
||||||
|
dangerCol.AddChild(_dangerText);
|
||||||
|
_dangerBar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 5, 0));
|
||||||
|
_dangerBar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Danger, Palette.Danger, 5, 0));
|
||||||
|
dangerCol.AddChild(_dangerBar);
|
||||||
|
_dangerDetail.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
dangerCol.AddChild(_dangerDetail);
|
||||||
|
_danger.AddChild(dangerCol);
|
||||||
|
AddChild(_danger);
|
||||||
|
|
||||||
|
var body = PanelKit.Row(20);
|
||||||
|
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
AddChild(body);
|
||||||
|
|
||||||
|
// conto economico
|
||||||
|
var left = Column(body, 1.35f);
|
||||||
|
var incomeHeader = PanelKit.Row(8);
|
||||||
|
var incomeTitle = UiTheme.Text(T("Conto economico"), 20, bold: true);
|
||||||
|
incomeTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
incomeHeader.AddChild(incomeTitle);
|
||||||
|
var group = new ButtonGroup();
|
||||||
|
_months.ButtonGroup = group;
|
||||||
|
_years.ButtonGroup = group;
|
||||||
|
_months.Text = T("Mesi");
|
||||||
|
_years.Text = T("Anni");
|
||||||
|
_months.Pressed += () => RefreshTable(_shown);
|
||||||
|
_years.Pressed += () => RefreshTable(_shown);
|
||||||
|
incomeHeader.AddChild(_months);
|
||||||
|
incomeHeader.AddChild(_years);
|
||||||
|
left.AddChild(incomeHeader);
|
||||||
|
_table.AddThemeConstantOverride("h_separation", 18);
|
||||||
|
_table.AddThemeConstantOverride("v_separation", 6);
|
||||||
|
left.AddChild(_table);
|
||||||
|
_tableNote.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
left.AddChild(_tableNote);
|
||||||
|
|
||||||
|
// rating e prestiti
|
||||||
|
var right = Column(body, 0.9f);
|
||||||
|
right.AddChild(UiTheme.Text(T("Rating creditizio"), 20, bold: true));
|
||||||
|
var ratingRow = PanelKit.Row(16);
|
||||||
|
ratingRow.AddChild(_rating);
|
||||||
|
WhyTooltip.Attach(_rating, () => new ExplainTarget(ExplainSubject.Rating));
|
||||||
|
_ratingCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
_ratingCaption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
_ratingCaption.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
ratingRow.AddChild(_ratingCaption);
|
||||||
|
right.AddChild(ratingRow);
|
||||||
|
right.AddChild(_ratingBody);
|
||||||
|
right.AddChild(PanelKit.Separator());
|
||||||
|
right.AddChild(UiTheme.Text(T("Prestiti"), 20, bold: true));
|
||||||
|
right.AddChild(_loans);
|
||||||
|
_credit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
right.AddChild(_credit);
|
||||||
|
var loanRow = PanelKit.Row(10);
|
||||||
|
loanRow.AddChild(_amount);
|
||||||
|
loanRow.AddChild(_borrow);
|
||||||
|
right.AddChild(loanRow);
|
||||||
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
right.AddChild(_status);
|
||||||
|
_borrow.Text = T("Chiedi un prestito");
|
||||||
|
_borrow.Pressed += Borrow;
|
||||||
|
_amount.ValueChanged += _ => RefreshLoans(_shown);
|
||||||
|
|
||||||
|
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||||
|
}
|
||||||
|
|
||||||
|
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, 12, 24));
|
||||||
|
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Auto, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||||
|
frame.AddChild(scroll);
|
||||||
|
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||||
|
margin.AddThemeConstantOverride("margin_right", 10);
|
||||||
|
scroll.AddChild(margin);
|
||||||
|
var col = PanelKit.Column(12);
|
||||||
|
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
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.Finance is null && _sinceRequest > 5)) Request(today);
|
||||||
|
if (w.Finance is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Request(long day)
|
||||||
|
{
|
||||||
|
_requestedDay = day;
|
||||||
|
_sinceRequest = 0;
|
||||||
|
_session.Send(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ aggiornamento
|
||||||
|
|
||||||
|
private void Refresh(ClientWorld w, FinanceReport report)
|
||||||
|
{
|
||||||
|
_shown = report;
|
||||||
|
_subtitle.Text = $"{Fmt.Company(w, report.Company)} · {Fmt.Date(w, report.Day)} · {T("patrimonio netto")} {report.NetWorth}";
|
||||||
|
_cash.Text = report.Cash.ToString();
|
||||||
|
_cash.AddThemeColorOverride("font_color", report.Cash.IsNegative ? Palette.Danger : Palette.AmberLight);
|
||||||
|
RefreshDanger(report);
|
||||||
|
RefreshTable(report);
|
||||||
|
RefreshRating(report);
|
||||||
|
RefreshLoans(report);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Barra della cassa negativa. Il motore conta i giorni una volta al giorno, quindi dopo un prestito il
|
||||||
|
/// contatore può restare indietro di un giorno rispetto alla cassa: il conto alla rovescia si mostra solo
|
||||||
|
/// con la cassa davvero negativa (scoperto) o in bancarotta.
|
||||||
|
/// </summary>
|
||||||
|
private void RefreshDanger(FinanceReport r)
|
||||||
|
{
|
||||||
|
bool overdraft = r.Overdraft.Cents > 0;
|
||||||
|
bool recovering = !overdraft && !r.Bankrupt && r.NegativeCashDays > 0;
|
||||||
|
_danger.Visible = overdraft || r.Bankrupt || recovering;
|
||||||
|
_dangerBar.Visible = overdraft || r.Bankrupt;
|
||||||
|
if (!_danger.Visible) return;
|
||||||
|
_dangerBar.Value = r.BankruptcyDays > 0 ? Math.Clamp((double)r.NegativeCashDays / r.BankruptcyDays, 0, 1) : 1;
|
||||||
|
if (r.Bankrupt)
|
||||||
|
{
|
||||||
|
_dangerText.Text = T("Bancarotta dichiarata");
|
||||||
|
_dangerDetail.Text = T("La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (recovering)
|
||||||
|
{
|
||||||
|
_dangerText.Text = T("La cassa è tornata positiva");
|
||||||
|
_dangerDetail.Text = string.Format(T("Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani."), Days(r.NegativeCashDays));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int left = Math.Max(0, r.BankruptcyDays - r.NegativeCashDays);
|
||||||
|
_dangerText.Text = r.NegativeCashDays == 0
|
||||||
|
? string.Format(T("Cassa negativa da oggi: bancarotta tra {0}"), Days(r.BankruptcyDays))
|
||||||
|
: string.Format(T("Cassa negativa da {0}: bancarotta tra {1}"), Days(r.NegativeCashDays), Days(left));
|
||||||
|
_dangerDetail.Text = string.Format(T("Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi."),
|
||||||
|
r.Overdraft, Days(r.BankruptcyDays));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Days(int n) => n == 1 ? $"1 {T("giorno")}" : $"{n} {T("giorni")}";
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ conto economico
|
||||||
|
|
||||||
|
private static string[] MonthNames() =>
|
||||||
|
[T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
|
||||||
|
|
||||||
|
/// <summary>Colonne da mostrare: il mese in corso e i mesi chiusi, poi l'anno in corso; oppure l'anno in corso e gli anni chiusi.</summary>
|
||||||
|
private List<IncomeColumnInfo> ShownColumns(FinanceReport r)
|
||||||
|
{
|
||||||
|
if (_years.ButtonPressed)
|
||||||
|
{
|
||||||
|
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)
|
||||||
|
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedYear).Take(ClosedColumns)).ToList();
|
||||||
|
}
|
||||||
|
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentMonth)
|
||||||
|
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedMonth).Take(ClosedColumns))
|
||||||
|
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ColumnTitle(IncomeColumnInfo c)
|
||||||
|
{
|
||||||
|
string month = c.Month is >= 1 and <= 12 ? MonthNames()[c.Month - 1] : "";
|
||||||
|
return c.Kind switch
|
||||||
|
{
|
||||||
|
IncomeColumnInfo.CurrentMonth => $"{month} {c.Year}\n{T("in corso")}",
|
||||||
|
IncomeColumnInfo.ClosedMonth => $"{month} {c.Year}\n ",
|
||||||
|
IncomeColumnInfo.CurrentYear => $"{c.Year}\n{T("finora")}",
|
||||||
|
_ => $"{c.Year}\n ",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshTable(FinanceReport? r)
|
||||||
|
{
|
||||||
|
foreach (var c in _table.GetChildren()) c.QueueFree();
|
||||||
|
if (r is null) return;
|
||||||
|
var columns = ShownColumns(r);
|
||||||
|
_table.Columns = columns.Count + 1;
|
||||||
|
Cell(T("Voce"), Palette.TextSecondary, bold: true, left: true);
|
||||||
|
foreach (var c in columns)
|
||||||
|
Cell(ColumnTitle(c), c.Kind is IncomeColumnInfo.CurrentMonth or IncomeColumnInfo.CurrentYear ? Palette.AmberLight : Palette.TextSecondary, bold: true);
|
||||||
|
|
||||||
|
foreach (byte section in new[] { FinanceLineInfo.SectionRevenue, FinanceLineInfo.SectionCost, FinanceLineInfo.SectionCapital })
|
||||||
|
{
|
||||||
|
// le voci sempre a zero nelle colonne mostrate non occupano righe
|
||||||
|
var lines = r.Lines.Where(l => l.Section == section && columns.Any(c => c.Value(l.Kind).Cents != 0)).ToList();
|
||||||
|
if (lines.Count == 0) continue;
|
||||||
|
Cell(SectionName(section), Palette.Amber, bold: true, left: true);
|
||||||
|
foreach (var _ in columns) Cell("", Palette.Text);
|
||||||
|
foreach (var line in lines)
|
||||||
|
{
|
||||||
|
Cell(EntryName((LedgerEntry)line.Kind), Palette.Text, left: true, indent: true);
|
||||||
|
foreach (var c in columns)
|
||||||
|
{
|
||||||
|
var v = c.Value(line.Kind);
|
||||||
|
Cell(v.Cents == 0 ? "—" : v.ToString(), v.IsNegative ? Palette.Danger : v.Cents == 0 ? Palette.TextSecondary : Palette.Text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (section == FinanceLineInfo.SectionCost)
|
||||||
|
{
|
||||||
|
Cell(T("Utile operativo"), Palette.Text, bold: true, left: true);
|
||||||
|
foreach (var c in columns) Cell(c.Profit.ToString(), c.Profit.IsNegative ? Palette.Danger : Palette.AmberLight, bold: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Cell(T("Flusso di cassa"), Palette.Text, bold: true, left: true);
|
||||||
|
foreach (var c in columns) Cell(c.CashFlow.ToString(), c.CashFlow.IsNegative ? Palette.Danger : Palette.Ok, bold: true);
|
||||||
|
_tableNote.Text = columns.Count <= 1
|
||||||
|
? T("I mesi e gli anni chiusi compaiono qui man mano che passano.")
|
||||||
|
: T("L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Cell(string text, Color color, bool bold = false, bool left = false, bool indent = false)
|
||||||
|
{
|
||||||
|
var l = UiTheme.Text(indent ? " " + text : text, 14, color, bold);
|
||||||
|
l.HorizontalAlignment = left ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||||||
|
if (left) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
else l.CustomMinimumSize = new Vector2(110, 0);
|
||||||
|
_table.AddChild(l);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SectionName(byte section) => section switch
|
||||||
|
{
|
||||||
|
FinanceLineInfo.SectionRevenue => T("Ricavi"),
|
||||||
|
FinanceLineInfo.SectionCost => T("Costi"),
|
||||||
|
_ => T("Investimenti e finanziamenti"),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Nome della voce del registro nella lingua dell'interfaccia.</summary>
|
||||||
|
public static string EntryName(LedgerEntry e) => e switch
|
||||||
|
{
|
||||||
|
LedgerEntry.FreightRevenue => T("Noli merci"),
|
||||||
|
LedgerEntry.PassengerRevenue => T("Biglietti passeggeri"),
|
||||||
|
LedgerEntry.Trading => T("Commercio in proprio"),
|
||||||
|
LedgerEntry.Contracts => T("Contratti"),
|
||||||
|
LedgerEntry.Industries => T("Industrie possedute"),
|
||||||
|
LedgerEntry.Subsidiaries => T("Controllate"),
|
||||||
|
LedgerEntry.DividendsReceived => T("Dividendi incassati"),
|
||||||
|
LedgerEntry.RunningCosts => T("Esercizio dei treni"),
|
||||||
|
LedgerEntry.StationUpkeep => T("Stazioni e depositi"),
|
||||||
|
LedgerEntry.FleetMaintenance => T("Manutenzione dei treni"),
|
||||||
|
LedgerEntry.TrackMaintenance => T("Manutenzione dei binari"),
|
||||||
|
LedgerEntry.Wages => T("Stipendi"),
|
||||||
|
LedgerEntry.Interest => T("Interessi"),
|
||||||
|
LedgerEntry.Duties => T("Dazi"),
|
||||||
|
LedgerEntry.Storage => T("Magazzini"),
|
||||||
|
LedgerEntry.Penalties => T("Penali"),
|
||||||
|
LedgerEntry.Construction => T("Costruzioni"),
|
||||||
|
LedgerEntry.VehiclePurchase => T("Acquisto di treni"),
|
||||||
|
LedgerEntry.VehicleSale => T("Vendita di treni"),
|
||||||
|
LedgerEntry.IndustryPurchase => T("Acquisto di industrie"),
|
||||||
|
LedgerEntry.LoanTaken => T("Prestiti ricevuti"),
|
||||||
|
LedgerEntry.LoanRepaid => T("Prestiti rimborsati"),
|
||||||
|
LedgerEntry.Shares => T("Azioni"),
|
||||||
|
LedgerEntry.Dividends => T("Dividendi pagati"),
|
||||||
|
_ => T("Altro"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ rating
|
||||||
|
|
||||||
|
private static string Ratio(double value) => Fmt.Number(value, 2);
|
||||||
|
|
||||||
|
private void RefreshRating(FinanceReport r)
|
||||||
|
{
|
||||||
|
_rating.Text = r.Rating;
|
||||||
|
_ratingCaption.Text = r.RatingInitial
|
||||||
|
? T("Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.")
|
||||||
|
: $"{T("Calcolato a inizio mese sugli ultimi")} {r.RatingMonths} {(r.RatingMonths == 1 ? T("mese chiuso") : T("mesi chiusi"))}. "
|
||||||
|
+ $"{T("Punteggio")} {Ratio(r.Score)}.";
|
||||||
|
foreach (var c in _ratingBody.GetChildren()) c.QueueFree();
|
||||||
|
|
||||||
|
_ratingBody.AddChild(Measure(T("Margine (utile / ricavi)"), r.MarginNeutral ? T("neutro") : Fmt.Pct(r.Margin, 1), r.MarginWeight, r.MarginComponent));
|
||||||
|
if (r.MarginNeutral)
|
||||||
|
_ratingBody.AddChild(Note(string.Format(T("Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating."),
|
||||||
|
r.MinRevenueMonths, r.RevenueMonths)));
|
||||||
|
string leverage = r.LeverageUnbounded ? T("patrimonio non positivo") : Ratio(r.Leverage);
|
||||||
|
_ratingBody.AddChild(Measure(T("Leva (debiti / patrimonio netto)"), leverage, r.LeverageWeight, r.LeverageComponent));
|
||||||
|
|
||||||
|
if (r.Bankrupt)
|
||||||
|
{
|
||||||
|
_ratingBody.AddChild(Note(T("In bancarotta il rating è D finché la situazione non si risolve.")));
|
||||||
|
}
|
||||||
|
else if (r.NextRating.Length == 0)
|
||||||
|
{
|
||||||
|
_ratingBody.AddChild(Note(T("È il rating più alto: i prestiti costano il minimo.")));
|
||||||
|
}
|
||||||
|
else if (r.NextAlreadyMet)
|
||||||
|
{
|
||||||
|
_ratingBody.AddChild(Note(string.Format(T("Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese."),
|
||||||
|
Ratio(r.Score), r.ScoreRating)));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var ways = new List<string>();
|
||||||
|
if (r.MarginReachable) ways.Add(string.Format(T("un margine di almeno {0}"), Fmt.Pct(r.MarginNeeded, 1)));
|
||||||
|
if (r.LeverageReachable)
|
||||||
|
{
|
||||||
|
string way = r.DebtToRepay.Cents <= 0 ? T("una leva non oltre {0}")
|
||||||
|
: r.RepayAffordable ? T("una leva non oltre {0} (rimborsando {1})")
|
||||||
|
: T("una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)");
|
||||||
|
ways.Add(string.Format(way, Ratio(r.LeverageMax), r.DebtToRepay));
|
||||||
|
}
|
||||||
|
string how = ways.Count == 0 ? T("serve migliorare insieme margine e leva") : string.Join($" {T("oppure")} ", ways);
|
||||||
|
_ratingBody.AddChild(Note(string.Format(T("Per il gradino {0} serve un punteggio di {1}: {2}."), r.NextRating, Ratio(r.NextThreshold), how)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// soglie e tassi per rating
|
||||||
|
var grid = new GridContainer { Columns = 3 };
|
||||||
|
grid.AddThemeConstantOverride("h_separation", 24);
|
||||||
|
grid.AddChild(UiTheme.Text(T("Rating"), 12, Palette.TextSecondary, bold: true));
|
||||||
|
grid.AddChild(UiTheme.Text(T("Punteggio da"), 12, Palette.TextSecondary, bold: true));
|
||||||
|
grid.AddChild(UiTheme.Text(T("Tasso"), 12, Palette.TextSecondary, bold: true));
|
||||||
|
foreach (var t in r.Thresholds)
|
||||||
|
{
|
||||||
|
bool current = t.Rating == r.Rating;
|
||||||
|
var color = current ? Palette.AmberLight : Palette.TextSecondary;
|
||||||
|
grid.AddChild(UiTheme.Text(t.Rating, 12, color, current));
|
||||||
|
grid.AddChild(UiTheme.Text(Ratio(t.MinScore), 12, color, current));
|
||||||
|
grid.AddChild(UiTheme.Text(Fmt.Pct(t.LoanRate, 1), 12, color, current));
|
||||||
|
}
|
||||||
|
_ratingBody.AddChild(grid);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Control Measure(string caption, string value, float weight, float component)
|
||||||
|
{
|
||||||
|
var col = PanelKit.Column(4);
|
||||||
|
var row = PanelKit.Row(8);
|
||||||
|
var c = UiTheme.Text(caption, 14, Palette.Text);
|
||||||
|
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
row.AddChild(c);
|
||||||
|
row.AddChild(UiTheme.Text(value, 14, Palette.Text, bold: true));
|
||||||
|
col.AddChild(row);
|
||||||
|
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(component, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 6) };
|
||||||
|
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 3, 0));
|
||||||
|
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
|
||||||
|
col.AddChild(bar);
|
||||||
|
col.AddChild(UiTheme.Text($"{T("componente")} {Ratio(component)} × {T("peso")} {Ratio(weight)}", 12, Palette.TextSecondary));
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Label Note(string text)
|
||||||
|
{
|
||||||
|
var l = UiTheme.Text(text, 13, Palette.Text);
|
||||||
|
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||||
|
|
||||||
|
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||||
|
|
||||||
|
private void RefreshLoans(FinanceReport? r)
|
||||||
|
{
|
||||||
|
foreach (var c in _loans.GetChildren()) c.QueueFree();
|
||||||
|
if (r is null) return;
|
||||||
|
var w = _session.World;
|
||||||
|
if (r.LoanList.Count == 0) _loans.AddChild(UiTheme.Text(T("Nessun prestito in corso."), 13, Palette.TextSecondary));
|
||||||
|
foreach (var loan in r.LoanList)
|
||||||
|
{
|
||||||
|
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 12));
|
||||||
|
var col = PanelKit.Column(4);
|
||||||
|
var head = PanelKit.Row(8);
|
||||||
|
var title = UiTheme.Text($"{T("Residuo")} {loan.Remaining} {T("su")} {loan.Principal}", 14, Palette.Text, bold: true);
|
||||||
|
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
head.AddChild(title);
|
||||||
|
head.AddChild(UiTheme.Text($"{Fmt.Pct(loan.AnnualRate, 1)} {T("fisso")}", 14, Palette.AmberLight, bold: true));
|
||||||
|
col.AddChild(head);
|
||||||
|
col.AddChild(UiTheme.Text(
|
||||||
|
$"{T("Rata mensile")} {loan.Payment} ({T("interessi")} {loan.NextInterest}) · {loan.MonthsLeft} {T("mesi")} · {T("scadenza")} {Fmt.Date(w, loan.MaturityDay)}",
|
||||||
|
12, Palette.TextSecondary));
|
||||||
|
var buttons = PanelKit.Row(8);
|
||||||
|
var part = Money.Min(Amount, loan.Remaining);
|
||||||
|
var repay = new Button { Text = $"{T("Rimborsa")} {part}", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
repay.Disabled = part >= loan.Remaining;
|
||||||
|
int id = loan.Loan;
|
||||||
|
repay.Pressed += () => Repay(id, part);
|
||||||
|
var all = new Button { Text = $"{T("Estingui")} ({loan.Remaining})", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
var remaining = loan.Remaining;
|
||||||
|
all.Pressed += () => Repay(id, remaining);
|
||||||
|
buttons.AddChild(repay);
|
||||||
|
buttons.AddChild(all);
|
||||||
|
col.AddChild(buttons);
|
||||||
|
card.AddChild(col);
|
||||||
|
_loans.AddChild(card);
|
||||||
|
}
|
||||||
|
|
||||||
|
_borrow.Disabled = !r.LoansAllowed || r.LoanAvailable.Cents <= 0;
|
||||||
|
_credit.Text = r.Bankrupt ? T("In bancarotta non si possono chiedere prestiti")
|
||||||
|
: r.Receivership ? T("In amministrazione controllata non si possono chiedere prestiti")
|
||||||
|
: string.Format(T("Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni."),
|
||||||
|
r.LoanAvailable, r.MaxLoan, Fmt.Pct(r.NewLoanRate, 1), Fmt.Pct(r.BaseRate, 1), r.Rating, Fmt.Pct(r.Spread, 1), r.LoanTermMonths / 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Borrow() =>
|
||||||
|
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||||
|
{
|
||||||
|
_status.Text = r.Message;
|
||||||
|
Request(Fmt.Today(_session.World));
|
||||||
|
});
|
||||||
|
|
||||||
|
private void Repay(int loan, Money amount) =>
|
||||||
|
_session.Command(new RepayLoanCommand(new LoanId(loan), amount), r =>
|
||||||
|
{
|
||||||
|
_status.Text = r.Message;
|
||||||
|
Request(Fmt.Today(_session.World));
|
||||||
|
});
|
||||||
|
}
|
||||||
+10
-4
@@ -1,9 +1,9 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Protocol.Client;
|
using RailEnterprise.Protocol.Client;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Panels;
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
|
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
|
||||||
@@ -26,6 +26,12 @@ public static class Fmt
|
|||||||
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
|
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
|
||||||
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
|
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Avanzamento (0–1) in percentuale intera per difetto («99%»): il 100 % compare solo quando la
|
||||||
|
/// frazione è piena, cioè con il requisito o il livello davvero raggiunto (ADR 0018).
|
||||||
|
/// </summary>
|
||||||
|
public static string Progress(double fraction) => Number(Math.Floor(Math.Clamp(fraction, 0, 1) * 100 + 1e-9), 0) + "%";
|
||||||
|
|
||||||
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
|
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
|
||||||
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
|
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
|
||||||
|
|
||||||
File renamed without changes.
@@ -0,0 +1,731 @@
|
|||||||
|
using Godot;
|
||||||
|
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 RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scheda dell'industria a tutto schermo (immagine di riferimento 07, sezione 11): in alto nome,
|
||||||
|
/// livello, proprietà, stazione che la serve, valore stimato e l'anello dell'efficienza con il
|
||||||
|
/// fattore che la limita; sotto tre schede (materie prime in ingresso, forza lavoro, produzione), il
|
||||||
|
/// grafo della catena produttiva con fornitori, città dei pendolari e clienti, e la scheda «Impianti
|
||||||
|
/// e crescita» con condizione, punteggio trimestrale e soglie, comandi del proprietario e storico dei
|
||||||
|
/// fermi. Tutti i numeri arrivano dal server nella scheda (IndustryCard, blocco 1: ADR 0021); il
|
||||||
|
/// pannello li chiede una volta al secondo e li mostra com'è.
|
||||||
|
/// </summary>
|
||||||
|
public partial class IndustryPanel : VBoxContainer
|
||||||
|
{
|
||||||
|
private readonly GameSession _session;
|
||||||
|
private readonly OptionButton _chooser = new() { CustomMinimumSize = new Vector2(320, 44), FitToLongestItem = false };
|
||||||
|
private readonly List<int> _ids = [];
|
||||||
|
private readonly Label _title = UiTheme.TitleLabel("", 44);
|
||||||
|
private readonly Label _subtitle = UiTheme.Text("", 15, Palette.TextSecondary);
|
||||||
|
private readonly Label _ownerLine = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||||
|
private readonly Label _valuation = UiTheme.Text("", 26, Palette.AmberLight, bold: true);
|
||||||
|
private readonly EfficiencyRing _ring = new();
|
||||||
|
private readonly Label _limit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private readonly VBoxContainer _notices = PanelKit.Column(6);
|
||||||
|
private readonly ScrollContainer _scroll = new() { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||||
|
private readonly VBoxContainer _inputs = PanelKit.Column(8);
|
||||||
|
private readonly VBoxContainer _workforce = PanelKit.Column(8);
|
||||||
|
private readonly VBoxContainer _production = PanelKit.Column(8);
|
||||||
|
private readonly ChainGraph _graph = new();
|
||||||
|
private readonly VBoxContainer _chainFooter = PanelKit.Column(8);
|
||||||
|
private readonly VBoxContainer _plants = PanelKit.Column(8);
|
||||||
|
private readonly VBoxContainer _controls = PanelKit.Column(8);
|
||||||
|
private readonly VBoxContainer _history = PanelKit.Column(4);
|
||||||
|
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
/// <summary>Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta).</summary>
|
||||||
|
private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
|
private Button? _overhaul, _upgrade;
|
||||||
|
private readonly List<Button> _budgetButtons = [];
|
||||||
|
private SpinBox? _partsOrder;
|
||||||
|
private int _industry = -1;
|
||||||
|
private (int Industry, int Owner) _controlsKey = (-2, -2);
|
||||||
|
private int _entityVersion = -1, _detailVersion = -1;
|
||||||
|
private double _request, _sinceRefresh;
|
||||||
|
|
||||||
|
/// <summary>«Torna alla mappa».</summary>
|
||||||
|
public event Action? CloseRequested;
|
||||||
|
|
||||||
|
/// <summary>«Crea una linea verso questa industria»: strumento binari centrato sull'industria.</summary>
|
||||||
|
public event Action<int>? PlanLineRequested;
|
||||||
|
|
||||||
|
public IndustryPanel(GameSession session)
|
||||||
|
{
|
||||||
|
_session = session;
|
||||||
|
AddThemeConstantOverride("separation", 14);
|
||||||
|
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||||
|
|
||||||
|
// barra di navigazione: ritorno alla mappa e scelta dell'industria
|
||||||
|
var nav = PanelKit.Row(12);
|
||||||
|
var back = new Button { Text = "‹ " + T("Mappa"), CustomMinimumSize = new Vector2(120, 44) };
|
||||||
|
back.Pressed += () => CloseRequested?.Invoke();
|
||||||
|
nav.AddChild(back);
|
||||||
|
nav.AddChild(_chooser);
|
||||||
|
_chooser.ItemSelected += i => Select(_ids[(int)i]);
|
||||||
|
var hint = UiTheme.Text(T("Scheda dell'industria"), 13, Palette.TextSecondary);
|
||||||
|
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
nav.AddChild(hint);
|
||||||
|
AddChild(nav);
|
||||||
|
|
||||||
|
// intestazione: nome, livello, proprietà, valore ed efficienza
|
||||||
|
var header = PanelKit.Row(24);
|
||||||
|
var titles = PanelKit.Column(2);
|
||||||
|
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
_title.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||||
|
titles.AddChild(_title);
|
||||||
|
titles.AddChild(_subtitle);
|
||||||
|
_ownerLine.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
titles.AddChild(_ownerLine);
|
||||||
|
header.AddChild(titles);
|
||||||
|
var value = PanelKit.Column(0);
|
||||||
|
value.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||||
|
var valueCaption = UiTheme.Text(T("Valore stimato"), 13, Palette.TextSecondary);
|
||||||
|
valueCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
_valuation.HorizontalAlignment = HorizontalAlignment.Right;
|
||||||
|
value.AddChild(valueCaption);
|
||||||
|
value.AddChild(_valuation);
|
||||||
|
header.AddChild(value);
|
||||||
|
var ring = PanelKit.Column(2);
|
||||||
|
ring.AddChild(_ring);
|
||||||
|
// tooltip «perché» dell'efficienza con i termini dell'ultima produzione (ADR 0024)
|
||||||
|
WhyTooltip.Attach(_ring, () => _industry >= 0 ? new ExplainTarget(ExplainSubject.IndustryEfficiency, _industry) : null);
|
||||||
|
_limit.HorizontalAlignment = HorizontalAlignment.Center;
|
||||||
|
_limit.CustomMinimumSize = new Vector2(150, 0);
|
||||||
|
_limit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
ring.AddChild(_limit);
|
||||||
|
header.AddChild(ring);
|
||||||
|
AddChild(header);
|
||||||
|
AddChild(_notices);
|
||||||
|
|
||||||
|
// corpo scorrevole: tre schede, poi catena produttiva e impianti
|
||||||
|
AddChild(_scroll);
|
||||||
|
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
margin.AddThemeConstantOverride("margin_right", 10);
|
||||||
|
_scroll.AddChild(margin);
|
||||||
|
var body = PanelKit.Column(18);
|
||||||
|
margin.AddChild(body);
|
||||||
|
|
||||||
|
var cards = PanelKit.Row(18);
|
||||||
|
cards.AddChild(Card(T("Materie prime in ingresso"), _inputs, 1));
|
||||||
|
cards.AddChild(Card(T("Forza lavoro"), _workforce, 1));
|
||||||
|
cards.AddChild(Card(T("Produzione"), _production, 1));
|
||||||
|
body.AddChild(cards);
|
||||||
|
|
||||||
|
var lower = PanelKit.Row(18);
|
||||||
|
var chain = PanelKit.Column(10);
|
||||||
|
var legend = PanelKit.Row(16);
|
||||||
|
foreach (var (text, color) in new[] { (T("merci su linea"), Palette.Amber), (T("lavoratori"), Palette.Workers), (T("personale"), Palette.Staff), (T("non collegato"), Palette.TextSecondary) })
|
||||||
|
legend.AddChild(UiTheme.Text("— " + text, 12, color));
|
||||||
|
chain.AddChild(legend);
|
||||||
|
_graph.IndustryClicked += Select;
|
||||||
|
chain.AddChild(_graph);
|
||||||
|
chain.AddChild(_chainFooter);
|
||||||
|
_buyStatus.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
chain.AddChild(_buyStatus);
|
||||||
|
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
|
||||||
|
var plants = PanelKit.Column(10);
|
||||||
|
plants.AddChild(_plants);
|
||||||
|
plants.AddChild(_controls);
|
||||||
|
plants.AddChild(_history);
|
||||||
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
plants.AddChild(_status);
|
||||||
|
lower.AddChild(Card(T("Impianti e crescita"), plants, 1));
|
||||||
|
body.AddChild(lower);
|
||||||
|
|
||||||
|
RefreshList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Scheda con titolo e contenuto, larga in proporzione al rapporto dato.</summary>
|
||||||
|
private static PanelContainer Card(string title, Control content, float ratio)
|
||||||
|
{
|
||||||
|
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||||
|
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 22));
|
||||||
|
var col = PanelKit.Column(12);
|
||||||
|
col.AddChild(UiTheme.Text(title, 19, bold: true));
|
||||||
|
col.AddChild(content);
|
||||||
|
card.AddChild(col);
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Industria mostrata (−1 se nessuna).</summary>
|
||||||
|
public int Industry => _industry;
|
||||||
|
|
||||||
|
public void Select(int id)
|
||||||
|
{
|
||||||
|
if (id == _industry) return;
|
||||||
|
_industry = id;
|
||||||
|
_status.Text = "";
|
||||||
|
_buyStatus.Text = "";
|
||||||
|
_scroll.ScrollVertical = 0;
|
||||||
|
SyncSelection();
|
||||||
|
Request();
|
||||||
|
Refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Scorre il corpo della scheda (0 in cima, 1 in fondo).</summary>
|
||||||
|
public void ScrollTo(double fraction)
|
||||||
|
{
|
||||||
|
var bar = _scroll.GetVScrollBar();
|
||||||
|
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Request()
|
||||||
|
{
|
||||||
|
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Process(double delta)
|
||||||
|
{
|
||||||
|
// la scheda aperta si aggiorna una volta al secondo; il pannello al massimo quattro volte
|
||||||
|
_request += delta;
|
||||||
|
_sinceRefresh += delta;
|
||||||
|
if (_request >= 1)
|
||||||
|
{
|
||||||
|
_request = 0;
|
||||||
|
Request();
|
||||||
|
}
|
||||||
|
var w = _session.World;
|
||||||
|
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Result(CommandResultMessage r) => Show(_status, r);
|
||||||
|
|
||||||
|
private void Show(Label label, CommandResultMessage r)
|
||||||
|
{
|
||||||
|
label.Text = r.Message;
|
||||||
|
label.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||||
|
Request();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Refresh()
|
||||||
|
{
|
||||||
|
var w = _session.World;
|
||||||
|
_sinceRefresh = 0;
|
||||||
|
if (w.EntityVersion != _entityVersion) RefreshList();
|
||||||
|
_entityVersion = w.EntityVersion;
|
||||||
|
_detailVersion = w.DetailVersion;
|
||||||
|
foreach (var box in new[] { _notices, _inputs, _workforce, _production, _chainFooter, _plants, _history })
|
||||||
|
foreach (var c in box.GetChildren()) c.QueueFree();
|
||||||
|
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
|
||||||
|
{
|
||||||
|
_title.Text = T("Industrie");
|
||||||
|
_subtitle.Text = T("Scegli un'industria nell'elenco in alto.");
|
||||||
|
_ownerLine.Text = "";
|
||||||
|
_valuation.Text = "";
|
||||||
|
_limit.Text = "";
|
||||||
|
_ring.Set(0, Palette.Amber);
|
||||||
|
_graph.Visible = false;
|
||||||
|
BuildControls(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var card = w.IndustryCards.GetValueOrDefault(_industry);
|
||||||
|
BuildHeader(w, ind, card);
|
||||||
|
BuildControls(ind);
|
||||||
|
UpdateControls(ind, card);
|
||||||
|
var sheet = card?.Sheet;
|
||||||
|
if (card is null || sheet is null)
|
||||||
|
{
|
||||||
|
_graph.Visible = false;
|
||||||
|
foreach (var box in new[] { _inputs, _workforce, _production, _plants })
|
||||||
|
box.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BuildInputs(w, sheet);
|
||||||
|
BuildWorkforce(w, sheet);
|
||||||
|
BuildProduction(w, card, sheet);
|
||||||
|
BuildChain(w, ind, card, sheet);
|
||||||
|
BuildPlants(w, ind, card, sheet);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ elenco
|
||||||
|
|
||||||
|
/// <summary>Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
|
||||||
|
private void RefreshList()
|
||||||
|
{
|
||||||
|
var w = _session.World;
|
||||||
|
int me = w.Summary?.CompanyId ?? 0;
|
||||||
|
long today = Fmt.Today(w);
|
||||||
|
var ordered = w.Industries.Values.Where(i => !i.Closed)
|
||||||
|
.OrderBy(i => i.Owner == me ? 0 : i.Owner < 0 ? 1 : 2).ThenBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Id).ToList();
|
||||||
|
bool same = ordered.Count == _ids.Count && ordered.Select(i => i.Id).SequenceEqual(_ids);
|
||||||
|
if (!same)
|
||||||
|
{
|
||||||
|
_ids.Clear();
|
||||||
|
_chooser.Clear();
|
||||||
|
}
|
||||||
|
for (int n = 0; n < ordered.Count; n++)
|
||||||
|
{
|
||||||
|
var ind = ordered[n];
|
||||||
|
string owner = ind.Owner == me ? T("tua") : ind.Owner < 0 ? T("privati") : Fmt.Company(w, ind.Owner);
|
||||||
|
string stop = ind.StoppedUntilDay >= today ? " · " + T("ferma") : "";
|
||||||
|
string text = $"{ind.Name} · {Fmt.Number(ind.Condition, 0)}% · {owner}{stop}";
|
||||||
|
if (!same)
|
||||||
|
{
|
||||||
|
_ids.Add(ind.Id);
|
||||||
|
_chooser.AddItem(text, n);
|
||||||
|
}
|
||||||
|
else if (_chooser.GetItemText(n) != text)
|
||||||
|
{
|
||||||
|
_chooser.SetItemText(n, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!same) SyncSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SyncSelection()
|
||||||
|
{
|
||||||
|
int index = _ids.IndexOf(_industry);
|
||||||
|
if (index >= 0 && _chooser.Selected != index) _chooser.Select(index);
|
||||||
|
if (index < 0) _chooser.Select(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ intestazione
|
||||||
|
|
||||||
|
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
|
||||||
|
{
|
||||||
|
int me = w.Summary?.CompanyId ?? 0;
|
||||||
|
var sheet = card?.Sheet;
|
||||||
|
_title.Text = ind.Name;
|
||||||
|
string level = sheet is null ? $"{T("Livello")} {ind.Level}" : $"{T("Livello")} {sheet.Level} {T("di")} {sheet.MaxLevel}";
|
||||||
|
_subtitle.Text = $"{TypeName(w, ind.Type)} · {level}";
|
||||||
|
string owner = ind.Owner == me ? T("la tua compagnia") : ind.Owner < 0 ? T("proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||||
|
string served = "";
|
||||||
|
if (sheet is not null)
|
||||||
|
{
|
||||||
|
var names = sheet.ServingStations.Select(s => w.Stations.TryGetValue(s, out var st) ? st.Name : $"#{s}").Take(3).ToList();
|
||||||
|
served = names.Count == 0
|
||||||
|
? " · " + T("nessuna stazione la serve")
|
||||||
|
: $" · {T("servita dalla stazione")} {string.Join(", ", names)}" +
|
||||||
|
(sheet.ServingLine >= 0 && w.Lines.TryGetValue(sheet.ServingLine, out var line) ? $" ({T("linea")} {line.Name})" : "");
|
||||||
|
}
|
||||||
|
_ownerLine.Text = $"{T("Proprietà")}: {owner}{served}";
|
||||||
|
_valuation.Text = card?.Valuation.ToString() ?? "—";
|
||||||
|
float e = sheet?.Efficiency ?? ind.Efficiency;
|
||||||
|
var limit = sheet is null ? IndustryLimit.None : (IndustryLimit)sheet.Limit;
|
||||||
|
_ring.Set(e, limit is IndustryLimit.None ? Palette.Ok : e < 0.35f ? Palette.Danger : Palette.Amber);
|
||||||
|
_limit.Text = sheet is null ? T("Efficienza") : $"{T("Efficienza")} · {LimitText(limit)}";
|
||||||
|
|
||||||
|
long today = Fmt.Today(w);
|
||||||
|
if (ind.StoppedUntilDay >= today)
|
||||||
|
_notices.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
|
||||||
|
else if (ind.PendingWork != 0)
|
||||||
|
_notices.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
|
||||||
|
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
|
||||||
|
if (ind.PartsShort)
|
||||||
|
_notices.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tre schede
|
||||||
|
|
||||||
|
private void BuildInputs(ClientWorld w, IndustrySheetInfo s)
|
||||||
|
{
|
||||||
|
if (s.Inputs.Count == 0)
|
||||||
|
{
|
||||||
|
_inputs.AddChild(Wrapped(T("Non consuma materie prime: estrae, coltiva o raccoglie da sé."), 13, Palette.TextSecondary));
|
||||||
|
}
|
||||||
|
foreach (var f in s.Inputs)
|
||||||
|
{
|
||||||
|
string unit = Unit(w, f.Good);
|
||||||
|
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||||
|
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
|
||||||
|
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||||
|
_inputs.AddChild(Wrapped($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||||
|
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, f.Good, unit, supplier: true));
|
||||||
|
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
|
||||||
|
_inputs.AddChild(PanelKit.Separator());
|
||||||
|
}
|
||||||
|
if (s.Inputs.Count > 0)
|
||||||
|
_inputs.AddChild(PanelKit.Pair($"{T("Copertura degli ingressi")} ({s.CoverageWindowDays} {T("giorni")})", ColoredValue(Fmt.Pct(s.CovInput, 0), CoverageColor(s.CovInput))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BuildWorkforce(ClientWorld w, IndustrySheetInfo s)
|
||||||
|
{
|
||||||
|
WorkforceBlock(w, s.Workers, s.CovWorkers, s.CoverageWindowDays, staff: false);
|
||||||
|
_workforce.AddChild(PanelKit.Separator());
|
||||||
|
WorkforceBlock(w, s.Staff, s.CovStaff, s.CoverageWindowDays, staff: true);
|
||||||
|
var limit = (IndustryLimit)s.Limit;
|
||||||
|
if (limit is IndustryLimit.Workers or IndustryLimit.Staff)
|
||||||
|
{
|
||||||
|
var wf = limit == IndustryLimit.Staff ? s.Staff : s.Workers;
|
||||||
|
string who = limit == IndustryLimit.Staff ? T("il personale qualificato") : T("i lavoratori");
|
||||||
|
_workforce.AddChild(UiTheme.Notice($"{T("Collo di bottiglia")}: {who}. {T("Mancano")} {wf.Missing} {T("persone: portale in treno dalle città vicine.")}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WorkforceBlock(ClientWorld w, WorkforceInfo f, float coverage30, int window, bool staff)
|
||||||
|
{
|
||||||
|
var color = staff ? Palette.Staff : Palette.Workers;
|
||||||
|
if (f.Jobs <= 0)
|
||||||
|
{
|
||||||
|
_workforce.AddChild(UiTheme.Text(staff ? T("Nessun posto per il personale") : T("Nessun posto per i lavoratori"), 13, Palette.TextSecondary));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
|
||||||
|
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
|
||||||
|
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
|
||||||
|
// OnSite sono i posti coperti da chi vive negli alloggi dell'industria, non i presenti
|
||||||
|
_workforce.AddChild(Wrapped($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("in sede")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||||
|
if (f.Missing > 0)
|
||||||
|
{
|
||||||
|
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
|
||||||
|
_workforce.AddChild(Wrapped($"{T("Mancano")} {f.Missing}" + (reason.Length > 0 ? " · " + reason : ""), 12, Palette.Amber));
|
||||||
|
}
|
||||||
|
foreach (var src in f.Sources)
|
||||||
|
{
|
||||||
|
string town = w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}";
|
||||||
|
string via = src.Walking ? T("a piedi") : src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var line) ? line.Name : Fmt.Company(w, src.Carrier);
|
||||||
|
string time = src.Walking || src.Minutes <= 0 ? "" : $" · {Fmt.Number(src.Minutes, 0)} min";
|
||||||
|
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
|
||||||
|
}
|
||||||
|
if (f.SourceCount > f.Sources.Count)
|
||||||
|
_workforce.AddChild(Wrapped($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
|
||||||
|
{
|
||||||
|
foreach (var f in s.Outputs)
|
||||||
|
{
|
||||||
|
string unit = Unit(w, f.Good);
|
||||||
|
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||||
|
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
|
||||||
|
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||||
|
_production.AddChild(Wrapped($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||||
|
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, f.Good, unit, supplier: false));
|
||||||
|
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
|
||||||
|
_production.AddChild(PanelKit.Separator());
|
||||||
|
}
|
||||||
|
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
|
||||||
|
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
|
||||||
|
var sale = PanelKit.Pair(T("Prezzo di vendita"), PanelKit.Value(s.SalePrice < 0 ? "—" : Fmt.PricePrecise(s.SalePrice)));
|
||||||
|
// le industrie vendono al prezzo globale del giorno (ADR 0004): si spiega quello
|
||||||
|
if (s.SalePrice >= 0 && s.Outputs.Count == 1)
|
||||||
|
{
|
||||||
|
int good = s.Outputs[0].Good;
|
||||||
|
WhyTooltip.Attach(sale, () => new ExplainTarget(ExplainSubject.GlobalPrice, good));
|
||||||
|
}
|
||||||
|
_production.AddChild(sale);
|
||||||
|
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
|
||||||
|
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ catena produttiva
|
||||||
|
|
||||||
|
private void BuildChain(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||||
|
{
|
||||||
|
var left = new List<ChainNode>();
|
||||||
|
foreach (var f in s.Inputs)
|
||||||
|
foreach (var p in f.Partners.Take(2))
|
||||||
|
left.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.Number(p.MonthlyUnits, 0)} {Unit(w, f.Good)}/{T("mese")}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||||
|
foreach (var (wf, staff) in new[] { (s.Workers, false), (s.Staff, true) })
|
||||||
|
foreach (var src in wf.Sources.Take(staff ? 1 : 2))
|
||||||
|
left.Add(new ChainNode(w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}",
|
||||||
|
$"{src.Headcount} {(staff ? T("tecnici") : T("lavoratori"))}", staff ? ChainEdge.Staff : ChainEdge.Workers));
|
||||||
|
var right = new List<ChainNode>();
|
||||||
|
foreach (var f in s.Outputs)
|
||||||
|
foreach (var p in f.Partners.Take(3))
|
||||||
|
right.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.PricePrecise(p.Price)}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
|
||||||
|
string outputs = string.Join(", ", s.Outputs.Select(f => GoodName(w, f.Good)));
|
||||||
|
_graph.Set(left, new ChainNode(ind.Name, $"{T("Livello")} {s.Level} · {outputs}", ChainEdge.Goods), right);
|
||||||
|
_graph.Visible = true;
|
||||||
|
|
||||||
|
// azioni della catena: linea verso l'industria e offerta di acquisto
|
||||||
|
var actions = PanelKit.Row(10);
|
||||||
|
var plan = UiTheme.Primary(T("Crea una linea verso questa industria"));
|
||||||
|
plan.CustomMinimumSize = new Vector2(0, 44);
|
||||||
|
int id = ind.Id;
|
||||||
|
plan.Pressed += () => PlanLineRequested?.Invoke(id);
|
||||||
|
actions.AddChild(plan);
|
||||||
|
int me = w.Summary?.CompanyId ?? 0;
|
||||||
|
if (ind.Owner != me)
|
||||||
|
{
|
||||||
|
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
|
||||||
|
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
|
||||||
|
buy.Pressed += () =>
|
||||||
|
{
|
||||||
|
_buyStatus.Text = T("Offerta inviata…");
|
||||||
|
_buyStatus.AddThemeColorOverride("font_color", Palette.TextSecondary);
|
||||||
|
_session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), r => Show(_buyStatus, r));
|
||||||
|
};
|
||||||
|
actions.AddChild(buy);
|
||||||
|
}
|
||||||
|
_chainFooter.AddChild(actions);
|
||||||
|
if (ind.Owner == me)
|
||||||
|
_chainFooter.AddChild(Wrapped(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||||
|
else if (ind.Owner < 0 && !s.ForSale)
|
||||||
|
_chainFooter.AddChild(Wrapped(T("Industria inattiva: non è in vendita finché non riprende a produrre."), 12, Palette.TextSecondary));
|
||||||
|
else if (!s.ForSale)
|
||||||
|
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
|
||||||
|
else if (!s.BuyUnlocked)
|
||||||
|
_chainFooter.AddChild(UiTheme.Text($"{T("Disponibile al livello")} «{Fmt.Tier(w, s.BuyTier)}» ({T("avanzamento")} {Fmt.Progress(s.BuyProgress)})", 12, Palette.TextSecondary));
|
||||||
|
else
|
||||||
|
_chainFooter.AddChild(UiTheme.Text($"{T("Prezzo chiesto dai proprietari")}: {card.Valuation}", 12, Palette.TextSecondary));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ impianti e crescita
|
||||||
|
|
||||||
|
private void BuildPlants(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
|
||||||
|
{
|
||||||
|
var condColor = MaintenancePanel.ConditionColor((int)ind.Condition);
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
|
||||||
|
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||||
|
_plants.AddChild(Wrapped($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||||
|
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||||
|
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
|
||||||
|
if (s.ReserveFraction >= 0)
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Giacimento residuo"), ColoredValue(Fmt.Pct(s.ReserveFraction, 0), s.Depletion < 1 ? Palette.Amber : Palette.Text)));
|
||||||
|
if (s.EventCapacity < 1) _plants.AddChild(PanelKit.Pair(T("Capacità ridotta da un evento"), ColoredValue("×" + Fmt.Number(s.EventCapacity, 2), Palette.Amber)));
|
||||||
|
|
||||||
|
// crescita trimestrale: punteggio in corso, soglie, componenti
|
||||||
|
_plants.AddChild(PanelKit.Separator());
|
||||||
|
var scoreHeader = FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}");
|
||||||
|
_plants.AddChild(scoreHeader);
|
||||||
|
var bar = new ScoreBar();
|
||||||
|
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
|
||||||
|
int scored = _industry;
|
||||||
|
WhyTooltip.Attach(scoreHeader, () => new ExplainTarget(ExplainSubject.IndustryGrowth, scored));
|
||||||
|
WhyTooltip.Attach(bar, () => new ExplainTarget(ExplainSubject.IndustryGrowth, scored));
|
||||||
|
_plants.AddChild(bar);
|
||||||
|
_plants.AddChild(Wrapped($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
|
||||||
|
var g = w.Data.Balance.Growth;
|
||||||
|
_plants.AddChild(Wrapped($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
|
||||||
|
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
|
||||||
|
if (!s.Served)
|
||||||
|
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
|
||||||
|
else if (s.Level >= s.MaxLevel)
|
||||||
|
_plants.AddChild(UiTheme.Text(T("Livello massimo raggiunto"), 12, Palette.Ok));
|
||||||
|
|
||||||
|
int me = w.Summary?.CompanyId ?? 0;
|
||||||
|
if (ind.Owner == me)
|
||||||
|
{
|
||||||
|
_plants.AddChild(PanelKit.Separator());
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||||
|
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||||
|
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||||
|
_plants.AddChild(Wrapped($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||||
|
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||||
|
}
|
||||||
|
|
||||||
|
_history.AddChild(PanelKit.Separator());
|
||||||
|
_history.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
|
||||||
|
if (card.Stops.Count == 0) _history.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
|
||||||
|
foreach (var stop in Enumerable.Reverse(card.Stops).Take(6))
|
||||||
|
_history.AddChild(UiTheme.Text($"{Fmt.Date(w, stop.Day)} · {StopName(stop.Kind)} · {stop.Days} {T("giorni")}", 13, stop.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
|
||||||
|
private void BuildControls(IndustryInfo? ind)
|
||||||
|
{
|
||||||
|
int me = _session.World.Summary?.CompanyId ?? 0;
|
||||||
|
var key = ind is null || ind.Owner != me ? (-1, -1) : (ind.Id, ind.Owner);
|
||||||
|
if (key == _controlsKey) return;
|
||||||
|
_controlsKey = key;
|
||||||
|
foreach (var c in _controls.GetChildren()) c.QueueFree();
|
||||||
|
_budgetButtons.Clear();
|
||||||
|
_partsOrder = null;
|
||||||
|
_overhaul = _upgrade = null;
|
||||||
|
if (ind is null || ind.Owner != me) return;
|
||||||
|
var w = _session.World;
|
||||||
|
int id = ind.Id;
|
||||||
|
_controls.AddChild(PanelKit.Separator());
|
||||||
|
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
|
||||||
|
var row = PanelKit.Row(6);
|
||||||
|
var group = new ButtonGroup();
|
||||||
|
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
|
||||||
|
{
|
||||||
|
var p = w.Data.Balance.IndustryMaintenance.For(budget);
|
||||||
|
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
|
||||||
|
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
|
||||||
|
_budgetButtons.Add(b);
|
||||||
|
row.AddChild(b);
|
||||||
|
}
|
||||||
|
_controls.AddChild(row);
|
||||||
|
|
||||||
|
var order = PanelKit.Row(6);
|
||||||
|
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
|
||||||
|
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
|
||||||
|
caption.MouseFilter = MouseFilterEnum.Pass;
|
||||||
|
order.AddChild(caption);
|
||||||
|
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
order.AddChild(_partsOrder);
|
||||||
|
var orderButton = new Button { Text = T("Ordina ricambi") };
|
||||||
|
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
|
||||||
|
order.AddChild(orderButton);
|
||||||
|
_controls.AddChild(order);
|
||||||
|
|
||||||
|
var actions = PanelKit.Row(6);
|
||||||
|
var m = w.Data.Balance.IndustryMaintenance;
|
||||||
|
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||||
|
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||||
|
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||||
|
overhaul.SetMeta(BaseTooltip, overhaul.TooltipText);
|
||||||
|
actions.AddChild(overhaul);
|
||||||
|
_overhaul = overhaul;
|
||||||
|
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||||
|
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||||
|
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||||
|
upgrade.SetMeta(BaseTooltip, upgrade.TooltipText);
|
||||||
|
actions.AddChild(upgrade);
|
||||||
|
_upgrade = upgrade;
|
||||||
|
_controls.AddChild(actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
|
||||||
|
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
|
||||||
|
|
||||||
|
// revisione e ammodernamento: il server li rifiuta durante un fermo, con un lavoro già in
|
||||||
|
// programma o (l'ammodernamento) al livello massimo; il pulsante lo dice prima
|
||||||
|
string busy = ind.StoppedUntilDay >= Fmt.Today(_session.World) ? T("L'industria è ferma: riprova a fermo finito.")
|
||||||
|
: ind.PendingWork != 0 ? T("C'è già un lavoro in programma.") : "";
|
||||||
|
var sheet = card?.Sheet;
|
||||||
|
string top = sheet is not null && sheet.Level >= sheet.MaxLevel ? T("Livello massimo raggiunto") : "";
|
||||||
|
Gate(_overhaul, busy);
|
||||||
|
Gate(_upgrade, busy.Length > 0 ? busy : top);
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string BaseTooltip = "base_tooltip";
|
||||||
|
|
||||||
|
/// <summary>Abilita il pulsante, o lo disabilita con il motivo in testa al suggerimento.</summary>
|
||||||
|
private static void Gate(Button? button, string reason)
|
||||||
|
{
|
||||||
|
if (button is null) return;
|
||||||
|
button.Disabled = reason.Length > 0;
|
||||||
|
string tip = button.GetMeta(BaseTooltip, "").AsString();
|
||||||
|
button.TooltipText = reason.Length > 0 ? reason + "\n" + tip : tip;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ pezzi
|
||||||
|
|
||||||
|
private static HBoxContainer FlowHeader(string name, string value, Color? color = null)
|
||||||
|
{
|
||||||
|
var row = PanelKit.Row(8);
|
||||||
|
var l = UiTheme.Text(name, 15, color, bold: true);
|
||||||
|
l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
row.AddChild(l);
|
||||||
|
row.AddChild(UiTheme.Text(value, 14, bold: true));
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProgressBar Bar(float fraction, Color color)
|
||||||
|
{
|
||||||
|
var bar = new ProgressBar { MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||||
|
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||||
|
return bar;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Control PartnerLine(ClientWorld w, ChainPartnerInfo p, int good, string unit, bool supplier)
|
||||||
|
{
|
||||||
|
string link = p.Line >= 0 && w.Lines.TryGetValue(p.Line, out var line)
|
||||||
|
? $"{T("linea")} {line.Name}"
|
||||||
|
: $"{T("non collegata")} · {Fmt.Number(p.DistanceKm, 1)} km";
|
||||||
|
string amount = (ChainPartnerKind)p.Kind == ChainPartnerKind.Hub ? "" : $" · {Fmt.Number(p.MonthlyUnits, 0)} {unit}/{T("mese")}";
|
||||||
|
string text = $"{(supplier ? "←" : "→")} {PartnerName(w, p)}{amount} · {Fmt.PricePrecise(p.Price)} · {link}";
|
||||||
|
var label = Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
|
||||||
|
// prezzo del partner spiegato dal server: locale per le industrie che comprano, globale per chi vende e per
|
||||||
|
// le città; quello degli hub è il prezzo mondiale con il dazio, senza spiegazione
|
||||||
|
var kind = (ChainPartnerKind)p.Kind;
|
||||||
|
int target = p.Target;
|
||||||
|
if (kind == ChainPartnerKind.Industry && !supplier) WhyTooltip.Attach(label, () => new ExplainTarget(ExplainSubject.LocalPrice, good, target));
|
||||||
|
else if (kind != ChainPartnerKind.Hub) WhyTooltip.Attach(label, () => new ExplainTarget(ExplainSubject.GlobalPrice, good));
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string PartnerName(ClientWorld w, ChainPartnerInfo p) => (ChainPartnerKind)p.Kind switch
|
||||||
|
{
|
||||||
|
ChainPartnerKind.Industry => w.Industries.TryGetValue(p.Target, out var i) ? i.Name : $"#{p.Target}",
|
||||||
|
ChainPartnerKind.Hub => w.Hubs.TryGetValue(p.Target, out var h) ? h.Name : $"#{p.Target}",
|
||||||
|
_ => w.Towns.TryGetValue(p.Target, out var t) ? t.Name : $"#{p.Target}",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static int PartnerIndustry(ChainPartnerInfo p) => (ChainPartnerKind)p.Kind == ChainPartnerKind.Industry ? p.Target : -1;
|
||||||
|
|
||||||
|
private static bool English => TranslationServer.GetLocale().StartsWith("en");
|
||||||
|
|
||||||
|
private static string GoodName(ClientWorld w, int good) =>
|
||||||
|
good >= 0 && good < w.Data.Goods.Count ? (English ? w.Data.Goods[good].NameEn : w.Data.Goods[good].NameIt) : $"#{good}";
|
||||||
|
|
||||||
|
private static string Unit(ClientWorld w, int good) => good >= 0 && good < w.Data.Goods.Count ? w.Data.Goods[good].Unit : "";
|
||||||
|
|
||||||
|
private static string TypeName(ClientWorld w, string type)
|
||||||
|
{
|
||||||
|
var def = w.Data.Industries.FirstOrDefault(d => d.Id == type);
|
||||||
|
return def is null ? type : English ? def.NameEn : def.NameIt;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Color CoverageColor(float coverage) => coverage >= 0.9f ? Palette.Ok : coverage >= 0.5f ? Palette.Amber : Palette.Danger;
|
||||||
|
|
||||||
|
private static Control StockRow(string caption, int have, int target, Color color)
|
||||||
|
{
|
||||||
|
var row = PanelKit.Row(8);
|
||||||
|
var name = UiTheme.Text(caption, 13, Palette.TextSecondary);
|
||||||
|
name.CustomMinimumSize = new Vector2(96, 0);
|
||||||
|
row.AddChild(name);
|
||||||
|
var bar = new ProgressBar { MaxValue = Math.Max(1, Math.Max(have, target)), Value = have, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter };
|
||||||
|
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 3, 0));
|
||||||
|
row.AddChild(bar);
|
||||||
|
row.AddChild(UiTheme.Text($"{have} / {target}", 13, bold: true));
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ testi
|
||||||
|
|
||||||
|
/// <summary>Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.</summary>
|
||||||
|
public static string LimitText(IndustryLimit limit) => limit switch
|
||||||
|
{
|
||||||
|
IndustryLimit.None => T("a piena capacità"),
|
||||||
|
IndustryLimit.Inputs => T("limitata dalle materie prime"),
|
||||||
|
IndustryLimit.Workers => T("limitata dai lavoratori"),
|
||||||
|
IndustryLimit.Staff => T("limitata dal personale"),
|
||||||
|
IndustryLimit.Profit => T("limitata dalla redditività"),
|
||||||
|
IndustryLimit.Condition => T("limitata dagli impianti"),
|
||||||
|
IndustryLimit.Depletion => T("limitata dal giacimento"),
|
||||||
|
IndustryLimit.Event => T("limitata da un evento"),
|
||||||
|
IndustryLimit.Stopped => T("ferma"),
|
||||||
|
_ => T("inattiva"),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string StopName(byte kind) => kind switch
|
||||||
|
{
|
||||||
|
1 => T("Guasto"),
|
||||||
|
2 => T("Incidente grave"),
|
||||||
|
3 => T("Revisione"),
|
||||||
|
4 => T("Ammodernamento"),
|
||||||
|
_ => T("Fermo"),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string WorkName(byte work) => work switch
|
||||||
|
{
|
||||||
|
1 => T("Revisione programmata"),
|
||||||
|
2 => T("Ammodernamento programmato"),
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static Label ColoredValue(string text, Color color)
|
||||||
|
{
|
||||||
|
var l = PanelKit.Value(text);
|
||||||
|
l.AddThemeColorOverride("font_color", color);
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Label Wrapped(string text, int size, Color? color)
|
||||||
|
{
|
||||||
|
var l = UiTheme.Text(text, size, color);
|
||||||
|
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -0,0 +1,198 @@
|
|||||||
|
using Godot;
|
||||||
|
using RailEnterprise.Client.App;
|
||||||
|
|
||||||
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
|
/// <summary>Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.</summary>
|
||||||
|
public partial class EfficiencyRing : Control
|
||||||
|
{
|
||||||
|
private float _value;
|
||||||
|
private Color _color = Palette.Amber;
|
||||||
|
|
||||||
|
public EfficiencyRing() => CustomMinimumSize = new Vector2(112, 112);
|
||||||
|
|
||||||
|
public void Set(float value, Color color)
|
||||||
|
{
|
||||||
|
_value = Math.Clamp(value, 0, 1);
|
||||||
|
_color = color;
|
||||||
|
QueueRedraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Draw()
|
||||||
|
{
|
||||||
|
var c = Size / 2;
|
||||||
|
float r = Math.Min(Size.X, Size.Y) / 2 - 8;
|
||||||
|
DrawArc(c, r, 0, Mathf.Tau, 64, Palette.Inner, 10, true);
|
||||||
|
if (_value > 0) DrawArc(c, r, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * _value, 64, _color, 10, true);
|
||||||
|
string text = Fmt.Pct(_value, 0);
|
||||||
|
var font = UiTheme.BodyBold;
|
||||||
|
const int size = 24;
|
||||||
|
var s = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
|
||||||
|
DrawString(font, new Vector2(c.X - s.X / 2, c.Y + s.Y / 4), text, HorizontalAlignment.Left, -1, size, Palette.Text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Barra del punteggio di crescita: il riempimento è il punteggio del trimestre in corso, le tacche
|
||||||
|
/// sono le soglie di declassamento (rossa) e di promozione (verde), la lineetta l'ultimo trimestre.
|
||||||
|
/// </summary>
|
||||||
|
public partial class ScoreBar : Control
|
||||||
|
{
|
||||||
|
private float _score, _last = -1, _down, _up;
|
||||||
|
|
||||||
|
public ScoreBar() => CustomMinimumSize = new Vector2(0, 26);
|
||||||
|
|
||||||
|
public void Set(float score, float last, float down, float up)
|
||||||
|
{
|
||||||
|
(_score, _last, _down, _up) = (Math.Clamp(score, 0, 1), last, down, up);
|
||||||
|
QueueRedraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Draw()
|
||||||
|
{
|
||||||
|
float h = 12, y = 7, w = Size.X;
|
||||||
|
DrawRect(new Rect2(0, y, w, h), Palette.Inner);
|
||||||
|
var fill = _score >= _up ? Palette.Ok : _score < _down ? Palette.Danger : Palette.Amber;
|
||||||
|
DrawRect(new Rect2(0, y, w * _score, h), fill);
|
||||||
|
DrawLine(new Vector2(w * _down, 2), new Vector2(w * _down, y + h + 5), Palette.Danger, 2);
|
||||||
|
DrawLine(new Vector2(w * _up, 2), new Vector2(w * _up, y + h + 5), Palette.Ok, 2);
|
||||||
|
if (_last >= 0) DrawLine(new Vector2(w * Math.Clamp(_last, 0, 1), y - 3), new Vector2(w * Math.Clamp(_last, 0, 1), y + h + 3), Palette.Text, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).</summary>
|
||||||
|
public enum ChainEdge
|
||||||
|
{
|
||||||
|
/// <summary>Merci su una linea della compagnia: linea piena ambra.</summary>
|
||||||
|
Goods,
|
||||||
|
/// <summary>Lavoratori pendolari: tratteggio blu.</summary>
|
||||||
|
Workers,
|
||||||
|
/// <summary>Personale qualificato: puntinato azzurro.</summary>
|
||||||
|
Staff,
|
||||||
|
/// <summary>Partner possibile ma non collegato: tratteggio grigio.</summary>
|
||||||
|
Unlinked,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).</summary>
|
||||||
|
public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Grafo della catena produttiva: fornitori e città dei pendolari a sinistra, l'industria al centro,
|
||||||
|
/// clienti a destra. I nodi delle industrie si aprono con un clic.
|
||||||
|
/// </summary>
|
||||||
|
public partial class ChainGraph : Control
|
||||||
|
{
|
||||||
|
private const float NodeW = 210, NodeH = 50, Gap = 10;
|
||||||
|
private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
|
||||||
|
private List<ChainNode> _left = [], _right = [];
|
||||||
|
private ChainNode? _center;
|
||||||
|
|
||||||
|
public event Action<int>? IndustryClicked;
|
||||||
|
|
||||||
|
public ChainGraph()
|
||||||
|
{
|
||||||
|
CustomMinimumSize = new Vector2(0, 260);
|
||||||
|
MouseFilter = MouseFilterEnum.Stop;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Set(List<ChainNode> left, ChainNode center, List<ChainNode> right)
|
||||||
|
{
|
||||||
|
(_left, _center, _right) = (left, center, right);
|
||||||
|
int rows = Math.Max(3, Math.Max(left.Count, right.Count));
|
||||||
|
CustomMinimumSize = new Vector2(0, rows * (NodeH + Gap) + 10);
|
||||||
|
QueueRedraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _Draw()
|
||||||
|
{
|
||||||
|
_hits.Clear();
|
||||||
|
if (_center is null) return;
|
||||||
|
float w = Size.X, h = Size.Y;
|
||||||
|
float nodeW = Math.Min(NodeW, (w - 80) / 3);
|
||||||
|
var centerRect = new Rect2(w / 2 - nodeW / 2, h / 2 - NodeH * 0.7f, nodeW, NodeH * 1.4f);
|
||||||
|
var leftRects = Column(_left, 0, nodeW, h);
|
||||||
|
var rightRects = Column(_right, w - nodeW, nodeW, h);
|
||||||
|
for (int i = 0; i < _left.Count; i++)
|
||||||
|
Edge(new Vector2(leftRects[i].End.X, leftRects[i].GetCenter().Y), new Vector2(centerRect.Position.X, centerRect.GetCenter().Y), _left[i].Edge);
|
||||||
|
for (int i = 0; i < _right.Count; i++)
|
||||||
|
Edge(new Vector2(centerRect.End.X, centerRect.GetCenter().Y), new Vector2(rightRects[i].Position.X, rightRects[i].GetCenter().Y), _right[i].Edge);
|
||||||
|
for (int i = 0; i < _left.Count; i++) Node(leftRects[i], _left[i], false);
|
||||||
|
for (int i = 0; i < _right.Count; i++) Node(rightRects[i], _right[i], false);
|
||||||
|
Node(centerRect, _center, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Rect2> Column(List<ChainNode> nodes, float x, float width, float height)
|
||||||
|
{
|
||||||
|
float total = nodes.Count * NodeH + Math.Max(0, nodes.Count - 1) * Gap;
|
||||||
|
float y = (height - total) / 2;
|
||||||
|
var rects = new List<Rect2>(nodes.Count);
|
||||||
|
foreach (var _ in nodes)
|
||||||
|
{
|
||||||
|
rects.Add(new Rect2(x, y, width, NodeH));
|
||||||
|
y += NodeH + Gap;
|
||||||
|
}
|
||||||
|
return rects;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Edge(Vector2 from, Vector2 to, ChainEdge edge)
|
||||||
|
{
|
||||||
|
switch (edge)
|
||||||
|
{
|
||||||
|
case ChainEdge.Goods:
|
||||||
|
DrawLine(from, to, Palette.Amber, 3, true);
|
||||||
|
break;
|
||||||
|
case ChainEdge.Workers:
|
||||||
|
DrawDashedLine(from, to, Palette.Workers, 2.5f, 10);
|
||||||
|
break;
|
||||||
|
case ChainEdge.Staff:
|
||||||
|
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// grigio leggibile sul fondo della scheda (il bordo dei pannelli sparirebbe)
|
||||||
|
DrawDashedLine(from, to, Palette.TextSecondary, 2, 8);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Node(Rect2 rect, ChainNode node, bool center)
|
||||||
|
{
|
||||||
|
bool unlinked = !center && node.Edge == ChainEdge.Unlinked;
|
||||||
|
var border = center ? Palette.Amber : node.Edge switch
|
||||||
|
{
|
||||||
|
ChainEdge.Goods => Palette.AmberDark,
|
||||||
|
ChainEdge.Workers => Palette.Workers,
|
||||||
|
ChainEdge.Staff => Palette.Staff,
|
||||||
|
_ => Palette.Inner,
|
||||||
|
};
|
||||||
|
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
|
||||||
|
// partner non collegato: bordo tratteggiato grigio, come «Opportunità non collegata» nell'immagine 07
|
||||||
|
if (unlinked) DashedRect(rect.Grow(-1), Palette.TextSecondary);
|
||||||
|
var font = UiTheme.BodyBold;
|
||||||
|
float width = rect.Size.X - 16;
|
||||||
|
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
|
||||||
|
center ? Palette.AmberLight : Palette.Text);
|
||||||
|
DrawString(UiTheme.Body, rect.Position + new Vector2(8, center ? 48 : 39), node.Subtitle, HorizontalAlignment.Left, width, 12, Palette.TextSecondary);
|
||||||
|
if (node.Industry >= 0) _hits.Add((rect, node));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DashedRect(Rect2 r, Color color)
|
||||||
|
{
|
||||||
|
var (a, b, c, d) = (r.Position, new Vector2(r.End.X, r.Position.Y), r.End, new Vector2(r.Position.X, r.End.Y));
|
||||||
|
DrawDashedLine(a, b, color, 1.5f, 6);
|
||||||
|
DrawDashedLine(b, c, color, 1.5f, 6);
|
||||||
|
DrawDashedLine(c, d, color, 1.5f, 6);
|
||||||
|
DrawDashedLine(d, a, color, 1.5f, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void _GuiInput(InputEvent e)
|
||||||
|
{
|
||||||
|
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
|
||||||
|
foreach (var (rect, node) in _hits)
|
||||||
|
{
|
||||||
|
if (!rect.HasPoint(click.Position)) continue;
|
||||||
|
IndustryClicked?.Invoke(node.Industry);
|
||||||
|
AcceptEvent();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-7
@@ -1,11 +1,11 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
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>
|
/// <summary>Scheda dell'entità selezionata (treno, stazione, industria, città) come nel pannello destro dell'immagine 01.</summary>
|
||||||
public partial class InfoPanel : VBoxContainer
|
public partial class InfoPanel : VBoxContainer
|
||||||
@@ -142,6 +142,7 @@ public partial class InfoPanel : VBoxContainer
|
|||||||
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
|
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
|
||||||
}
|
}
|
||||||
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
|
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
|
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
|
||||||
int me = w.Summary?.CompanyId ?? 0;
|
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);
|
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("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
|
||||||
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
|
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
|
||||||
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
|
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)
|
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
|
||||||
if (w.Employment is { } report)
|
if (w.Employment is { } report)
|
||||||
{
|
{
|
||||||
@@ -197,7 +199,7 @@ public partial class InfoPanel : VBoxContainer
|
|||||||
}
|
}
|
||||||
default:
|
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);
|
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;
|
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
AddChild(help);
|
AddChild(help);
|
||||||
File renamed without changes.
+11
-7
@@ -1,12 +1,12 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Core.Rail;
|
using RailEnterprise.Core.Rail;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
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>
|
/// <summary>Linee: fermate scelte con un clic sulle stazioni, nome e colore, attesa del pieno alla prima fermata.</summary>
|
||||||
public partial class LinesPanel : VBoxContainer
|
public partial class LinesPanel : VBoxContainer
|
||||||
@@ -29,6 +29,9 @@ public partial class LinesPanel : VBoxContainer
|
|||||||
|
|
||||||
public event Action? StopsChanged;
|
public event Action? StopsChanged;
|
||||||
|
|
||||||
|
/// <summary>Pulsante «Crea linea» (per l'evidenziazione del tutorial).</summary>
|
||||||
|
public Control? CreateButton { get; }
|
||||||
|
|
||||||
public LinesPanel(GameSession session)
|
public LinesPanel(GameSession session)
|
||||||
{
|
{
|
||||||
_session = session;
|
_session = session;
|
||||||
@@ -54,6 +57,7 @@ public partial class LinesPanel : VBoxContainer
|
|||||||
RefreshStops();
|
RefreshStops();
|
||||||
};
|
};
|
||||||
row.AddChild(create);
|
row.AddChild(create);
|
||||||
|
CreateButton = create;
|
||||||
row.AddChild(clear);
|
row.AddChild(clear);
|
||||||
AddChild(row);
|
AddChild(row);
|
||||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
File renamed without changes.
+142
-10
@@ -1,17 +1,21 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Net;
|
using RailEnterprise.Client.Net;
|
||||||
using ViaFerrea.Core.Commands;
|
using RailEnterprise.Core.Commands;
|
||||||
using ViaFerrea.Core.Common;
|
using RailEnterprise.Core.Common;
|
||||||
using ViaFerrea.Protocol.Messages;
|
using RailEnterprise.Core.Data;
|
||||||
using static ViaFerrea.Client.App.Localization;
|
using RailEnterprise.Protocol.Messages;
|
||||||
|
using static RailEnterprise.Client.App.Localization;
|
||||||
|
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||||
|
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||||
|
|
||||||
namespace ViaFerrea.Client.Panels;
|
namespace RailEnterprise.Client.Panels;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
|
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
|
||||||
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
|
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
|
||||||
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
|
/// la scorta di ricambi, rinnovo della flotta (ere e obsolescenza, ADR 0020). Le cartelle, i registri
|
||||||
|
/// e il quadro della flotta arrivano su richiesta dal server: età, successori e valori non si calcolano qui.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class MaintenancePanel : VBoxContainer
|
public partial class MaintenancePanel : VBoxContainer
|
||||||
{
|
{
|
||||||
@@ -29,12 +33,19 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
private readonly VBoxContainer _workshop = PanelKit.Column(8);
|
private readonly VBoxContainer _workshop = PanelKit.Column(8);
|
||||||
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
|
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
|
||||||
private readonly HBoxContainer _orderRow = PanelKit.Row();
|
private readonly HBoxContainer _orderRow = PanelKit.Row();
|
||||||
|
private readonly VBoxContainer _fleet = PanelKit.Column(6);
|
||||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||||
private readonly List<int> _trainIds = [];
|
private readonly List<int> _trainIds = [];
|
||||||
private readonly List<int> _depotIds = [];
|
private readonly List<int> _depotIds = [];
|
||||||
private int _train = -1, _depot = -1;
|
private int _train = -1, _depot = -1;
|
||||||
private int _entityVersion = -1, _detailVersion = -1;
|
private int _entityVersion = -1, _detailVersion = -1;
|
||||||
private double _request;
|
private double _request;
|
||||||
|
private long _fleetDay = long.MinValue;
|
||||||
|
private double _sinceFleet = double.MaxValue;
|
||||||
|
// quadro della flotta mostrato: la sezione si ricostruisce solo quando ne arriva uno nuovo, così i
|
||||||
|
// pulsanti «Rinnova» non si ricreano sotto il cursore a ogni aggiornamento della cartella
|
||||||
|
private FleetReport? _fleetShown;
|
||||||
|
private bool _fleetBuilt;
|
||||||
private bool _updating;
|
private bool _updating;
|
||||||
|
|
||||||
public event Action<bool>? HeatMapToggled;
|
public event Action<bool>? HeatMapToggled;
|
||||||
@@ -69,6 +80,9 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
AddChild(_workshop);
|
AddChild(_workshop);
|
||||||
AddChild(_workshopDetails);
|
AddChild(_workshopDetails);
|
||||||
AddChild(_orderRow);
|
AddChild(_orderRow);
|
||||||
|
AddChild(PanelKit.Separator());
|
||||||
|
AddChild(UiTheme.Text(T("Rinnovo della flotta"), 14, bold: true));
|
||||||
|
AddChild(_fleet);
|
||||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
AddChild(_status);
|
AddChild(_status);
|
||||||
|
|
||||||
@@ -113,10 +127,26 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
|
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
|
||||||
}
|
}
|
||||||
var w = _session.World;
|
var w = _session.World;
|
||||||
|
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
||||||
|
_sinceFleet += delta;
|
||||||
|
long today = Fmt.Today(w);
|
||||||
|
if (today != _fleetDay || (w.Fleet is null && _sinceFleet > 5)) RequestFleet(today);
|
||||||
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
|
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Result(CommandResultMessage r) => _status.Text = r.Message;
|
private void RequestFleet(long day)
|
||||||
|
{
|
||||||
|
_fleetDay = day;
|
||||||
|
_sinceFleet = 0;
|
||||||
|
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Result(CommandResultMessage r)
|
||||||
|
{
|
||||||
|
_status.Text = r.Message;
|
||||||
|
// un rinnovo prenotato o completato cambia il quadro della flotta
|
||||||
|
RequestFleet(Fmt.Today(_session.World));
|
||||||
|
}
|
||||||
|
|
||||||
private void Refresh()
|
private void Refresh()
|
||||||
{
|
{
|
||||||
@@ -160,6 +190,7 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
|
|
||||||
BuildCard();
|
BuildCard();
|
||||||
BuildWorkshop();
|
BuildWorkshop();
|
||||||
|
if (!_fleetBuilt || !ReferenceEquals(w.Fleet, _fleetShown)) BuildFleet();
|
||||||
}
|
}
|
||||||
|
|
||||||
private string DueText(TrainInfo t)
|
private string DueText(TrainInfo t)
|
||||||
@@ -181,7 +212,10 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
_card.AddChild(UiTheme.TitleLabel(T("Cartella di manutenzione") + " · " + t.Name, 22));
|
_card.AddChild(UiTheme.TitleLabel(T("Cartella di manutenzione") + " · " + t.Name, 22));
|
||||||
var card = w.Cards.GetValueOrDefault(_train);
|
var card = w.Cards.GetValueOrDefault(_train);
|
||||||
var stats = PanelKit.Row();
|
var stats = PanelKit.Row();
|
||||||
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%")));
|
var condition = PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%"));
|
||||||
|
int trainId = _train;
|
||||||
|
WhyTooltip.Attach(condition, () => new ExplainTarget(ExplainSubject.TrainCondition, trainId));
|
||||||
|
stats.AddChild(condition);
|
||||||
stats.AddChild(PanelKit.Stat(T("Guasti nell'anno"), PanelKit.Value($"{card?.FailuresThisYear ?? 0}")));
|
stats.AddChild(PanelKit.Stat(T("Guasti nell'anno"), PanelKit.Value($"{card?.FailuresThisYear ?? 0}")));
|
||||||
stats.AddChild(PanelKit.Stat(T("Costi dell'anno"), PanelKit.Value((card?.CostThisYear ?? Money.Zero).ToString())));
|
stats.AddChild(PanelKit.Stat(T("Costi dell'anno"), PanelKit.Value((card?.CostThisYear ?? Money.Zero).ToString())));
|
||||||
_card.AddChild(stats);
|
_card.AddChild(stats);
|
||||||
@@ -212,6 +246,12 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
{
|
{
|
||||||
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||||
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
|
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
|
||||||
|
if (w.Fleet?.Vehicles.FirstOrDefault(f => f.Vehicle == v.Vehicle) is { } info)
|
||||||
|
{
|
||||||
|
var value = UiTheme.Text(VehicleOutlook(info), 12, info.Superseded ? Palette.Amber : Palette.TextSecondary);
|
||||||
|
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
_cardDetails.AddChild(value);
|
||||||
|
}
|
||||||
foreach (var c in v.Components)
|
foreach (var c in v.Components)
|
||||||
{
|
{
|
||||||
var row = PanelKit.Row(6);
|
var row = PanelKit.Row(6);
|
||||||
@@ -261,8 +301,98 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
actions.AddChild(b);
|
actions.AddChild(b);
|
||||||
}
|
}
|
||||||
_cardControls.AddChild(actions);
|
_cardControls.AddChild(actions);
|
||||||
|
// rinnovo: l'intervento con effetto «renew» dei dati, vende i veicoli superati e compra i successori
|
||||||
|
if (w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Effect == InterventionEffect.Renew) is { } renewal)
|
||||||
|
{
|
||||||
|
var renew = new Button { Text = renewal.NameIt };
|
||||||
|
renew.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), renewal.Id), Result);
|
||||||
|
_cardControls.AddChild(renew);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ rinnovo della flotta
|
||||||
|
|
||||||
|
/// <summary>Riga di obsolescenza di un veicolo: superato, successore con prestazioni e prezzo, valori, costo di manutenzione.</summary>
|
||||||
|
private string VehicleOutlook(FleetVehicleInfo v)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
if (v.Superseded)
|
||||||
|
{
|
||||||
|
parts.Add(string.Format(T("superato dal {0}"), v.SupersededYear));
|
||||||
|
var next = _session.World.Data.Vehicles.FirstOrDefault(d => d.Id == v.Successor);
|
||||||
|
if (next is not null)
|
||||||
|
parts.Add(string.Format(T("successore {0} ({1} kW, {2} km/h, {3})"), next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
||||||
|
}
|
||||||
|
if (!v.InProduction) parts.Add(T("fuori produzione"));
|
||||||
|
parts.Add(string.Format(T("valore {0}"), v.BookValue));
|
||||||
|
parts.Add(string.Format(T("rivendita {0}"), v.Resale));
|
||||||
|
if (v.MaintenanceFactor > 1.001f) parts.Add(string.Format(T("manutenzione ×{0:0.##}"), v.MaintenanceFactor));
|
||||||
|
return string.Join(" · ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BuildFleet()
|
||||||
|
{
|
||||||
|
foreach (var c in _fleet.GetChildren()) c.QueueFree();
|
||||||
|
var w = _session.World;
|
||||||
|
var report = w.Fleet;
|
||||||
|
_fleetShown = report;
|
||||||
|
_fleetBuilt = true;
|
||||||
|
if (report is null)
|
||||||
|
{
|
||||||
|
_fleet.AddChild(UiTheme.Text(T("Quadro della flotta in arrivo dal server…"), 13, Palette.TextSecondary));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_fleet.AddChild(PanelKit.Pair(T("Era"), PanelKit.Value(EraName(report.Era))));
|
||||||
|
if (report.NextEra.Length > 0)
|
||||||
|
_fleet.AddChild(PanelKit.Pair(T("Prossima era"), PanelKit.Value($"{EraName(report.NextEra)} · {report.NextEraYear}")));
|
||||||
|
_fleet.AddChild(PanelKit.Pair(T("Valore della flotta"), PanelKit.Value(report.BookValueTotal.ToString())));
|
||||||
|
var superseded = report.Vehicles.Where(v => v.Superseded).ToList();
|
||||||
|
if (superseded.Count == 0)
|
||||||
|
{
|
||||||
|
_fleet.AddChild(UiTheme.Text(T("Nessun veicolo superato"), 13, Palette.TextSecondary));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (var v in superseded.Take(8))
|
||||||
|
{
|
||||||
|
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
|
||||||
|
string where = v.Train >= 0 && w.Trains.TryGetValue(v.Train, out var t) ? t.Name
|
||||||
|
: v.Depot >= 0 && w.Depots.TryGetValue(v.Depot, out var d) ? d.Name : "";
|
||||||
|
_fleet.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {where} · {v.AgeYears:0.#}/{v.LifeYears} {T("anni")}", 13, bold: true));
|
||||||
|
var line = UiTheme.Text(VehicleOutlook(v), 12, Palette.Amber);
|
||||||
|
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
_fleet.AddChild(line);
|
||||||
|
}
|
||||||
|
if (superseded.Count > 8)
|
||||||
|
_fleet.AddChild(UiTheme.Text(string.Format(T("e altri {0} veicoli superati"), superseded.Count - 8), 12, Palette.TextSecondary));
|
||||||
|
foreach (var r in report.Trains)
|
||||||
|
{
|
||||||
|
string name = w.Trains.TryGetValue(r.Train, out var t) ? t.Name : $"#{r.Train}";
|
||||||
|
var row = PanelKit.Row(6);
|
||||||
|
var text = UiTheme.Text(string.Format(T("{0}: {1} veicoli da rinnovare, spesa netta {2}"), name, r.Vehicles, r.NetCost), 13,
|
||||||
|
r.Affordable ? Palette.Text : Palette.Danger);
|
||||||
|
text.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||||
|
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||||
|
row.AddChild(text);
|
||||||
|
if (r.Booked)
|
||||||
|
{
|
||||||
|
// rinnovo già prenotato: niente pulsante, ripremerlo rifarebbe la prenotazione
|
||||||
|
row.AddChild(UiTheme.Text(T("rinnovo prenotato"), 13, Palette.TextSecondary));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int train = r.Train;
|
||||||
|
string intervention = report.RenewalIntervention;
|
||||||
|
var button = new Button { Text = T("Rinnova") };
|
||||||
|
button.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
||||||
|
row.AddChild(button);
|
||||||
|
}
|
||||||
|
_fleet.AddChild(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Nome italiano dell'era dal suo id in eras.json (il quadro della flotta manda l'id).</summary>
|
||||||
|
private string EraName(string id) => _session.World.Data.Eras.Eras.FirstOrDefault(e => e.Id == id)?.NameIt ?? id;
|
||||||
|
|
||||||
// ------------------------------------------------------------------ registro officina
|
// ------------------------------------------------------------------ registro officina
|
||||||
|
|
||||||
private void BuildWorkshop()
|
private void BuildWorkshop()
|
||||||
@@ -279,6 +409,8 @@ public partial class MaintenancePanel : VBoxContainer
|
|||||||
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
|
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
|
||||||
_workshop.AddChild(stats);
|
_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.")));
|
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 is not null)
|
||||||
{
|
{
|
||||||
if (reg.WorkRate < 0.999f)
|
if (reg.WorkRate < 0.999f)
|
||||||
File renamed without changes.
@@ -0,0 +1,590 @@
|
|||||||
|
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;
|
||||||
|
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
||||||
|
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
||||||
|
|
||||||
|
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);
|
||||||
|
// tooltip «perché» del prezzo globale del bene scelto (ADR 0024)
|
||||||
|
WhyTooltip.Attach(_goodPrice, () => _selected >= 0 ? new ExplainTarget(ExplainSubject.GlobalPrice, _selected) : null);
|
||||||
|
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);
|
||||||
|
// prezzo locale dell'industria spiegato dal server; gli hub comprano al prezzo mondiale meno il dazio
|
||||||
|
if (p.Kind != SellPlaceInfo.Hub)
|
||||||
|
{
|
||||||
|
int good = g.Good, target = p.Target;
|
||||||
|
WhyTooltip.Attach(price, () => new ExplainTarget(ExplainSubject.LocalPrice, good, target));
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
// il suggerimento della riga sta sul nome e sulla linea, non sul riquadro: sul prezzo c'è il tooltip «perché»,
|
||||||
|
// e il suggerimento nativo di un antenato gli comparirebbe sopra
|
||||||
|
string tip = 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")}";
|
||||||
|
foreach (var l in new[] { label, line })
|
||||||
|
{
|
||||||
|
l.TooltipText = tip;
|
||||||
|
l.MouseFilter = MouseFilterEnum.Pass;
|
||||||
|
}
|
||||||
|
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.Progress(report.TradingProgress)}", 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using Godot;
|
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>
|
/// <summary>Mattoni comuni dei pannelli laterali.</summary>
|
||||||
public static class PanelKit
|
public static class PanelKit
|
||||||
File renamed without changes.
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
using Godot;
|
using Godot;
|
||||||
using ViaFerrea.Client.App;
|
using RailEnterprise.Client.App;
|
||||||
using ViaFerrea.Client.Map;
|
using RailEnterprise.Client.Map;
|
||||||
using ViaFerrea.Core.Rail;
|
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>
|
/// <summary>Grafico altimetrico del tracciato: terreno, quota del binario e opere colorate (pannello TrackProfile).</summary>
|
||||||
public partial class ProfileChart : Control
|
public partial class ProfileChart : Control
|
||||||
File renamed without changes.
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user