diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 041eea4f0..12c5c5866 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -32,13 +32,27 @@ jobs: # running is left to finish; with a build cancelled the publish job of that run is skipped. A push # to master gets a group of its own, its commit, so the builds of master are never cancelled. + # Windows is built twice: with AVX2 (the default of ENABLE_AVX2) and without it, for CPUs older + # than Haswell (2013). Each variant has its own concurrency group, or one would cancel the other. + windows: - name: Windows x64 / MSVC + name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 concurrency: - group: ${{ github.workflow }}-windows-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -112,11 +126,13 @@ jobs: $pythonRoot = Split-Path $pythonExe Write-Host "Python root: $pythonRoot" + Write-Host "Extra CMake flags: ${{ matrix.variant.cmake_flags }}" cmake -S . -B build ` -G "Visual Studio 17 2022" ` -A x64 ` - "-DPython3_ROOT_DIR=$pythonRoot" + "-DPython3_ROOT_DIR=$pythonRoot" ` + ${{ matrix.variant.cmake_flags }} - name: Build shell: pwsh @@ -164,10 +180,183 @@ jobs: -Recurse ` -Force + # The downloads of the next step, kept between the runs: a release or raw.githubusercontent.com out of reach then + # doesn't fail the build. The key is this file, which pins them; a cache of an older one is taken too, as the next + # step checks every file by its SHA-256 and downloads only those it doesn't have. + - name: Restore the audio library downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/audio-dlls-downloads + key: audio-dlls-${{ hashFiles('.github/workflows/build_bin.yml') }} + restore-keys: audio-dlls- + + # The game loads OpenAL32.dll and libsndfile-1.dll from its own folder, and the depot had OpenAL Soft 1.18.1 and + # libsndfile 1.0.28 (2017) there. OpenAL Soft 1.18 lacks ALC_SOFT_reopen_device and ALC_SOFT_system_events, so on + # Windows the sound didn't follow a change of the output device; libsndfile 1.0.28 reads no Opus and no MP3, which + # the Linux build (libsndfile 1.2) does. The official release binaries of both are taken, pinned by SHA-256. They + # need nothing beyond the system DLLs and msvcrt.dll (soft_oal.dll) or KERNEL32.dll (sndfile.dll). soft_oal.dll + # has no AVX code; sndfile.dll (its static opus and mpg123) picks its AVX/AVX2 paths at run time, so the same files + # go with both variants. The exe links them by name: soft_oal.dll is shipped as OpenAL32.dll (as its readme says, + # without the router), sndfile.dll as libsndfile-1.dll. Both are LGPL, so their license texts go with them, in + # licenses/, with those of what the DLLs have built in (below); the libsndfile zip has none, its COPYING is taken + # from the source tree of the same tag. + - name: Add the OpenAL Soft and libsndfile DLLs + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $output = "build/bin/$env:CONFIG_WIN" + $licenses = Join-Path $output 'licenses' + $work = Join-Path $env:RUNNER_TEMP 'audio-dlls' + $downloads = Join-Path $env:RUNNER_TEMP 'audio-dlls-downloads' + New-Item -ItemType Directory -Force -Path $work, $licenses, $downloads | Out-Null + $pinned = [System.Collections.Generic.List[string]]::new() + + # the file of the URL with the given SHA-256: the one kept by a run before, else downloaded. named by its + # SHA-256 and the last part of its path, without the query: several license texts are named the same + function Get-Pinned([string] $Url, [string] $Sha256) { + $name = "$Sha256-$([uri]::new($Url).Segments[-1])" + $pinned.Add($name) + $file = Join-Path $downloads $name + if ((Test-Path -Path $file) -and (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() -eq $Sha256) { + Write-Host "$Url kept by a run before" + return $file + } + # not a browser's user agent, which Debian's server answers with a challenge page + Invoke-WebRequest -Uri $Url -OutFile $file -UserAgent 'ci-download' -MaximumRetryCount 3 -RetryIntervalSec 10 -TimeoutSec 120 + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $Sha256) { + Remove-Item -Path $file -Force + throw "${Url}: SHA-256 $hash, expected $Sha256" + } + return $file + } + + # each package: the zip and, for each file wanted from it, where it goes in the build + $packages = @( + @{ Url = 'https://github.com/kcat/openal-soft/releases/download/1.25.2/openal-soft-1.25.2-bin.zip' + Sha256 = '67a0c4b800bd860c93c04f38caf8cbe4875f9c84700ac430efc451f70e265434' + Files = [ordered]@{ + 'openal-soft-1.25.2-bin/bin/Win64/soft_oal.dll' = 'OpenAL32.dll' + 'openal-soft-1.25.2-bin/COPYING' = 'licenses/openal-soft-COPYING.txt' } }, + @{ Url = 'https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2-win64.zip' + Sha256 = '2173935c0c1ed13cf627951d34483f9d405ead2eb473190461c42ba220643a3f' + Files = [ordered]@{ + 'libsndfile-1.2.2-win64/bin/sndfile.dll' = 'libsndfile-1.dll' } } + ) + foreach ($package in $packages) { + $zip = Get-Pinned $package.Url $package.Sha256 + $unpacked = Join-Path $work ([IO.Path]::GetFileNameWithoutExtension($zip)) + Expand-Archive -Path $zip -DestinationPath $unpacked -Force + foreach ($entry in $package.Files.GetEnumerator()) { + Copy-Item -Path (Join-Path $unpacked $entry.Key) -Destination (Join-Path $output $entry.Value) -Force + Write-Host "$($entry.Value) <- $($package.Url) $($entry.Key)" + } + } + + # the license texts, each from the source tree of the version built in: of libsndfile, its ALAC and GSM 06.10 + # code, and the libraries its vcpkg build linked into sndfile.dll; of OpenAL Soft's PFFFT, Microsoft GSL and + # its BSD 3-Clause parts, and of the MinGW-w64 runtime and winpthreads, linked into soft_oal.dll (a MinGW GCC + # 15 build: the texts are the same in mingw-w64 12 and 13). + # The versions in sndfile.dll: those it names (libopus 1.4, libFLAC 1.4.2, libVorbis 1.3.7), mpg123 1.31.3 by + # the SHA-512 of its source archive in the build paths it keeps, and libogg 1.3.5 and LAME 3.100 of the vcpkg + # ports of the time (mid 2023). LAME's from Debian's copy of the 3.100 source, the same file as in LAME's own + # repository on SourceForge, which may answer a script with a challenge page + $texts = [ordered]@{ + 'libsndfile-COPYING.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING' + 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140') + 'libsndfile-ALAC-LICENSE.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE' + '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9') + 'libsndfile-GSM610-COPYRIGHT.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT' + '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7') + 'libogg-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING' + 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814') + 'libvorbis-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING' + 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a') + 'flac-COPYING.Xiph.txt' = @('https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph' + '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d') + 'opus-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING' + '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682') + 'mpg123-COPYING.txt' = @('https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co' + 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366') + 'lame-COPYING.txt' = @('https://sources.debian.org/data/main/l/lame/3.100-6/COPYING' + 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd') + 'openal-soft-pffft-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft' + '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de') + 'openal-soft-gsl-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE' + '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555') + 'openal-soft-BSD-3Clause.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause' + 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff') + 'openal-soft-winpthreads-COPYING.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING' + '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177') + 'openal-soft-mingw-w64-runtime.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt' + 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd') + } + foreach ($text in $texts.GetEnumerator()) { + $file = Get-Pinned $text.Value[0] $text.Value[1] + Copy-Item -Path $file -Destination (Join-Path $licenses $text.Key) -Force + } + + # OpenAL Soft's bs2b has its license only in its source files: the notice as core/bs2b.cpp of 1.25.2 has it + @' + Copyright (c) 2005 Boris Mikhaylov + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + '@ | Set-Content -Path (Join-Path $licenses 'openal-soft-bs2b-LICENSE.txt') -Encoding utf8 + + # what the DLLs are and have built in, where their source is (the LGPL ones); the DLLs can be replaced by the user + @( + 'OpenAL32.dll: OpenAL Soft 1.25.2, unmodified soft_oal.dll of the official binaries, GNU LGPL 2 or later' + ' (openal-soft-COPYING.txt). Source: https://github.com/kcat/openal-soft/releases/tag/1.25.2' + ' Built in: a modified PFFFT, BSD-style (openal-soft-pffft-LICENSE.txt); Microsoft GSL, MIT' + ' (openal-soft-gsl-LICENSE.txt); the ambisonic rotator, the vocal morpher and the compressor, BSD 3-Clause' + ' (openal-soft-BSD-3Clause.txt); bs2b, MIT (openal-soft-bs2b-LICENSE.txt); {fmt} 11.2.0, MIT, whose' + ' exception for the object form asks for no text. Linked into it by its MinGW-w64 build: the MinGW-w64' + ' runtime (openal-soft-mingw-w64-runtime.txt) and winpthreads, MIT and BSD-style' + ' (openal-soft-winpthreads-COPYING.txt);' + ' libstdc++ and libgcc under the GCC Runtime Library Exception, which asks for no text.' + ' Its default HRTF data set is based on the KEMAR HRTF measurements by Bill Gardner and Keith Martin,' + ' MIT Media Laboratory, 1994: http://sound.media.mit.edu/resources/KEMAR.html' + 'libsndfile-1.dll: libsndfile 1.2.2, unmodified sndfile.dll of the official binaries, GNU LGPL 2.1 or later' + ' (libsndfile-COPYING.txt). Source: https://github.com/libsndfile/libsndfile/releases/tag/1.2.2' + ' Its ALAC code: Apache License 2.0 (libsndfile-ALAC-LICENSE.txt). Its GSM 06.10 code: Jutta Degener and' + ' Carsten Bormann, TU Berlin (libsndfile-GSM610-COPYRIGHT.txt). Its G.721/G.723 code: Sun Microsystems, public' + ' domain.' + ' Linked into it by its build, made with the vcpkg ports of the time and their patches' + ' (https://github.com/microsoft/vcpkg/tree/2023.08.09/ports, the ports named below):' + ' libogg 1.3.5, BSD (libogg-COPYING.txt), port libogg. Source: https://github.com/xiph/ogg/releases/tag/v1.3.5' + ' libvorbis 1.3.7, BSD (libvorbis-COPYING.txt), port libvorbis. Source: https://github.com/xiph/vorbis/releases/tag/v1.3.7' + ' libFLAC 1.4.2, BSD (flac-COPYING.Xiph.txt), port libflac. Source: https://github.com/xiph/flac/releases/tag/1.4.2' + ' libopus 1.4, BSD (opus-COPYING.txt), port opus. Source: https://github.com/xiph/opus/releases/tag/v1.4' + ' mpg123 1.31.3, GNU LGPL 2.1 (mpg123-COPYING.txt), port mpg123. Source: https://www.mpg123.de/download/mpg123-1.31.3.tar.bz2' + ' LAME 3.100, GNU LGPL 2 or later (lame-COPYING.txt), port mp3lame. Source: https://sourceforge.net/projects/lame/files/lame/3.100/' + ) | Set-Content -Path (Join-Path $licenses 'audio-libraries.txt') -Encoding utf8 + + # the files no pin names any more aren't kept for the next run + Get-ChildItem -Path $downloads -File | Where-Object { $pinned -notcontains $_.Name } | Remove-Item -Force + - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/bin/${{ env.CONFIG_WIN }}/ if-no-files-found: error @@ -176,7 +365,7 @@ jobs: - name: Upload Windows debug symbols uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-symbols-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/pdb/${{ env.CONFIG_WIN }}/*.pdb build/bin/${{ env.CONFIG_WIN }}/*.map @@ -189,13 +378,24 @@ jobs: # ============================================================ linux: - name: Linux x64 / GCC + name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 - # see the note above the windows job + # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: - group: ${{ github.workflow }}-linux-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -221,8 +421,13 @@ jobs: | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null sudo apt-get update + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. sudo apt-get install -y \ build-essential \ + libasound2-dev \ + libpulse-dev \ + libpipewire-0.3-dev \ libgl1-mesa-dev \ libglew-dev \ libglfw3-dev \ @@ -249,12 +454,17 @@ jobs: https://github.com/kcat/openal-soft.git \ /tmp/openal-soft + # the backends are loaded with dlopen at run time (ALSOFT_DLOPEN), so the bundled library needs none of them; + # REQUIRE makes a missing header fail the build instead of shipping a library without sound cmake \ -S /tmp/openal-soft \ -B /tmp/openal-soft/build \ -DCMAKE_BUILD_TYPE=Release \ -DALSOFT_EXAMPLES=OFF \ - -DALSOFT_UTILS=OFF + -DALSOFT_UTILS=OFF \ + -DALSOFT_REQUIRE_PIPEWIRE=ON \ + -DALSOFT_REQUIRE_PULSEAUDIO=ON \ + -DALSOFT_REQUIRE_ALSA=ON cmake \ --build /tmp/openal-soft/build \ @@ -282,6 +492,7 @@ jobs: -DWITH_ZMQ=OFF \ -DWITH_OPENVR=OFF \ -DUSE_LTO=OFF \ + ${{ matrix.variant.cmake_flags }} \ -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" @@ -347,7 +558,7 @@ jobs: - name: Upload Linux build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-linux-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_LINUX }} path: | build/bin/ if-no-files-found: error @@ -370,29 +581,47 @@ jobs: cancel-in-progress: false steps: - - name: Download Windows build + # the AVX2 build keeps the old name of the download, so the links already handed out still work + - name: Download Windows build (AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - - name: Download Linux build + - name: Download Windows build (no AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64-noavx2 + + - name: Download Linux build (AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 + - name: Download Linux build (no AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} + path: dist/maszyna-linux-x64-noavx2 + - name: Pack run: | cd dist - find maszyna-linux-x64 -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; - if [ -d maszyna-linux-x64/linuxpython64/bin ]; then - chmod +x maszyna-linux-x64/linuxpython64/bin/* - fi + # the artifacts lose the executable bit + for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; + if [ -d "$dir/linuxpython64/bin" ]; then + chmod +x "$dir"/linuxpython64/bin/* + fi + done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . ls -la - name: Publish rolling release of the branch @@ -412,14 +641,18 @@ jobs: "" \ "Download without a GitHub account:" \ "- Windows: $base/maszyna-windows-x64.zip" \ + "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ "- Linux: $base/maszyna-linux-x64.tar.gz" \ + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ dist/maszyna-windows-x64.zip \ + dist/maszyna-windows-x64-noavx2.zip \ dist/maszyna-linux-x64.tar.gz \ + dist/maszyna-linux-x64-noavx2.tar.gz \ --target "$SHA" \ --prerelease \ --latest=false \ @@ -428,4 +661,6 @@ jobs: echo "### Public download" >> "$GITHUB_STEP_SUMMARY" echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY" + echo "- Windows, no AVX2: $base/maszyna-windows-x64-noavx2.zip" >> "$GITHUB_STEP_SUMMARY" echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY" + echo "- Linux, no AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" >> "$GITHUB_STEP_SUMMARY" diff --git a/CMakeLists.txt b/CMakeLists.txt index d106d7ffb..5bd72dbbe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -481,6 +481,11 @@ if (ADD_VERSION_SUFFIX) set (SUFFIX "_${SRC_SHORT_DATE}_${GIT_HASH}") endif() +# a build without AVX2 says so in its name, so a starter can pick it on a CPU without AVX2 +if (NOT ENABLE_AVX2) + set (SUFFIX "${SUFFIX}_noavx2") +endif() + set(OPENVR_LIBRARY "openvr_api") set(OPENVR_INCLUDE_DIR "") @@ -557,7 +562,9 @@ set(CORE_SOURCES "simulation/simulationtestrules.cpp" "simulation/simulationsnapshot.cpp" "simulation/simulationsnapshotmover.cpp" +"vehicle/aiwire.cpp" "vehicle/blackbox.cpp" +"utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" "vehicle/drivingaid.cpp" diff --git a/EU07.cpp b/EU07.cpp index 20f24aa5a..a76564663 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,11 +22,17 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include #include #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -107,6 +113,8 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); + // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + PhysicsLogs.stop(); finish_log(); fflush(stdout); fflush(stderr); @@ -136,10 +144,29 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } +// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred +// of them they took all the files the C library of Windows lets a process have open by default (512): the files +// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h), +// but the limit is raised to the most either system allows still, for whatever else opens many files at once +void raise_open_files_limit() +{ +#ifdef _WIN32 + _setmaxstdio(8192); +#else + rlimit limit{}; + if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max) + { + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + } +#endif +} + } // namespace int main(int argc, char *argv[]) { + raise_open_files_limit(); #ifdef WITHDUMPGEN #ifdef _WIN32 SetUnhandledExceptionFilter(CrashHandler); @@ -215,6 +242,9 @@ int main(int argc, char *argv[]) MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); } #endif + // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // otherwise, and a second stop only writes what came since + PhysicsLogs.stop(); } #ifndef _WIN32 fflush(stdout); diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 175c5c38c..df86cd545 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -1526,8 +1526,6 @@ class TSt113 : public TH14K1 static double const BEP_K[/*?*/ /*-1..5*/ 5 - -1 + 1]; /// Lookup of bh_* function codes to handle position values. static double const pos_table[11]; // = {-1, 5, -1, 0, 2, 3, 4, 5, 0, 0, 1}; - /// Local control pressure (mirrors PP). - double CP = 0; public: /// Computes brake pipe flow for the St113 handle (with EP). diff --git a/application/application.cpp b/application/application.cpp index 7098e336a..20e489f5c 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -35,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include "version_info.h" #include "simulation/simulationtest.h" #include "simulation/simulationsnapshotworld.h" +#include "utilities/physicslog.h" #include #include #include @@ -393,10 +394,14 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize glfw!"); return result; } - if (needs_ogl() && (result = init_ogl()) != 0) + if (needs_ogl()) { - ErrorLog("Failed to initialize ogl!"); - return result; + result = init_ogl(); + if (result != 0) + { + ErrorLog("Failed to initialize ogl!"); + return result; + } } if (crashreport_is_pending() && false == Global.test.enabled) @@ -746,6 +751,9 @@ void eu07_application::exit() track_sleepers::stop_background(); step("the black box"); simulation::Blackbox.close(); + step("the physics logs"); + // what is kept of them, the black box's written last, waited for a second at most: the rest is dropped + PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) mode.reset(); @@ -1354,6 +1362,21 @@ int eu07_application::init_settings(int Argc, char *Argv[]) simulation::apply_test_mode_settings(); } + // a renderer this build doesn't have gets the full one: the starter writes the words of every build it knows + // ("vulkan" for the vulkan builds), and any word not known here used to start the legacy renderer. + // "simpleshader" and "off" of the older starters keep the legacy one they always had + auto const &renderer{Global.GfxRenderer}; + auto const known{renderer == "default" || renderer == "legacy" || renderer == "simple" || renderer == "null" || renderer == "simpleshader" || + renderer == "off" || (renderer == "experimental" && gfx_renderer_factory::get_instance()->has_backend(renderer))}; + if (false == known) + { + WriteLog("gfxrenderer \"" + renderer + "\" isn't in this build, the full renderer is used instead"); + Global.GfxRenderer = "default"; + Global.NvRenderer = false; + Global.LegacyRenderer = false; + Global.BasicRenderer = false; + } + return 0; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 015b574e6..124e3fef8 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -41,6 +41,10 @@ http://mozilla.org/MPL/2.0/. #endif #include +#include +#include + +#include "audio/audiorenderer.h" namespace { @@ -1720,6 +1724,81 @@ bool debug_panel::render_section_developer() const return true; } +namespace { + +// a combo choosing one of the names, the first entry standing for the library's own choice. the names are asked for +// each time the list opens, as devices come and go. returns: true if the choice changed +template +bool name_combo( char const *Label, std::string &Value, Names_ const &Names, char const *Defaultlabel, std::string_view const Defaultvalue ) { + + auto const preview { Value == Defaultvalue ? std::string{ Defaultlabel } : Value }; + if( false == ImGui::BeginCombo( Label, preview.c_str() ) ) { return false; } + + static std::vector names; // one list per call site, as each passes its own lambda + if( ImGui::IsWindowAppearing() ) { + names = Names(); + } + auto changed { false }; + if( ImGui::Selectable( Defaultlabel, Value == Defaultvalue ) ) { + Value = Defaultvalue; + changed = true; + } + for( auto const &name : names ) { + if( ImGui::Selectable( name.c_str(), name == Value ) ) { + Value = name; + changed = true; + } + } + ImGui::EndCombo(); + return changed; +} + +// options of the audio device, applied by reopening it: output device, output mode, HRTF, limiter, mixing rate, sources +void render_audio_device_settings() { + + auto changed { false }; + changed |= name_combo( "Output device###audiodevice", Global.AudioRenderer, + [] { return audio::renderer.output_devices(); }, "System default", "" ); + changed |= name_combo( "Output mode###audiooutputmode", Global.AudioOutputMode, + [] { return std::vector{ "mono", "stereo", "stereo-basic", "uhj", "headphones", "quad", "5.1", "6.1", "7.1" }; }, + "Automatic", "auto" ); + changed |= name_combo( "HRTF###audiohrtf", Global.AudioHrtf, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + changed |= name_combo( "HRTF data set###audiohrtfprofile", Global.AudioHrtfProfile, + [] { return audio::renderer.hrtf_profiles(); }, "Library's choice", "" ); + changed |= name_combo( "Limiter###audiolimiter", Global.AudioLimiter, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + + auto frequency { Global.AudioFrequency > 0 ? std::to_string( Global.AudioFrequency ) : std::string{} }; + if( name_combo( "Mixing rate###audiofrequency", frequency, + [] { return std::vector{ "22050", "32000", "44100", "48000", "96000" }; }, "Device's", "" ) ) { + Global.AudioFrequency = ( frequency.empty() ? 0 : std::stoi( frequency ) ); + changed = true; + } + + if( changed ) { + audio::renderer.apply_device_settings(); + } +} + +// options of the sources, applied to the playing ones right away: resampler, Doppler effect, EFX +void render_audio_source_settings() { + + auto changed { false }; + changed |= name_combo( "Resampler###audioresampler", Global.AudioResampler, + [] { return audio::renderer.resamplers(); }, "Library's default", "" ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioDoppler, 2 ) + "###audiodoppler" ).c_str(), &Global.AudioDoppler, 0.0f, 1.0f, "Doppler effect" ); + changed |= ImGui::Checkbox( "Soundproofing muffles high frequencies###audiolowpass", &Global.AudioLowpass ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioAirAbsorption, 1 ) + "###audioairabsorption" ).c_str(), &Global.AudioAirAbsorption, 0.0f, 10.0f, "Air absorption" ); + + if( changed ) { + audio::renderer.apply_source_settings(); + } + ImGui::TextWrapped( "%s", audio::renderer.device_status().c_str() ); +} + +} // namespace + bool debug_panel::render_section_settings() const { @@ -1767,6 +1846,10 @@ debug_panel::render_section_settings() const { commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } + if( Global.bSoundEnabled ) { + render_audio_device_settings(); + render_audio_source_settings(); + } return true; } diff --git a/application/editormode.cpp b/application/editormode.cpp index e08e1f0e7..ab150cb7b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -1398,6 +1398,7 @@ bool editor_mode::update() Global.editor_tracks = (current_work_area() == work_area::tracks); selftest_step(); steps.step("selftest"); + thumbnails_trim(); // the drives of the switches go to the tips of their blades once, as the templates of the scenery are known if (false == m_drives_checked) { diff --git a/application/editormode.h b/application/editormode.h index bcf22592c..81347c950 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -745,13 +745,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri char filter[64]{}; float size{96.f}; // of the images, pixels std::string selected; - std::map thumbnails; // texture shown for the item of the name, 0: none + struct thumbnail + { + int texture{0}; // 0: none + int material{0}; // the material the texture is the first of, 0: a texture alone + double shown{0.0}; // when it was last asked for, ImGui time + }; + std::map thumbnails; // texture shown for the item of the name + bool refresh{false}; // all the images to be let go of and read again int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor int loadsframe{-1}; } m_textures; void render_texture_browser(); // texture of the image of the item of the browser, 0 while there's none std::uint64_t texture_thumbnail(texture_browser::item const &Item); + // the textures of the images out of sight for a while taken out of the memory: a picker of thousands of them scrolled + // through would keep them all, full size, until the memory ran out + void thumbnails_trim(); // takes a material dragged from the texture browser onto the item drawn last. returns: true if one was dropped, its name in Name static bool material_drop(std::string &Name); // the same, for a text field diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index 155210a87..e3423de5e 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -93,25 +93,53 @@ std::uint64_t editor_mode::texture_thumbnail(texture_browser::item const &Item) if (browser.loads >= 2) return 0; ++browser.loads; - texture_handle texture{null_handle}; + texture_browser::thumbnail thumbnail; if (Item.material) { - auto const material{GfxRenderer->Fetch_Material(Item.name)}; - if (auto const *data{GfxRenderer->Material(material)}; material != null_handle && data != nullptr) - texture = data->GetTexture(0); + // a material reads all its textures, the normal maps and the rest with the one shown + thumbnail.material = GfxRenderer->Fetch_Material(Item.name); + if (auto const *data{GfxRenderer->Material(thumbnail.material)}; thumbnail.material != null_handle && data != nullptr) + thumbnail.texture = data->GetTexture(0); } else - texture = GfxRenderer->Fetch_Texture(Item.name, true); - lookup = browser.thumbnails.emplace(Item.name, texture).first; + thumbnail.texture = GfxRenderer->Fetch_Texture(Item.name, true); + lookup = browser.thumbnails.emplace(Item.name, thumbnail).first; } - if (lookup->second == null_handle) + lookup->second.shown = ImGui::GetTime(); + if (lookup->second.texture == null_handle) return 0; - auto &texture{GfxRenderer->Texture(lookup->second)}; + auto &texture{GfxRenderer->Texture(lookup->second.texture)}; if (false == texture.get_is_ready()) texture.create(); return texture.get_is_ready() ? static_cast(texture.get_id()) : 0; } +void editor_mode::thumbnails_trim() +{ + // a few seconds out of sight, so scrolling back and forth doesn't read them over and over + // all of them after the browser's Refresh, here before any image is drawn: not while the panels drawn earlier in the + // frame still refer to them + auto constexpr kept{3.0}; + auto const now{ImGui::GetTime()}; + auto &browser{m_textures}; + for (auto entry{browser.thumbnails.begin()}; entry != browser.thumbnails.end();) + { + auto const &thumbnail{entry->second}; + if (false == browser.refresh && ((thumbnail.texture == null_handle && thumbnail.material == null_handle) || now - thumbnail.shown < kept)) + { + ++entry; + continue; + } + // the scene's own textures stay; shown again, the image is read anew within the few a frame + if (thumbnail.material != null_handle) + GfxRenderer->Unload_Material(thumbnail.material); + else + GfxRenderer->Unload_Texture(thumbnail.texture); + entry = browser.thumbnails.erase(entry); + } + browser.refresh = false; +} + void editor_mode::render_texture_browser() { auto &browser{m_textures}; @@ -173,7 +201,8 @@ void editor_mode::render_texture_browser() if (ImGui::Button(STR_C("Refresh"))) { browser.listed = false; - browser.thumbnails.clear(); + // the images let go of at the start of the next frame, see thumbnails_trim() + browser.refresh = true; } ImGui::SameLine(); ImGui::TextUnformatted((std::string{paths::textures} + browser.folder).c_str()); diff --git a/application/editormodetrackprops.cpp b/application/editormodetrackprops.cpp index 13a9d2a49..4542d0225 100644 --- a/application/editormodetrackprops.cpp +++ b/application/editormodetrackprops.cpp @@ -1043,8 +1043,10 @@ void editor_mode::textures_index() { if (entry->is_directory(ignored)) { - // the normal maps go with their textures, not on a track by themselves - if (lowered(entry->path().filename().string()) == "normals") + // the normal maps go with their textures, not on a track by themselves; the previews of the node bank, thousands of + // them, are images of models and not textures of anything + auto const folder{lowered(entry->path().filename().string())}; + if (folder == "normals" || (folder == "previews" && entry.depth() == 0)) entry.disable_recursion_pending(); continue; } diff --git a/audio/audio.cpp b/audio/audio.cpp index 3be2810d1..cd053f682 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -35,7 +35,8 @@ decoded_sound decode_sound( std::string const &File ) { SF_INFO si; si.format = 0; - SNDFILE *sf = sf_open(File.c_str(), SFM_READ, &si); + // the file as it's named on the disk, the name of the buffer is in lowercase + SNDFILE *sf = sf_open(FileOnDisk(File).c_str(), SFM_READ, &si); if (sf == nullptr) throw std::runtime_error("sound: sf_open failed"); @@ -216,9 +217,9 @@ openal_buffer::fetch_caption() { std::string captionfilename { name }; captionfilename.erase( captionfilename.rfind( '.' ) ); // obcięcie rozszerzenia captionfilename += "-" + Global.asLang + ".txt"; // już może być w różnych językach - if( true == FileExists( captionfilename ) ) { + if( auto const casedfilename { FileCased( captionfilename ) }; false == casedfilename.empty() ) { // wczytanie - std::ifstream inputfile( captionfilename ); + std::ifstream inputfile( casedfilename ); caption.assign( std::istreambuf_iterator( inputfile ), std::istreambuf_iterator() ); } } @@ -391,7 +392,7 @@ buffer_manager::find_file( std::string const &Filename ) const { auto const lookup { FileExists( { Filename }, - { ".ogg", ".flac", ".wav" } ) }; + { ".ogg", ".flac", ".wav", ".opus", ".mp3" } ) }; return lookup.first + lookup.second; } diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 080ab66f3..7950fca56 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -14,14 +14,102 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "vehicle/Camera.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "simulation/simulation.h" #include "vehicle/Train.h" +#include +#include +#include +#include + namespace audio { openal_renderer renderer; bool event_volume_change { false }; +namespace { + +struct named_value { + std::string_view name; + ALCint value; +}; + +// values of sound.outputmode, as ALC_OUTPUT_MODE_SOFT takes them +constexpr std::array output_modes { + named_value{ "mono", ALC_MONO_SOFT }, + named_value{ "stereo", ALC_STEREO_SOFT }, + named_value{ "stereo-basic", ALC_STEREO_BASIC_SOFT }, + named_value{ "uhj", ALC_STEREO_UHJ_SOFT }, + named_value{ "headphones", ALC_STEREO_HRTF_SOFT }, + named_value{ "quad", ALC_QUAD_SOFT }, + named_value{ "5.1", ALC_SURROUND_5_1_SOFT }, + named_value{ "6.1", ALC_SURROUND_6_1_SOFT }, + named_value{ "7.1", ALC_SURROUND_7_1_SOFT } }; + +// returns: ALC_OUTPUT_MODE_SOFT value for given sound.outputmode, or nothing for auto +std::optional output_mode_value( std::string_view const Name ) { + + if( Name == "auto" ) { return std::nullopt; } + if( auto const lookup { std::ranges::find( output_modes, Name, &named_value::name ) }; lookup != std::end( output_modes ) ) { + return lookup->value; + } + WriteLog( std::format( "sound: unknown output mode \"{}\", left to the library", Name ) ); + return std::nullopt; +} + +// returns: name of given ALC_OUTPUT_MODE_SOFT value +std::string_view output_mode_name( ALCint const Value ) { + + if( auto const lookup { std::ranges::find( output_modes, Value, &named_value::value ) }; lookup != std::end( output_modes ) ) { + return lookup->name; + } + return "other"; +} + +// returns: ALC_TRUE or ALC_FALSE for given on/off option, or nothing for auto +std::optional switch_value( std::string_view const Name ) { + + if( Name == "on" ) { return ALC_TRUE; } + if( Name == "off" ) { return ALC_FALSE; } + return std::nullopt; +} + +// opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini +// in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged +// say, leaves the default one rather than no sound at all. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device() { + + if( Global.AudioRenderer.empty() ) { + return ::alcOpenDevice( nullptr ); + } + if( auto *device { ::alcOpenDevice( Global.AudioRenderer.c_str() ) } ) { + return device; + } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + if( auto *device { ::alcOpenDevice( utf8name.c_str() ) } ) { + Global.AudioRenderer = utf8name; + return device; + } + } + ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) ); + Global.AudioRenderer.clear(); + return ::alcOpenDevice( nullptr ); +} + +// splits a list of null-terminated names ending with an empty name, as alcGetString gives device lists +std::vector split_name_list( ALCchar const *List ) { + + std::vector names; + while( List != nullptr && *List != '\0' ) { + auto const &name { names.emplace_back( List ) }; + List += name.size() + 1; + } + return names; +} + +} // namespace + float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin float const EU07_SOUND_VELOCITYLIMIT { 250 / 3.6f }; // 343 m/sec ~= speed of sound; arbitrary limit of 250 km/h @@ -178,6 +266,7 @@ openal_source::sync_with( sound_properties const &State ) { sound_range : 5 ) }; // range of -1 means sound of unlimited range, positioned at the listener ::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) * State.soundproofing ); + renderer.soundproofing_filter( id, State.soundproofing_hf ); } if( sound_range != -1 ) { auto const rangesquared { sound_range * sound_range }; @@ -274,6 +363,8 @@ openal_renderer::~openal_renderer() { if( m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( nullptr, nullptr ); } // stop callbacks before teardown + if( m_lowpassfilter != 0 ) { m_alDeleteFilters( 1, &m_lowpassfilter ); } + ::alcMakeContextCurrent( nullptr ); if( m_context != nullptr ) { ::alcDestroyContext( m_context ); } @@ -325,7 +416,9 @@ openal_renderer::init() { return false; } ::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED ); - ::alDopplerFactor( 0.25f ); + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + WriteLog( "sound: " + device_status() ); // all done m_ready = true; return true; @@ -400,8 +493,9 @@ openal_renderer::update( double const Deltatime ) { // event-driven: the callback (any thread) flags default-output / device-removal changes needsreopen = m_outputchanged.exchange( false ); } - else if( m_candetectdisconnect ) { - // fallback without ALC_SOFT_system_events: poll for a hard disconnect at ~1 Hz + if( false == needsreopen && m_candetectdisconnect ) { + // poll for a hard disconnect at ~1 Hz: the fallback without ALC_SOFT_system_events, and a safety net + // with it, as not every backend reports the removal of a device m_devicechecktime += Deltatime; if( m_devicechecktime >= 1.0 ) { m_devicechecktime = 0.0; @@ -411,12 +505,15 @@ openal_renderer::update( double const Deltatime ) { } } if( needsreopen ) { - if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes ) == ALC_TRUE ) { + if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes.data() ) == ALC_TRUE ) { auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) }; WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" ); + m_reopenfailed = false; } - else { + else if( false == m_reopenfailed ) { + // with no output left the poll retries each second; the log gets it once ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" ); + m_reopenfailed = true; } } } @@ -562,6 +659,7 @@ openal_renderer::fetch_source() { glm::vec3 zero_pos{ 0.f, 0.f, 0.f }; ::alSourcefv( newsource.id, AL_POSITION, glm::value_ptr( zero_pos ) ); ::alSourcefv( newsource.id, AL_VELOCITY, glm::value_ptr( zero_pos ) ); + configure_source( newsource.id ); } return newsource; @@ -583,7 +681,7 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = ::alcOpenDevice( Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() ); + m_device = open_output_device(); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -604,10 +702,16 @@ openal_renderer::init_caps() { WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } ); - ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds - std::copy( std::begin( attr ), std::end( attr ), std::begin( m_contextattributes ) ); // cached for device reopen + // the device options (output mode, HRTF and the like) are known once the device is open + m_hasoutputmode = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_mode" ) == ALC_TRUE ); + m_haslimiter = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_limiter" ) == ALC_TRUE ); + if( alcIsExtensionPresent( m_device, "ALC_SOFT_HRTF" ) == ALC_TRUE ) { + m_alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress( m_device, "alcGetStringiSOFT" ); + m_alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress( m_device, "alcResetDeviceSOFT" ); + } + m_contextattributes = device_attributes(); // cached for device reopen - m_context = ::alcCreateContext( m_device, attr ); + m_context = ::alcCreateContext( m_device, m_contextattributes.data() ); if( m_context == nullptr ) { ErrorLog( "Failed to create audio context" ); return false; @@ -664,7 +768,245 @@ openal_renderer::init_caps() { } } + init_extensions(); + return true; } +// resolves the entry points of the context extensions the settings use: source resampler, EFX filters +void +openal_renderer::init_extensions() { + + if( alIsExtensionPresent( "AL_SOFT_source_resampler" ) == AL_TRUE ) { + m_alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress( "alGetStringiSOFT" ); + } + if( alcIsExtensionPresent( m_device, "ALC_EXT_EFX" ) == ALC_TRUE ) { + m_alGenFilters = (LPALGENFILTERS)alGetProcAddress( "alGenFilters" ); + m_alDeleteFilters = (LPALDELETEFILTERS)alGetProcAddress( "alDeleteFilters" ); + m_alFilteri = (LPALFILTERI)alGetProcAddress( "alFilteri" ); + m_alFilterf = (LPALFILTERF)alGetProcAddress( "alFilterf" ); + m_hasefx = ( m_alGenFilters != nullptr && m_alDeleteFilters != nullptr && m_alFilteri != nullptr && m_alFilterf != nullptr ); + } + if( false == m_hasefx ) { + return; + } + ::alGetError(); + m_alGenFilters( 1, &m_lowpassfilter ); + m_alFilteri( m_lowpassfilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS ); + if( ::alGetError() != AL_NO_ERROR ) { + WriteLog( "sound: warning: EFX low-pass filter not available" ); + m_lowpassfilter = 0; + } +} + +// returns: attributes of the device and the context made from the settings. with the defaults they are as before the +// settings existed, which leaves output mode, HRTF, limiter and mixing rate to the library +std::vector +openal_renderer::device_attributes() const { + + // sound.maxsources, kept for an OpenAL other than OpenAL Soft: that one gives at least 256 sources whatever is asked + std::vector attributes { ALC_MONO_SOURCES, Global.audio_max_sources }; + auto const add { [ &attributes ]( ALCint const Key, ALCint const Value ) { + attributes.push_back( Key ); + attributes.push_back( Value ); } }; + + if( auto const mode { output_mode_value( Global.AudioOutputMode ) }; mode && m_hasoutputmode ) { + add( ALC_OUTPUT_MODE_SOFT, *mode ); + } + if( m_alcGetStringiSOFT != nullptr ) { + if( auto const hrtf { switch_value( Global.AudioHrtf ) } ) { + add( ALC_HRTF_SOFT, *hrtf ); + } + if( auto const index { hrtf_index( Global.AudioHrtfProfile ) }; index >= 0 ) { + add( ALC_HRTF_ID_SOFT, index ); + } + } + if( auto const limiter { switch_value( Global.AudioLimiter ) }; limiter && m_haslimiter ) { + add( ALC_OUTPUT_LIMITER_SOFT, *limiter ); + } + if( Global.AudioFrequency > 0 ) { + add( ALC_FREQUENCY, Global.AudioFrequency ); + } + attributes.push_back( 0 ); + return attributes; +} + +// returns: index of the named HRTF data set, or -1 if the name is empty or unknown +int +openal_renderer::hrtf_index( std::string const &Name ) const { + + if( Name.empty() ) { return -1; } + auto const profiles { hrtf_profiles() }; + if( auto const lookup { std::ranges::find( profiles, Name ) }; lookup != std::end( profiles ) ) { + return static_cast( std::distance( std::begin( profiles ), lookup ) ); + } + WriteLog( std::format( "sound: unknown HRTF data set \"{}\", left to the library", Name ) ); + return -1; +} + +// returns: index of the resampler of the settings, the library's default with none set, or -1 without the extension +ALint +openal_renderer::resampler_index() const { + + if( m_alGetStringiSOFT == nullptr ) { return -1; } + if( false == Global.AudioResampler.empty() ) { + auto const names { resamplers() }; + if( auto const lookup { std::ranges::find( names, Global.AudioResampler ) }; lookup != std::end( names ) ) { + return static_cast( std::distance( std::begin( names ), lookup ) ); + } + WriteLog( std::format( "sound: unknown resampler \"{}\", the library's default used", Global.AudioResampler ) ); + } + return ::alGetInteger( AL_DEFAULT_RESAMPLER_SOFT ); +} + +// sets the options of the settings on a source +void +openal_renderer::configure_source( ALuint const Source ) const { + + if( m_resampler >= 0 ) { + ::alSourcei( Source, AL_SOURCE_RESAMPLER_SOFT, m_resampler ); + } + if( m_hasefx ) { + ::alSourcef( Source, AL_AIR_ABSORPTION_FACTOR, Global.AudioAirAbsorption ); + } +} + +// sets the EFX low-pass filter of a source for given soundproofing: the stronger the soundproofing, the more muffled +void +openal_renderer::soundproofing_filter( ALuint const Source, float const Soundproofing ) const { + + if( m_lowpassfilter == 0 ) { return; } + // a soundproofing left undefined by the data (-1, which OpenAL doesn't take as the gain either) isn't muffled + if( false == Global.AudioLowpass || Soundproofing < 0.f || Soundproofing >= 1.f ) { + ::alSourcei( Source, AL_DIRECT_FILTER, AL_FILTER_NULL ); + return; + } + // the level is set by the gain already, the filter takes away only the high frequencies + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAIN, 1.f ); + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAINHF, std::clamp( Soundproofing, 0.f, 1.f ) ); + ::alSourcei( Source, AL_DIRECT_FILTER, static_cast( m_lowpassfilter ) ); +} + +// returns: names of the output devices +std::vector +openal_renderer::output_devices() const { + + if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ) { + return split_name_list( ::alcGetString( nullptr, ALC_ALL_DEVICES_SPECIFIER ) ); + } + return split_name_list( ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) ); +} + +// returns: names of the HRTF data sets of the device +std::vector +openal_renderer::hrtf_profiles() const { + + std::vector names; + if( m_device == nullptr || m_alcGetStringiSOFT == nullptr ) { return names; } + ALCint count { 0 }; + ::alcGetIntegerv( m_device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &count ); + for( ALCint index = 0; index < count; ++index ) { + auto const *name { m_alcGetStringiSOFT( m_device, ALC_HRTF_SPECIFIER_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: names of the resamplers +std::vector +openal_renderer::resamplers() const { + + std::vector names; + if( m_alGetStringiSOFT == nullptr ) { return names; } + auto const count { ::alGetInteger( AL_NUM_RESAMPLERS_SOFT ) }; + for( ALint index = 0; index < count; ++index ) { + auto const *name { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: what the device ended up with +std::string +openal_renderer::device_status() const { + + if( m_device == nullptr ) { return "no audio device"; } + + auto const namequery { ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ? ALC_ALL_DEVICES_SPECIFIER : ALC_DEVICE_SPECIFIER }; + auto const *devicename { ::alcGetString( m_device, namequery ) }; + ALCint frequency { 0 }; + ::alcGetIntegerv( m_device, ALC_FREQUENCY, 1, &frequency ); + auto status { std::format( "device \"{}\", {} Hz", devicename != nullptr ? devicename : "?", frequency ) }; + + if( m_hasoutputmode ) { + ALCint mode { 0 }; + ::alcGetIntegerv( m_device, ALC_OUTPUT_MODE_SOFT, 1, &mode ); + status += std::format( ", output {}", output_mode_name( mode ) ); + } + if( m_alcGetStringiSOFT != nullptr ) { + ALCint hrtf { ALC_FALSE }; + ::alcGetIntegerv( m_device, ALC_HRTF_SOFT, 1, &hrtf ); + if( hrtf == ALC_TRUE ) { + auto const *hrtfname { ::alcGetString( m_device, ALC_HRTF_SPECIFIER_SOFT ) }; + status += std::format( ", HRTF \"{}\"", hrtfname != nullptr ? hrtfname : "?" ); + } + else { + status += ", HRTF off"; + } + } + if( m_resampler >= 0 ) { + auto const *resamplername { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, m_resampler ) }; + status += std::format( ", resampler {}", resamplername != nullptr ? resamplername : "?" ); + } + if( m_lowpassfilter != 0 ) { + status += ", EFX"; + } + return status; +} + +// applies changed device options without a restart: reopens the device, or resets it with an older library +bool +openal_renderer::apply_device_settings() { + + if( false == m_ready ) { return false; } + + m_contextattributes = device_attributes(); + auto applied { false }; + if( m_alcReopenDeviceSOFT != nullptr ) { + auto const *devicename { Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() }; + applied = ( m_alcReopenDeviceSOFT( m_device, devicename, m_contextattributes.data() ) == ALC_TRUE ); + } + else if( m_alcResetDeviceSOFT != nullptr ) { + // without ALC_SOFT_reopen_device another output device takes a restart + applied = ( m_alcResetDeviceSOFT( m_device, m_contextattributes.data() ) == ALC_TRUE ); + if( applied ) { + WriteLog( "sound: this audio library can't switch the output device while running, a changed device takes a restart" ); + } + } + if( applied ) { + WriteLog( "sound: audio settings applied, " + device_status() ); + } + else { + ErrorLog( "sound: the audio device settings take a restart to apply" ); + } + return applied; +} + +// applies changed source options to every source; spare sources get them when taken +void +openal_renderer::apply_source_settings() { + + if( false == m_ready ) { return; } + + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + for( auto const &source : m_sources ) { + if( source.id != audio::null_resource ) { + configure_source( source.id ); + } + } + // the filters follow with the gain, which this flag makes every source set anew + audio::event_volume_change = true; +} + } // audio \ No newline at end of file diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 3f462eb49..86ea89cd8 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -48,6 +48,9 @@ struct sound_properties { sound_category category { sound_category::unknown }; float gain { 1.f }; float soundproofing { 1.f }; + // the soundproofing of what stands between the sound and the listener, without the volume trim of the sounds placed + // on top of the listener: what the low-pass filter muffles the sound by (sound.efx.lowpass) + float soundproofing_hf { 1.f }; std::uintptr_t soundproofing_stamp { ~std::uintptr_t{0} }; }; @@ -122,6 +125,20 @@ public: void erase( sound_source const *Controller ); void update( double const Deltatime ); + // choices the library offers, for the settings + std::vector output_devices() const; + std::vector hrtf_profiles() const; + std::vector resamplers() const; + // what the device ended up with: device, mixing rate, output mode, HRTF, resampler + std::string device_status() const; + // applies changed device options (sound.openal.renderer, outputmode, hrtf, limiter, frequency) + // without a restart. returns: false if the library can't do it + bool apply_device_settings(); + // applies changed source options (sound.resampler, doppler, efx.*) to every source + void apply_source_settings(); + // sets the EFX low-pass filter of a source for given soundproofing (sound.efx.lowpass) + void soundproofing_filter( ALuint const Source, float const Soundproofing ) const; + glm::dvec3 cached_camerapos; private: @@ -129,6 +146,11 @@ private: using source_sequence = std::stack; bool init_caps(); + void init_extensions(); + std::vector device_attributes() const; + int hrtf_index( std::string const &Name ) const; + ALint resampler_index() const; + void configure_source( ALuint const Source ) const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -149,10 +171,24 @@ private: LPALCDEVICEPAUSESOFT m_alcDevicePauseSOFT { nullptr }; LPALCDEVICERESUMESOFT m_alcDeviceResumeSOFT { nullptr }; LPALCREOPENDEVICESOFT m_alcReopenDeviceSOFT { nullptr }; + LPALCRESETDEVICESOFT m_alcResetDeviceSOFT { nullptr }; + LPALCGETSTRINGISOFT m_alcGetStringiSOFT { nullptr }; + LPALGETSTRINGISOFT m_alGetStringiSOFT { nullptr }; + LPALGENFILTERS m_alGenFilters { nullptr }; + LPALDELETEFILTERS m_alDeleteFilters { nullptr }; + LPALFILTERI m_alFilteri { nullptr }; + LPALFILTERF m_alFilterf { nullptr }; + + bool m_hasoutputmode { false }; // ALC_SOFT_output_mode + bool m_haslimiter { false }; // ALC_SOFT_output_limiter + bool m_hasefx { false }; // ALC_EXT_EFX, with its filter entry points + ALuint m_lowpassfilter { 0 }; // shared low-pass filter, its parameters are copied to a source when attached + ALint m_resampler { -1 }; // index of the resampler set on the sources, or -1 to leave the library's default bool m_candetectdisconnect { false }; - ALCint m_contextattributes[3] { 0, 0, 0 }; + std::vector m_contextattributes; // cached for device reopen double m_devicechecktime { 0.0 }; + bool m_reopenfailed { false }; // a failed reopen is retried each second, but logged once // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. // Preferred over polling because it reliably catches both device removal and default changes diff --git a/audio/sound.cpp b/audio/sound.cpp index 785b976f5..b981479cc 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -998,6 +998,8 @@ sound_source::update_soundproofing() { occupiedcab ); } } + // the walls muffle the sound, the trim below only lowers its volume + m_properties.soundproofing_hf = m_properties.soundproofing; // for ambient sounds reduce their volume to account for their placement right on top of the listener if( m_range < -1 ) { m_properties.soundproofing *= 0.4f; diff --git a/blackbox_doc.md b/blackbox_doc.md index ab330dc2e..126cea033 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -7,14 +7,42 @@ done at the same moment, every command the user gave, when the autopilot took ov the timetable and how the train kept to it at each station, and where it was told to sound the horn. From it another program (the starter, a viewer) can replay the session on the map, or set the user's driving against the AI's. -It is written along with the physics logs: `physicslog yes` in `eu07.ini`, not in an editor session. -`blackbox no` turns it off while the physics logs are kept (it is on by default). The file goes next to -them, `physicslog/_.blackbox` (the local time the recording started at). -The `.dat` logs stay as they are. +`blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no +`blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. +The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are +hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail +vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +editor session. The file goes to `physicslog/_.blackbox` (the local time the +recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. + +With the physics logs off it still gives the `.dat` log of each vehicle the user was in, as it goes: +`physicslog/.dat`, the same file name, the same columns and the same line every 0.05 s as +`physicslog yes` would write. In the name of a file, of these logs and of those of `physicslog yes`, the +characters no file name may have on Windows, `< > : " / \ | ? *` and the control characters, are `_`, on +every system: a spawned vehicle, named `:`, has its log as `_.dat`. A name +Windows keeps for a device (`con`, `nul`, `com1` and the like) gets a `_` before it. A log is the driver's, named after the vehicle that driver began in: it +begins the first time the user is with that driver, and goes on while the user looks around outside, or +moves to another cab of the unit or another vehicle of the same train. Taking a vehicle of another driver +goes on in that driver's log, begun then if it is the first time. Back with a driver, the log goes on after +the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of +the driver of its train. So the speed recorder's tape can be read from them as before, also while the +simulator runs, without a log of every vehicle. A driver who writes a log of its own, with +`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the +user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the +user drives has no log. Like those of `physicslog yes`, they are written every +two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds +of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. +The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of +those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as +long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. +Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, +and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no -new one starts when driving goes on after that. +new one starts when driving goes on after that. The `.dat` logs it gives with the physics logs off go on +then, after the gap of the time in the editor, until the simulator closes: they are files of their own. It is written as the session goes and flushed once a second, so the file can be read while the simulator still writes it, and after a crash all but the last second is there. A file without the `end` record @@ -162,14 +190,15 @@ record. ### 0x20 cab -The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 190 bytes. +The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 194 bytes (190 in the +files written before the speed of the wheels was added at the end). | type | field | |---------|------------------------------------------------------------------------| | `f64` | t | | `u32` | number of the vehicle | | `dvec3` | position | -| `f32` | speed [km/h], positive along the front of the vehicle | +| `f32` | speed of the vehicle [km/h], positive along its front | | `f32` | acceleration along the track [m/s²] | | `f32` | odometer [km] | | `u8` | driver: 0 none, 1 the user, 2 the AI (the autopilot) | @@ -221,6 +250,7 @@ The vehicle the user is in, every 0.1 s, also while the user looks around outsid | `f32` | the clutch of a diesel's gearbox, 0 open .. 1 closed | | `f32` | the filling of a diesel's hydraulic torque converter, 0..1 | | `f32` | the highest brake cylinder pressure of the vehicles of the train [bar] | +| `f32` | speed of the wheels [km/h], as the speedometer shows it: those of the powered vehicle (in a unit driven from an unpowered car, its motor car), signed as the speed of the vehicle: apart from it while the wheels slip, 0 while they are locked in a skid | The lights the train is to show follow from the movement and the two patterns after it: in a train run the head the pattern asked for, the usual one Pc 1 (both headlights and the upper one; Pc 2 is the left red marker with the right and the @@ -285,7 +315,8 @@ whose motors the cab drives (the motor car of a unit). | 0x0800'0000 | the cruise control holds a speed | The doors, their permits and steps, the departure signal and the releaser are of the vehicle the user is -in; the pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. +in. Left and right are those of the vehicle, seen from its front: from the rear cab (the cab -1) the driver's +left doors are the vehicle's right, as the simulator works them from there. The pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. The lights: 0x001 left headlight, 0x002 left red marker, 0x004 upper headlight, 0x010 right headlight, 0x020 right red marker, 0x040 rear-end signals, 0x080 left and 0x100 right auxiliary diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 12569ebd0..81a195aeb 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -16,7 +16,10 @@ http://mozilla.org/MPL/2.0/. #include #endif +#include +#include #include +#include namespace editor_http { @@ -160,6 +163,37 @@ bool client::get(std::string const &Url, std::vector &Out, std::st #elif defined(EU07_WITH_CURL) +namespace +{ +// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it +// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there +// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +std::string const &certificates_file() +{ + static std::string const file{[]() { + std::error_code error; + for (char const *variable : {"SSL_CERT_FILE", "CURL_CA_BUNDLE"}) + { + if (char const *value{std::getenv(variable)}; (value != nullptr) && (*value != '\0') && std::filesystem::is_regular_file(value, error)) + return std::string{value}; + } + for (char const *candidate : { + "/etc/ssl/certs/ca-certificates.crt", // Debian, Ubuntu, Arch, SteamOS, Gentoo, NixOS + "/etc/pki/tls/certs/ca-bundle.crt", // Fedora, RHEL + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL + "/etc/ssl/ca-bundle.pem", // openSUSE + "/etc/ssl/cert.pem", // Alpine, the BSDs, macOS + }) + { + if (std::filesystem::is_regular_file(candidate, error)) + return std::string{candidate}; + } + return std::string{}; + }()}; + return file; +} +} // namespace + client::client() : m_platform(std::make_unique()) { @@ -204,6 +238,14 @@ bool client::get(std::string const &Url, std::vector &Out, std::st ::curl_easy_reset(m_platform->curl); ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + if (auto const &certificates{certificates_file()}; false == certificates.empty()) + { + ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); +#if LIBCURL_VERSION_NUM >= 0x073400 + // an https proxy is checked with the same file + ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); +#endif + } ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); // http kept for the services the user types; nothing else, also where a redirect leads diff --git a/editor/editorPreviews.cpp b/editor/editorPreviews.cpp index 27f84a9fe..68164460c 100644 --- a/editor/editorPreviews.cpp +++ b/editor/editorPreviews.cpp @@ -298,7 +298,9 @@ void image_cache::work() m_queue.pop_front(); } int width{0}, height{0}, components{0}; - auto *pixels{stbi_load(image.path.c_str(), &width, &height, &components, 4)}; + // the file as it's named on the disk, the path stays the key of the cache + auto const file{FileCased(image.path)}; + auto *pixels{file.empty() ? nullptr : stbi_load(file.c_str(), &width, &height, &components, 4)}; if (pixels != nullptr && width > 0 && height > 0) { // scaled down by the average of the pixels which make each one, the longer side to the size of the cache diff --git a/gl/shader.cpp b/gl/shader.cpp index 31a3e6a87..c276cdef8 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -1,8 +1,10 @@ #include "stdafx.h" +#include #include #include #include +#include #include "shader.h" #include "glsl_common.h" #include "utilities/Logs.h" @@ -58,6 +60,12 @@ std::string gl::shader::read_file(const std::string &filename) const std::ifstream f; f.open(filename); + if (false == f.is_open()) + { + // with the reason the system gives: a file which is there but can't be opened (too many files open) looks + // the same as a missing one otherwise + throw shader_exception("cannot open shader: " + filename + " (" + std::generic_category().message(errno) + ")"); + } stream << f.rdbuf(); f.close(); diff --git a/global_include/interfaces/IMaterial.h b/global_include/interfaces/IMaterial.h index c6f3d1237..2d16a43b0 100644 --- a/global_include/interfaces/IMaterial.h +++ b/global_include/interfaces/IMaterial.h @@ -3,6 +3,7 @@ #include #include #include +#include #include "ITexture.h" @@ -17,6 +18,11 @@ struct IMaterial virtual std::optional GetSelfillum() const = 0; virtual int GetShadowRank() const = 0; virtual texture_handle GetTexture(int slot) const = 0; + // every texture the material draws with, those of all its variants included. materials which don't tell give none + virtual std::vector GetAllTextures() const + { + return {}; + } static IMaterial *null_material() { struct NullMaterial : public IMaterial diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 668792f28..4a5bc4759 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -12248,15 +12248,11 @@ msgstr "Wierzchołek %zu: krzywa przejściowa między łukiem przylegającego to msgid "Download area" msgstr "Obszar pobierania" -msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model, -goes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" -msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle -do pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" +msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model,\ngoes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" +msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle\ndo pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" -msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up; -a point dragged moves, Shift+click removes it" -msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje; -przeciągnięty punkt się przesuwa, Shift+klik go usuwa" +msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up;\na point dragged moves, Shift+click removes it" +msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje;\nprzeciągnięty punkt się przesuwa, Shift+klik go usuwa" msgid "%zu points" msgstr "punktów: %zu" diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 680f67c42..52bc4047e 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -137,15 +137,19 @@ TModelsManager::find_in_databank( std::string const &Name ) { } // checks whether specified file exists. returns name of the located file, or empty string. +// the file is found in any case, as the scenery made on Windows names it, but the name is given back as asked for: it's the key of +// the bank, and TModel3d::LoadFromFile() opens the file as it's named on the disk std::string TModelsManager::find_on_disk( std::string const &Name ) { std::vector extensions { { ".e3d" }, { ".t3d" } }; for( auto const &extension : extensions ) { - auto lookup = FileExists(Name + extension) ? Name : FileExists(paths::models + Name + extension) ? paths::models + Name : ""; - if( false == lookup.empty() ) { - return lookup; + if( false == FileCased( Name + extension ).empty() ) { + return Name; + } + if( false == FileCased( paths::models + Name + extension ).empty() ) { + return paths::models + Name; } } diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 44f5f6255..e3507e216 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1702,24 +1702,27 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) m_filename = name; asBinary = name + ".e3d"; + // the files as they're named on the disk, the name given is in lowercase + auto const textfile{FileCased(name + ".t3d")}; + auto const binaryfile{FileCased(asBinary)}; // Hirek: Jesli mamy ustawione priorityLoadText3D na yes to wpierw ladujemy t3d - if (Global.priorityLoadText3D && FileExists(name + ".t3d")) + if (Global.priorityLoadText3D && (false == textfile.empty())) { - WriteLog("Forced loading text model \"" + name + ".t3d\""); - LoadFromTextFile(name + ".t3d", dynamic); + WriteLog("Forced loading text model \"" + textfile + "\""); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } - else if (FileExists(asBinary)) + else if (false == binaryfile.empty()) { - LoadFromBinFile(asBinary, dynamic); + LoadFromBinFile(binaryfile, dynamic); asBinary = ""; Init(); } - else if (FileExists(name + ".t3d")) + else if (false == textfile.empty()) { - LoadFromTextFile(name + ".t3d", dynamic); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } diff --git a/model/Texture.cpp b/model/Texture.cpp index cd275c9e0..9b428202b 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -640,7 +640,7 @@ void opengl_texture::load_STBI() { int x, y, n; stbi_set_flip_vertically_on_load(1); - uint8_t *image = stbi_load((name + type).c_str(), &x, &y, &n, 4); + uint8_t *image = stbi_load(FileOnDisk(name + type).c_str(), &x, &y, &n, 4); if (!image) { data_state = resource_state::failed; @@ -818,7 +818,7 @@ DDSURFACEDESC2 opengl_texture::deserialize_ddsd(std::istream &s) void opengl_texture::load_DDS() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -938,7 +938,7 @@ opengl_texture::load_DDS() { if( true == Global.gfx_texture_streaming ) { // the data is read by a worker thread, everything else about the texture is known already request = std::make_shared(); - request->file = name + type; + request->file = FileOnDisk( name + type ); request->offset = static_cast( file.tellg() ) + offset; request->size = datasize; request->flip = flip; @@ -1000,7 +1000,7 @@ opengl_texture::load_DDS() { void opengl_texture::load_KTX() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -1061,7 +1061,7 @@ opengl_texture::load_KTX() { void opengl_texture::load_TEX() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); char head[ 5 ]; file.read( head, 4 ); @@ -1108,7 +1108,7 @@ opengl_texture::load_TEX() { void opengl_texture::load_TGA() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); // Read the header of the TGA, compare it with the known headers for compressed and uncompressed TGAs unsigned char tgaheader[ 18 ]; @@ -1886,6 +1886,52 @@ texture_manager::mark_as_needed( texture_handle const Texture, bool const Near ) } } +void +texture_manager::unload( texture_handle const Texture ) { + + if( ( Texture <= 0 ) + || ( Texture >= static_cast( m_textures.size() ) ) ) { + return; + } + auto const &record { m_textures[ Texture ] }; + auto &texture { *record.first }; + if( ( record.second != resource_timestamp() ) + || ( texture.id == 0 ) // failed to load + || ( true == texture.is_static ) + || ( true == texture.is_rendertarget ) + || ( texture.type == "make:" ) + || ( texture.type == "internalsrc:" ) ) { + return; + } + if( ( texture.data_state == resource_state::loading ) + && ( texture.request != nullptr ) ) { + // read by a worker thread: taken over first, to be dropped with the rest + texture.complete_data(); + if( texture.data_state == resource_state::failed ) { + return; + } + } + auto const created { texture.id != opengl_texture::invalid_id }; + if( ( false == created ) + && ( texture.data_state != resource_state::good ) ) { + // nothing read nor made, e.g. the textures of a material asked for without loading + return; + } + if( true == created ) { + // deleted outright: release() would read the texture back from the card with gfx.resource.move, only for it to be dropped + ::glDeleteTextures( 1, &texture.id ); + texture.id = opengl_texture::invalid_id; + texture.is_ready = false; + // the released gl name can be given to a new texture, the unit cache can't trust it + for( auto &unit : opengl_texture::units ) { + unit = -1; + } + } + texture.data = std::vector(); + texture.data_state = resource_state::none; + texture.reload_on_use = true; +} + // releases gl textures of vehicles not needed nor drawn for a while void texture_manager::release_unneeded() { diff --git a/model/Texture.h b/model/Texture.h index 313d0f6f4..20221fcea 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -181,6 +181,10 @@ public: // releases gl textures of vehicles not needed nor drawn for a while void release_unneeded(); + // takes a texture the scene has never drawn out of both the gfx card and the memory, e.g. the image of a picker scrolled + // past, or one read and not made yet; it's read again when it's used. textures the scene draws are left to the resource sweep + void + unload( texture_handle const Texture ); // debug performance string std::string info() const; diff --git a/model/material.cpp b/model/material.cpp index 4e96ddd8c..fbd58bd70 100644 --- a/model/material.cpp +++ b/model/material.cpp @@ -86,11 +86,11 @@ int opengl_material::texture_slot( std::string const &Key ) // named binding, the slot it fills is up to the shader key.erase( 0, 1 ); key.pop_back(); - if( shader && ( shader->texture_conf.find( key ) != shader->texture_conf.end() ) ) { + if( shader && shader->texture_conf.contains( key ) ) { return static_cast( shader->texture_conf[ key ].id ); } - auto const lookup { texture_bindings.find( key ) }; - if( ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { + if( auto const lookup { texture_bindings.find( key ) }; + ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { return lookup->second; } // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders @@ -318,7 +318,7 @@ std::unordered_set seasons = { bool is_season( std::string const &String ) { - return seasons.find(String) != seasons.end(); + return seasons.contains(String); } std::unordered_set weather = { @@ -326,7 +326,7 @@ std::unordered_set weather = { bool is_weather( std::string const &String ) { - return weather.find(String) != weather.end(); + return weather.contains(String); } // imports member data pair from the config file @@ -362,7 +362,7 @@ void opengl_material::deserialize_texture_mapping( cParser &Input, std::string c value = variants.front(); } - auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, parse_info_s::tex_def{ value, Priority, variants } ) }; + auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, value, Priority, variants ) }; if( ( false == inserted ) && ( Priority > it->second.priority ) ) { it->second = parse_info_s::tex_def{ value, Priority, variants }; } @@ -389,7 +389,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } else if( key == Global.Season ) { @@ -397,7 +397,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } @@ -477,7 +477,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } @@ -489,7 +489,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } diff --git a/model/material.h b/model/material.h index 82d14557c..4b7323f76 100644 --- a/model/material.h +++ b/model/material.h @@ -66,6 +66,13 @@ struct opengl_material : public IMaterial { { return textures[slot]; } + virtual std::vector GetAllTextures() const override + { + std::vector all(textures.begin(), textures.end()); + for (auto const &variant : texture_variants) + all.insert(all.end(), variant.begin(), variant.end()); + return all; + } // returns texture set to use for model instance identified by provided variant id texture_set const &GetTextures(std::uint32_t const Variant) const { diff --git a/nodebank_previews_standalone.cpp b/nodebank_previews_standalone.cpp index d94eb13ed..65c5e07f3 100644 --- a/nodebank_previews_standalone.cpp +++ b/nodebank_previews_standalone.cpp @@ -76,19 +76,21 @@ bool parse_arguments(int const Argc, char *Argv[], preview_settings &Settings) } else if (token == "-resolution") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.resolution)) || (Settings.resolution < 16)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.resolution)) || (Settings.resolution < 16)) { report("-resolution needs a number of pixels, 16 or more", true); return false; } + ++i; } else if (token == "-margin") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.margin)) || (Settings.margin < 0)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.margin)) || (Settings.margin < 0)) { report("-margin needs a number of pixels, 0 or more", true); return false; } + ++i; } else if (token == "-no-shadows") { diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 5eb98222b..800f33dcf 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2570,6 +2570,11 @@ ITexture const &opengl33_renderer::Texture(texture_handle const Texture) const return m_textures.texture(Texture); } +void opengl33_renderer::Unload_Texture(texture_handle const Texture) +{ + m_textures.unload(Texture); +} + void opengl33_renderer::Update_AnimModel(TAnimModel *model) { model->RaAnimate(m_framestamp); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 807563c40..4322cc2db 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -110,6 +110,8 @@ class opengl33_renderer : public gfx_renderer { Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 71bd7d0ef..5083c6f2f 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -419,6 +419,15 @@ opengl_renderer::Render() { // add user interface setup_units( true, false, false ); ::glPushClientAttrib( GL_CLIENT_VERTEX_ARRAY_BIT ); + // the arrays the scene left enabled point into the buffer of whatever was drawn last; the ui sets up + // the vertex, colour and texture coordinates of the active unit only, so the driver would go on reading + // the rest with the indices of the ui, past the end of that buffer once the ui has more vertices than it + for( auto const unit : m_geometry.units().texture ) { + ::glClientActiveTexture( GL_TEXTURE0 + unit ); + ::glDisableClientState( GL_TEXTURE_COORD_ARRAY ); + } + ::glDisableClientState( GL_NORMAL_ARRAY ); + ::glDisableClientState( GL_COLOR_ARRAY ); ::glClientActiveTexture( GL_TEXTURE0 + m_diffusetextureunit ); // clear state for ui @@ -1922,6 +1931,12 @@ opengl_renderer::Texture( texture_handle const Texture ) const { return m_textures.texture( Texture ); } +void +opengl_renderer::Unload_Texture( texture_handle const Texture ) { + + m_textures.unload( Texture ); +} + void opengl_renderer::Pick_Control_Callback( std::function Callback ) { diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index ecb8a3c50..ef3a9f0f3 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -95,6 +95,8 @@ public: Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/renderer.cpp b/rendering/renderer.cpp index d9d4b5df0..7c4098ef0 100644 --- a/rendering/renderer.cpp +++ b/rendering/renderer.cpp @@ -29,6 +29,11 @@ std::unique_ptr gfx_renderer_factory::create(const std::string &ba return nullptr; } +bool gfx_renderer_factory::has_backend(const std::string &name) const +{ + return backends.contains(name); +} + gfx_renderer_factory *gfx_renderer_factory::get_instance() { if (!instance) @@ -39,6 +44,16 @@ gfx_renderer_factory *gfx_renderer_factory::get_instance() gfx_renderer_factory *gfx_renderer_factory::instance; +void gfx_renderer::Unload_Material( material_handle const Material ) +{ + if( Material == null_handle ) { + return; + } + for( auto const texture : this->Material( Material )->GetAllTextures() ) { + Unload_Texture( texture ); + } +} + material_handle gfx_renderer::Terrain_Material( material_handle const Reuse, std::vector const &Layers, int const Samples, std::uint8_t const *Weights, glm::vec3 const &Placement ) { // without blending the chunk gets the material which covers the most of it diff --git a/rendering/renderer.h b/rendering/renderer.h index 5ad805c4a..c72dcaea9 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -102,6 +102,11 @@ public: virtual void Bind_Texture( std::size_t const Unit, texture_handle const Texture ) = 0; virtual auto Texture( texture_handle const Texture ) -> ITexture & = 0; virtual auto Texture( texture_handle const Texture ) const -> ITexture const & = 0; + // a texture the scene has never drawn taken out of the gfx card and the memory, read again when it's used: the image of a + // texture picker scrolled past. backends which keep their textures otherwise leave it + virtual void Unload_Texture( texture_handle const Texture ) {} + // the same for all the textures of a material, those of its variants with them + void Unload_Material( material_handle const Material ); // utility methods virtual void Pick_Control_Callback( std::function Callback ) = 0; virtual void Pick_Node_Callback( std::function Callback ) = 0; @@ -151,6 +156,7 @@ public: bool register_backend(const std::string &backend, create_method func); std::unique_ptr create(const std::string &name); + bool has_backend(const std::string &name) const; static gfx_renderer_factory* get_instance(); diff --git a/scene/scene.cpp b/scene/scene.cpp index b31c1749a..eed3f6438 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" +#include "vehicle/aiwire.h" namespace scene { @@ -57,25 +58,15 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex for( auto *traction : m_directories.traction ) { - // współczynniki równania parametrycznego - auto const paramfrontdot = glm::dot( traction->vParametric, vFront ); - auto const fRaParam = - -( glm::dot( traction->pPoint1, vFront ) - glm::dot( pantographposition, vFront ) ) - / ( paramfrontdot != 0.0 ? - paramfrontdot : - 0.001 ); // div0 trap - - if( fRaParam < -0.001 - || fRaParam > 1.001 ) { continue; } + // the span against the pantograph, the geometry the AI uses to find the wire as well + auto const contact = ai_wire::span_contact( + traction->pPoint1, traction->vParametric, pantographposition, vFront, vUp, vLeft, pantograph->fWidth ); // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk = traction->pPoint1 + fRaParam * traction->vParametric; - // wektor musi się mieścić w przedziale ruchu pantografu - auto const vGdzie = vStyk - pantographposition; - auto fVertical = glm::dot( vGdzie, vUp ); + if( false == contact.within ) { continue; } + auto fVertical = contact.vertical; if( fVertical >= 0.0 ) { // jeśli ponad pantografem (bo może łapać druty spod wiaduktu) - auto const fHorizontal = std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth; + auto const fHorizontal = contact.horizontal; if (Global.bEnableTraction && fVertical < pantograph->PantWys - 0.15 ) { @@ -120,6 +111,24 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex } } +// checks whether a wire of the cell, not broken, is within reach of a pantograph at specified point +bool +basic_cell::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + for( auto const *traction : m_directories.traction ) { + if( ( traction->DamageFlag & 128 ) != 0 ) { + // a broken wire powers nothing + continue; + } + if( ai_wire::reaches( + ai_wire::span_contact( traction->pPoint1, traction->vParametric, Point, Front, Up, Left, Halfwidth ), + Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, updates sounds and polls event launchers within radius around specified point void basic_cell::update_events() { @@ -785,6 +794,22 @@ basic_section::update_traction( TDynamicObject *Vehicle, int const Pantographind } } +// checks whether a wire of the section's cells around specified point is within reach of a pantograph at the point +bool +basic_section::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + auto const radius { EU07_CELLSIZE * 0.5 }; // the same area of interest the pantographs look for their wire in + + for( auto const &cell : m_cells ) { + // we reject early cells which aren't within our area of interest + if( glm::length2( cell.area().center - Point ) < sq( cell.area().radius + radius ) + && cell.wire_over( Point, Front, Up, Left, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, polls event launchers within radius around specified point void basic_section::update_events( glm::dvec3 const &Location, float const Radius ) { @@ -1168,6 +1193,29 @@ basic_region::update_traction( TDynamicObject *Vehicle, int const Pantographinde } } +// checks whether there's a contact wire over specified point, within reach of a pantograph there +bool +basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + // the vertical up and the horizontal left of the heading. the tilt of the track in curves is left out + auto const up { glm::dvec3 { 0.0, 1.0, 0.0 } }; + auto const left { glm::cross( up, Front ) }; + auto const leftlength { glm::length( left ) }; + if( leftlength <= 0.0 ) { + // no heading along the ground + return false; + } + // a list of its own, not the shared scratchpad of the region + std::vector sectionlist; + sections( Point, EU07_CELLSIZE * 0.5, sectionlist ); + for( auto const *section : sectionlist ) { + if( section->wire_over( Point, Front, up, left / leftlength, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // checks whether specified file is a valid region data file bool basic_region::is_scene( std::string const &Scenariofile ) const { diff --git a/scene/scene.h b/scene/scene.h index 1c3f8064c..b8256e257 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -109,6 +109,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers within radius around specified point void update_events(); @@ -320,6 +324,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, updates sounds and polls event launchers within radius around specified point void update_events( glm::dvec3 const &Location, float const Radius ); @@ -446,6 +454,11 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether there's a contact wire, not broken, over specified point of a track with heading Front, within reach of + // a pantograph there: over its slide of half width Halfwidth, between Minheight and Maxheight above the point. the + // geometry is the one the pantographs find their wire with (ai_wire::span_contact), with the vertical up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers around camera void update_events(); diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 426f0e077..18b1905a4 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -143,7 +143,7 @@ shape_node::deserialize( std::istream &Input ) { // restores content of the node from provided input stream shape_node & -shape_node::import( cParser &Input, scene::node_data const &Nodedata ) { +shape_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; @@ -561,7 +561,7 @@ lines_node::deserialize( std::istream &Input ) { // restores content of the node from provded input stream lines_node & -lines_node::import( cParser &Input, scene::node_data const &Nodedata ) { +lines_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; diff --git a/scene/scenenode.h b/scene/scenenode.h index 237056669..a534f0631 100644 --- a/scene/scenenode.h +++ b/scene/scenenode.h @@ -122,7 +122,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream shape_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // imports data from provided submodel shape_node & convert( TSubModel const *Submodel ); @@ -254,7 +254,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream lines_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // adds content of provided node to already enclosed geometry. returns: true if merge could be performed bool merge( lines_node &Lines ); diff --git a/scene/sceneterrain.cpp b/scene/sceneterrain.cpp index d0453f2b3..585912a2b 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -455,7 +455,7 @@ bool terrain_file::write(std::string const &Text, std::string const &Binaryfile, Message = "node of type \"" + nodedata.type + "\" (line " + std::to_string(input.Line()) + ") can't be a part of binary terrain"; return false; } - auto shape{shape_node().import(input, nodedata)}; + auto shape{shape_node().import_from(input, nodedata)}; // the shapes are all sent to the section cells, which groups them the way it'd be done for translucent geometry. // whether they can be merged into section-wide pieces instead is decided when the file is loaded, see the layout notes shape.m_data.translucent = true; @@ -799,7 +799,7 @@ bool read_text_triangles(std::string const &Text, terrain_reference const &Refer input >> nodedata.range_max >> nodedata.range_min >> nodedata.name >> nodedata.type; if (nodedata.type == "triangles" || nodedata.type == "triangle_strip" || nodedata.type == "triangle_fan") { - auto const shape{shape_node().import(input, nodedata)}; + auto const shape{shape_node().import_from(input, nodedata)}; auto const &data{shape.data()}; auto const *material{GfxRenderer->Material(data.material)}; auto const name{material != nullptr ? material->GetName() : std::string{}}; diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index 666609b0e..fac540019 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -443,7 +443,7 @@ auto python_taskqueue::run_file(std::string const &File, std::string const &Path return false; } - std::ifstream inputfile{filepath + fileextension}; + std::ifstream inputfile{FileOnDisk(filepath + fileextension)}; std::string input; input.assign(std::istreambuf_iterator(inputfile), std::istreambuf_iterator()); diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index 422ce70dc..1a1751732 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -523,9 +523,9 @@ class wasm_runtime_host final : public runtime { for (auto const &[script, entry] : m_modules) { - if (entry.module != nullptr) + if (entry.wasm_module != nullptr) { - wasm_runtime_unload(entry.module); + wasm_runtime_unload(entry.wasm_module); } } if (m_started) @@ -551,7 +551,7 @@ class wasm_runtime_host final : public runtime struct module_entry { std::vector bytes; // the runtime reads the module from here as long as it is loaded - wasm_module_t module{nullptr}; + wasm_module_t wasm_module{nullptr}; }; wasm_module_t load_module(std::string const &Script); @@ -584,7 +584,7 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) { if (auto const lookup{m_modules.find(Script)}; lookup != m_modules.end()) { - return lookup->second.module; + return lookup->second.wasm_module; } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; @@ -601,23 +601,23 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) return nullptr; } std::array error{}; - entry.module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); - if (entry.module == nullptr) + entry.wasm_module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); + if (entry.wasm_module == nullptr) { ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data())); } - return entry.module; + return entry.wasm_module; } std::unique_ptr wasm_runtime_host::load(std::string const &Script, script_screen_kind const Kind) { - auto *module{load_module(Script)}; - if (module == nullptr) + auto *wasm_module{load_module(Script)}; + if (wasm_module == nullptr) { return nullptr; } auto loaded{std::make_unique(Script, Kind)}; - if (false == loaded->instantiate(module)) + if (false == loaded->instantiate(wasm_module)) { return nullptr; } diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 608b07586..9e979e2ca 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" @@ -43,6 +44,7 @@ namespace { // [s] between the samples of the user's train, the looks at everything else and the full looks at the vehicles constexpr double cabinterval{0.1}; +constexpr double tapeinterval{0.05}; // as the physics logs (deltalog of Driver.cpp) constexpr double lookinterval{1.0}; constexpr double slowlook{20.0}; // [ms] a look around taking longer is told in the log, part by part constexpr double keyframeinterval{60.0}; @@ -234,15 +236,26 @@ void blackbox_recorder::update(double const Deltatime) { if (false == simulation::is_ready) return; m_started = true; - if (false == WriteLogFlag || false == Global.BlackBox || Global.editor_session) + // "blackbox yes" or "no" of eu07.ini decides by itself, with no entry it goes with the physics logs + if (false == Global.BlackBox.value_or(WriteLogFlag || WriteTrainLogFlag) || Global.editor_session) return; + m_taping = true; open(); } - if (m_writer == nullptr) + if (false == m_taping) return; std::scoped_lock lock{m_mutex}; m_time += Deltatime; + // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a + // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with + // a recording which couldn't be made + if (m_time >= m_tapedue) { + keep_tape_line(); + m_tapedue = std::max(m_tapedue + tapeinterval, m_time); + } + if (m_writer == nullptr) + return; if (m_time >= m_cabdue) { write_cab(); m_cabdue = std::max(m_cabdue + cabinterval, m_time); @@ -412,6 +425,13 @@ void blackbox_recorder::write_cab() { sample.vehicle = vehicle_id(vehicle); sample.position = vehicle->GetPosition(); sample.speed_kmh = static_cast(occupied->V * 3.6); + // of the wheels as they turn, which the speedometer shows: apart from that of the vehicle when they slip or skid. + // those of the powered vehicle, as the speedometer has it (TTrain::DynamicSet), which in a unit driven from an + // unpowered car is another one, maybe facing the other way: signed as the occupied one's speed + // the vehicle itself, if none in the unit is powered + auto const *powered{train->Dynamic()->FindPowered()}; + auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->MoverParameters->WheelDiameter * powered->MoverParameters->nrot * 3.6); sample.acceleration = static_cast(controlling->AccS); sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { @@ -480,6 +500,30 @@ void blackbox_recorder::write_cab() { m_writer->cab(sample); } +void blackbox_recorder::keep_tape_line() { + auto const *train{simulation::Train}; + if (train == nullptr || train->Dynamic() == nullptr) + return; + auto const *vehicle{train->Dynamic()}; + // the driver of the vehicle, whose log it would be: it keeps the name of its first vehicle, so a change of the cab + // in a unit goes on in the same log. a passive one stands still (its clock too), so then the driver of the train + auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; + if (driver == nullptr) + return; + auto const &name{driver->physicslog_name()}; + // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has + // no time for, on a hard disk with hundreds of them + PhysicsLogs.put_first(name); + // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice + if (driver->writes_physicslog()) + return; + if (m_tapes.insert(name).second) { + PhysicsLogs.begin(name, TController::physicslog_header()); + WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); + } + PhysicsLogs.append(name, driver->physicslog_line()); +} + void blackbox_recorder::look_around(bool const Keyframe) { auto const &time{simulation::Time.data()}; m_writer->clock(m_time, static_cast(time.wYear), static_cast(simulation::Time.year_day()), second_of_day()); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 677c680b0..18ee052c4 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -31,13 +32,14 @@ enum class user_command; namespace simulation { // the black box of the session (see blackbox_doc.md): written along with the physics logs, in driver mode, -// from the moment the scenario is loaded until the simulator closes or the editor is entered +// from the moment the scenario is loaded until the simulator closes or the editor is entered. the tapes of the user's +// vehicles, with the physics logs off, go on after the editor until the simulator closes class blackbox_recorder { public: // starts the recording once the scenario is ready, if it is to be made, then records what is due. // Deltatime: simulation time passed since the last call void update(double Deltatime); - // writes the end of the recording and closes the file. a recording closed isn't started again + // writes the end of the recording and closes the file. a recording closed isn't started again; its tapes go on void close(); // what happens between the looks, from wherever it happens; the cabs may run on threads of their own. @@ -86,6 +88,11 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); + // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road + // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would + // have it. a driver's log is begun at the first line given for that driver, and goes on + // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap + void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals void look_around(bool Keyframe); void look_at_vehicles(bool Keyframe); @@ -107,8 +114,12 @@ private: std::ofstream m_file; std::unique_ptr m_writer; bool m_started{false}; // tried to start, made or not + bool m_taping{false}; // the recording was to be made: its tapes are kept from then on, the file made or not, closed or not double m_time{0.0}; double m_cabdue{0.0}; + double m_tapedue{0.0}; + // the names of the logs begun by the recording + std::set m_tapes; double m_lookdue{0.0}; double m_keyframedue{0.0}; std::unordered_map m_vehicles; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 41f67398c..da3e075ef 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -576,7 +576,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "road" ) { auto *road { new road_node( nodedata ) }; - road->import( + road->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -592,7 +592,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "sweep" ) { auto *sweep { new sweep_node( nodedata ) }; - sweep->import( + sweep->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -606,7 +606,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "junction" ) { auto *junction { new junction_node( nodedata ) }; - junction->import( + junction->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -638,7 +638,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( roadpoint_node::is_keyword( nodedata.type ) ) { // level crossing, or a point where road vehicles appear or are taken away auto *point { new roadpoint_node( nodedata ) }; - point->import( + point->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -739,7 +739,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch if( false == skip ) { ++Scratchpad.binary.geometry_imported; - auto shape { scene::shape_node().import( Input, nodedata ) }; + auto shape { scene::shape_node().import_from( Input, nodedata ) }; material = shape.data().material; if( true == Global.editor_session ) { shape.source_file( scene::terrain_file::reference_of( Input.Name() ) ); @@ -777,7 +777,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ++Scratchpad.binary.geometry_imported; simulation::Region->insert( - scene::lines_node().import( + scene::lines_node().import_from( Input, nodedata ), Scratchpad ); } @@ -1205,6 +1205,8 @@ include_terrain_file( std::string File, std::string &Includes, scene::scratch_da replace_slashes( File ); erase_extension( File ); + // the parser gives the name in lowercase, the files may be named in another case; the binary file is made next to the text + File = FileStemOnDisk( Global.asCurrentSceneryPath, File, { ".txtf", ".btf" } ); if( std::find( binary.terrain_textfiles.begin(), binary.terrain_textfiles.end(), File ) != binary.terrain_textfiles.end() ) { WriteLog( "Terrain file: " + File + " is already in use, ignored" ); return; diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 89a8a1046..2efa57291 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" +#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -44,6 +46,15 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } +// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of +// the other drivers: the closing at the end of the run drops those it has no time for +void put_physicslog_first(TDynamicObject const &Vehicle) +{ + auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; + if (driver != nullptr) + PhysicsLogs.put_first(driver->physicslog_name()); +} + } // namespace namespace simulation { @@ -124,11 +135,13 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - if (simulation::Vehicles.find(name) == nullptr) + auto const *vehicle { simulation::Vehicles.find(name) }; + if (vehicle == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } + put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; @@ -261,7 +274,9 @@ void test_manager::check_wall_clock(double const Elapsed) // but which doesn't close ends with its result if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit))) ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit)); - // what was logged last gets written, unless the log is held up by a hung thread + // what was logged last gets written, unless the log is held up by a hung thread, or the physics logs by a writer + // holding their files or a disk which doesn't answer: the run ends anyway, two seconds later at most + PhysicsLogs.flush_for(std::chrono::seconds{2}); StopLogService(); std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::_Exit(exit_code()); diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index ffb849ffd..9b677fbed 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -81,7 +81,15 @@ These are run by the game, by vehicles it has or by the cab, the AI or the scene The core library (`eu07_core`) and the test binary hold more than the physics: the parser of the game's text files, the helpers of `utilities.cpp`, the PLC of a vehicle, the parts of the vehicles and of the simulation moved out of the big classes to be tested, and the hosts of the script screens. The sections above don't cover them. Their numbers are lines run, from the report of the Coverage workflow. -The tables show the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. What those tests add is measured by the Coverage run of the pull request which brings them, and shown in the summary of that run. +The per-file table further down is from the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. With them, in the Coverage run of master `bac9954a` (2026-11-11, after #333; GCC 13.3, unoptimised, gcov): + +| File | Lines run, before | Lines run, with the tests | Functions run, with the tests | +|---|---|---|---| +| `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 98.2% (213 of 217) | 11 of 11 | +| `utilities/parser.cpp` | 40.0% (170 of 425) | 97.6% (415 of 425) | 41 of 41 | +| `utilities/utilities.cpp` | 28.2% (82 of 291) | 95.5% (299 of 313) | 51 of 51 | + +`utilities.cpp` grew by 22 lines on master between the two runs (`user_cache_path`, `utf8_to_win1250`). All 62 files of the game in that report together: lines 83.5% (15411 of 18464), functions 85.5% (1378 of 1612), branches 59.5% (15503 of 26046). The totals aren't comparable with the run below: the report holds 13 more files, from the merges in between. **The run measured:** pull request #325 on 2026-11-11 (its commit `33cedc45` merged into master `10c7527a`), GCC 13.3, unoptimised, gcov lines. All 49 files of the game in the report together: lines 84.4% (10305 of 12204), functions 85.0% (927 of 1090), branches 62.3% (10325 of 16578). @@ -114,7 +122,7 @@ The tables show the run before the tests of the parser, the helpers and the PLC Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. -- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. They have tests (`test_brake_setting.cpp`, `test_odometer.cpp`) and no numbers yet. +- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). diff --git a/tests/unit/test_ai_wire.cpp b/tests/unit/test_ai_wire.cpp new file mode 100644 index 000000000..070f8618f --- /dev/null +++ b/tests/unit/test_ai_wire.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aiwire.h" + +#include +#include +#include + +// where the overhead wire is for the AI driver (vehicle/aiwire.h): a pantograph against a span of the wire, and how far +// short of its target a train stops to keep its pantograph under the wire. the scene query over these +// (basic_region::wire_over) needs the scene, which the unit tests don't link + +namespace { + +// a vehicle running along +z on level track, the pantograph's base point 4 m above the origin +glm::dvec3 const front{0.0, 0.0, 1.0}; +glm::dvec3 const up{0.0, 1.0, 0.0}; +glm::dvec3 const left{1.0, 0.0, 0.0}; +glm::dvec3 const pantograph{0.0, 4.0, 0.0}; +double const halfwidth{0.5}; + +// a 100 m span along the track, at height Height and Offset to the side, its middle at Middle along the track +ai_wire::contact along(double const Offset, double const Height, double const Middle = 0.0) { + return ai_wire::span_contact({Offset, Height, Middle - 50.0}, {0.0, 0.0, 100.0}, pantograph, front, up, left, + halfwidth); +} + +// the wire over the route up to Last metres from the head of the train +auto wire_to(double const Last) { + return [Last](double const Distance) { return Distance <= Last; }; +} + +} // namespace + +TEST_CASE("ai wire: a span centred over the pantograph is on the slide") { + auto const contact{along(0.0, 6.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(2.0)); + CHECK(contact.horizontal == doctest::Approx(-halfwidth)); + CHECK(ai_wire::reaches(contact, 1.0, 3.0)); +} + +TEST_CASE("ai wire: a span at the very edge of the slide still touches it, one beyond it doesn't") { + auto const edge{along(halfwidth, 6.0)}; + CHECK(edge.horizontal == doctest::Approx(0.0)); + CHECK(ai_wire::reaches(edge, 1.0, 3.0)); + // either side + CHECK(ai_wire::reaches(along(-halfwidth, 6.0), 1.0, 3.0)); + + auto const beyond{along(halfwidth + 0.1, 6.0)}; + CHECK(beyond.within); + CHECK(beyond.horizontal == doctest::Approx(0.1)); + CHECK_FALSE(ai_wire::reaches(beyond, 1.0, 3.0)); +} + +TEST_CASE("ai wire: the wire is reached only within the given heights") { + auto const contact{along(0.0, 6.0)}; + + CHECK_FALSE(ai_wire::reaches(contact, 3.0, 9.0)); // too low: below the lowest height + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 1.5)); // too high: a bridge's wire above the line + CHECK(ai_wire::reaches(contact, 2.0, 2.0)); // the limits are included +} + +TEST_CASE("ai wire: a span below the pantograph is crossed but out of reach") { + auto const contact{along(0.0, 3.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(-1.0)); + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 9.0)); +} + +TEST_CASE("ai wire: a span ahead of or behind the pantograph isn't crossed") { + auto const ahead{along(0.0, 6.0, 60.0)}; + CHECK_FALSE(ahead.within); + CHECK_FALSE(ai_wire::reaches(ahead, 0.0, 9.0)); + + CHECK_FALSE(along(0.0, 6.0, -60.0).within); + // the ends of the span have the tolerance of the vehicles: 0.001 of the span's length + CHECK(along(0.0, 6.0, 50.05).within); + CHECK(along(0.0, 6.0, -50.05).within); + CHECK_FALSE(along(0.0, 6.0, 50.2).within); +} + +TEST_CASE("ai wire: a span skewed against the track is met where it crosses the plane of the pantograph") { + // the zigzag of the wire: from 0.3 m to the right to 0.3 m to the left over 100 m + auto const zigzag{ai_wire::span_contact({-0.3, 6.0, -50.0}, {0.6, 0.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(zigzag.within); + CHECK(zigzag.horizontal == doctest::Approx(0.15 - halfwidth)); + CHECK(ai_wire::reaches(zigzag, 1.0, 3.0)); + + // a sloping span from a tunnel portal, 1 m lower at its far end: the height where the plane crosses it + auto const sloping{ai_wire::span_contact({0.0, 6.0, -50.0}, {0.0, -1.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(sloping.vertical == doctest::Approx(1.25)); + + // a span of a wire crossing the line at a right angle lies in the plane of the pantograph over the track, and is + // out of reach a step along the track (the division by zero trap) + auto const across{ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph, front, up, left, halfwidth)}; + CHECK(across.within); + CHECK(std::isfinite(across.vertical)); + CHECK_FALSE(ai_wire::reaches(across, 0.0, 9.0)); // its end, 5 m to the side + CHECK_FALSE(ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph + glm::dvec3{0, 0, 1.0}, front, up, + left, halfwidth) + .within); +} + +TEST_CASE("ai wire: the direction of travel doesn't change what the pantograph meets") { + auto const forward{along(0.3, 6.0)}; + auto const backward{ai_wire::span_contact({0.3, 6.0, -50.0}, {0.0, 0.0, 100.0}, pantograph, -front, up, -left, + halfwidth)}; + + CHECK(backward.within); + CHECK(backward.vertical == forward.vertical); + CHECK(backward.horizontal == forward.horizontal); +} + +TEST_CASE("ai wire: the span test gives the very numbers of the code the vehicles had before it was moved here") { + // the math of basic_cell::update_traction before it called span_contact, as it was there + struct legacy { + bool within; + double vertical; + double horizontal; + }; + auto const legacy_contact{[](glm::dvec3 const &pPoint1, glm::dvec3 const &vParametric, + glm::dvec3 const &pantographposition, glm::dvec3 const &vFront, glm::dvec3 const &vUp, + glm::dvec3 const &vLeft, double const fWidth) { + auto const paramfrontdot = glm::dot(vParametric, vFront); + auto const fRaParam = + -(glm::dot(pPoint1, vFront) - glm::dot(pantographposition, vFront)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + if (fRaParam < -0.001 || fRaParam > 1.001) { + return legacy{false, 0.0, 0.0}; + } + auto const vStyk = pPoint1 + fRaParam * vParametric; + auto const vGdzie = vStyk - pantographposition; + auto const fVertical = glm::dot(vGdzie, vUp); + auto const fHorizontal = std::abs(glm::dot(vGdzie, vLeft)) - fWidth; + return legacy{true, fVertical, fHorizontal}; + }}; + + // pseudo-random vehicles and spans around a point far from the origin, as in a real scenery + std::uint32_t seed{12345}; + auto const next{[&seed](double const Low, double const High) { + seed = seed * 1664525u + 1013904223u; + return Low + (High - Low) * (seed >> 8) / double(1u << 24); + }}; + int within{0}; + for (int sample = 0; sample < 2000; ++sample) { + auto const heading{next(0.0, 6.283185307179586)}; + auto const cant{next(-0.1, 0.1)}; + glm::dvec3 const vFront{std::sin(heading), next(-0.03, 0.03), std::cos(heading)}; + glm::dvec3 const vUp{std::sin(cant) * std::cos(heading), std::cos(cant), -std::sin(cant) * std::sin(heading)}; + auto const vLeft{glm::cross(vUp, vFront)}; + glm::dvec3 const position{next(-20000.0, 20000.0), next(100.0, 300.0), next(-20000.0, 20000.0)}; + auto const pantographposition{position + vUp * 4.2}; + auto const spanheading{heading + next(-0.05, 0.05)}; + glm::dvec3 const vParametric{60.0 * std::sin(spanheading), next(-0.5, 0.5), 60.0 * std::cos(spanheading)}; + auto const pPoint1{position + glm::dvec3{next(-1.0, 1.0), next(5.0, 7.0), next(-1.0, 1.0)} - vParametric * next(-0.2, 1.2)}; + auto const fWidth{next(0.4, 0.7)}; + + auto const old{legacy_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + auto const now{ai_wire::span_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + CAPTURE(sample); + REQUIRE(now.within == old.within); + if (old.within) { + ++within; + // bit for bit + REQUIRE(now.vertical == old.vertical); + REQUIRE(now.horizontal == old.horizontal); + } + } + // both kinds were tried + CHECK(within > 200); + CHECK(within < 1800); +} + +TEST_CASE("ai wire: a stop with the wire over the pantograph stays where it is") { + auto const everywhere{[](double) { return true; }}; + CHECK(ai_wire::wire_shortfall(everywhere, 20.0, 130.0) == 0.0); + + // the wire ends between the pantographs: the rear one the train relies on is under it, with the margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(118.0), 20.0, 130.0) == 0.0); + // gaps behind the pantograph don't matter + auto const gap_behind{[](double const Distance) { return Distance <= 90.0 || Distance >= 95.0; }}; + CHECK(ai_wire::wire_shortfall(gap_behind, 20.0, 130.0) == 0.0); +} + +TEST_CASE("ai wire: a stop past the end of the wire is moved back to put the pantograph under the wire") { + // the head stops at 130 m, the pantograph 20 m behind it at 110 m; the wire ends at 100 m. 2 m steps back to the + // first place with the wire over the pantograph and 3 m ahead of it: 96 m + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0) == doctest::Approx(14.0)); + // the wire ends right at the pantograph: no margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(110.0), 20.0, 130.0) == doctest::Approx(4.0)); + // a gap in the wire at the pantograph: the stop goes before the gap + auto const gap{[](double const Distance) { return Distance <= 107.0 || Distance >= 112.0; }}; + CHECK(ai_wire::wire_shortfall(gap, 20.0, 130.0) == doctest::Approx(6.0)); +} + +TEST_CASE("ai wire: the margin of wire ahead of the pantograph") { + // exactly the margin ahead: fine + CHECK(ai_wire::wire_shortfall(wire_to(113.0), 20.0, 130.0) == 0.0); + // a little less: one step back + CHECK(ai_wire::wire_shortfall(wire_to(112.9), 20.0, 130.0) == doctest::Approx(2.0)); + // other margins and steps + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 0.0, 1.0) == doctest::Approx(10.0)); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 5.0, 1.0) == doctest::Approx(15.0)); +} + +TEST_CASE("ai wire: without the wire within the walk back the stop stays where it is") { + auto const nowhere{[](double) { return false; }}; + CHECK(ai_wire::wire_shortfall(nowhere, 20.0, 130.0) == 0.0); + + // the pantograph at 110 m: the wire ends more than 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-200.0), 20.0, 130.0) == 0.0); + // the last place looked at is 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0) == doctest::Approx(300.0)); + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0, 3.0, 2.0, 298.0) == 0.0); +} + +TEST_CASE("ai wire: a stop without a coverage or a step to walk with stays where it is") { + CHECK(ai_wire::wire_shortfall({}, 20.0, 130.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, 0.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, -2.0) == 0.0); +} + +TEST_CASE("ai wire: the walk back asks for the places the 2 m steps give") { + std::vector asked; + auto const recording{[&asked](double const Distance) { + asked.push_back(Distance); + return Distance <= 100.0; + }}; + ai_wire::wire_shortfall(recording, 20.0, 130.0); + + // the pantograph's place and the margin ahead, then the steps back; the margin is asked only where the place is + // under the wire + std::vector const expected{110.0, 108.0, 106.0, 104.0, 102.0, 100.0, 103.0, 98.0, 101.0, 96.0, 99.0}; + CHECK(asked == expected); +} + +TEST_CASE("ai wire: which stops keep the pantograph under the wire") { + using ai_wire::stop_kind; + // the stops of a train that runs with the wire + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::track_end)); + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::timetable_stop)); + // a signal is a wait, the vehicle to couple to may stand without the wire + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::signal)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::coupling)); + // without a current collector, with the voltage made up, where the scenery says to coast or lower the pantographs + CHECK_FALSE(ai_wire::stops_under_wire(false, true, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, false, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, true, stop_kind::timetable_stop)); +} diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index b11253b49..cad1920a1 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -127,6 +127,7 @@ blackbox::cab_sample sample() { s.clutch = 0.75f; s.converter_fill = 0.25f; s.consist_brake_cylinder = 3.5f; + s.wheel_speed_kmh = 71.5f; return s; } @@ -285,6 +286,8 @@ TEST_CASE("blackbox: a sample of the user's train has the documented size and or CHECK(cab.get() == 0.25f); // the highest brake cylinder pressure of the train CHECK(cab.get() == 3.5f); + // the speed of the wheels + CHECK(cab.get() == 71.5f); CHECK(cab.done()); } diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 889beb338..f74edfc03 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -265,3 +265,81 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab unit.run(0.1); CHECK(ep_brake(unit, 0.0, 10.0) < 0.1); } + +// the Knorr St113 of the EN57 (TSt113, derived from TH14K1) over a service application, lap and release: its +// control chamber (GetCP), the brake pipe and the cylinder, against the values the code gave when the test was +// written, at 1e-9. a change of the handle's code which shouldn't alter anything has to keep them +namespace { + +struct st113_sample { + double cp; // the handle's control chamber + double pipe; // the brake pipe + double cylinder; + double ep; // the EP intensity the handle gives +}; + +std::vector st113_run() { + test::reseed_random(); + vehicle real{definition::fiz("en57_v1/6bai")}; + REQUIRE(real->BrakeHandle == TBrakeHandle::St113); + REQUIRE(real->Handle != nullptr); + real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + auto &handle{*real->Handle}; + std::vector samples; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->PipePress, real->BrakePress, handle.GetEP()}); }}; + auto const hold{[&](double Position, std::initializer_list Seconds) { + real->BrakeLevelSet(Position); + for (auto const seconds : Seconds) { + real.run(seconds); + sample(); + } + }}; + sample(); // before the first step: the chamber as Init left it + hold(handle.GetPos(bh_RP), {1.0, 30.0, 30.0}); // charged in the running position + hold(handle.GetPos(bh_MB), {1.0, 5.0}); // the first step of the service brake + hold(handle.GetPos(bh_FB), {1.0, 2.0, 5.0, 10.0}); // full service + hold(handle.GetPos(bh_NP), {5.0}); // lap + hold(handle.GetPos(bh_RP), {1.0, 5.0, 10.0, 30.0}); // released + hold(handle.GetPos(bh_EB), {1.0, 5.0}); // emergency + hold(handle.GetPos(bh_FS), {1.0, 3.0}); // filling stroke + hold(handle.GetPos(bh_RP), {10.0, 60.0}); // released again + return samples; +} + +} // namespace + +TEST_CASE("brake handles: the pressures of the Knorr St113 of the EN57 over an application and a release") { + // {control chamber, brake pipe, cylinder, EP} after each hold of st113_run(), as the code gave them + std::vector const expected{ + {0, 3.5, 6, 0}, + {4.9984786171489723, 4.9985239614132073, 3.8589217414374479, -1}, + {4.9987671731417445, 4.9988125312381184, 9.6079198677899244e-17, -1}, + {4.9991258752288621, 4.9991713394295099, 9.6079198677899244e-17, -1}, + {4.9533680060376426, 4.9530025463238161, 9.6079198677899244e-17, 0}, + {4.8311329228109479, 4.8310446333333399, 9.6079198677899244e-17, 0}, + {4.7310321436160523, 4.7325637973526726, 9.6079198677899244e-17, 0}, + {4.5872331917154092, 4.5890657213751611, 9.6079198677899244e-17, 0}, + {4.1778305377419631, 4.1793406294291415, 1.6739519661380537, 0}, + {3.355298669598576, 3.3569433138107754, 2.5006765921012648, 0}, + {3.340608574818968, 3.3406062128010463, 2.5006765921012648, 0}, + {4.9982940431020717, 4.9983393759288948, 1.805897475684926, -1}, + {4.9983349224059745, 4.9983802579817755, 0.096548127644583259, -1}, + {4.9984201641741199, 4.9984655050733862, 0.062980447840665657, -1}, + {4.9987011353434028, 4.998746490639209, 9.2221356484789066e-17, -1}, + {0.005419548331438478, 0.0049542946616295885, 2.0688047473966584, 0}, + {1.1051369154140042e-16, 1.1051359148828238e-16, 2.5210994451474482, 0}, + {7.9894372542519436, 7.9895176172361353, 1.9107481967960043, 0}, + {7.9894891501326404, 7.9895615214846529, 0.36406880055594204, 0}, + {6.2299691431411732, 6.2285260180794131, 0.068969473862745739, -1}, + {4.9988917107669719, 4.9989370736220264, 1.0102243333979078e-16, -1}, + }; + auto const samples{st113_run()}; + REQUIRE(samples.size() == expected.size()); + for (std::size_t i = 0; i < samples.size(); ++i) { + CAPTURE(i); + CHECK(samples[i].cp == doctest::Approx(expected[i].cp).epsilon(1e-9)); + CHECK(samples[i].pipe == doctest::Approx(expected[i].pipe).epsilon(1e-9)); + CHECK(samples[i].cylinder == doctest::Approx(expected[i].cylinder).epsilon(1e-9)); + CHECK(samples[i].ep == doctest::Approx(expected[i].ep).epsilon(1e-9)); + } +} diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 067e31037..295d722cd 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -355,13 +355,146 @@ TEST_CASE("odometer: two simulations saving one file keep each other's states") } CHECK(files == 1); } - SUBCASE("a store with nothing recorded since doesn't write") { + SUBCASE("a store with nothing recorded since doesn't write, once the file showed what it saved") { + REQUIRE(odometer::save(second, path)); write_file(path, "1 replaced by hand\n"); REQUIRE(odometer::save(second, path)); CHECK(load().size() == 1); } } +namespace { + +odometer::store load_store(std::filesystem::path const &Path) { + odometer::store store; + std::ifstream input{Path, std::ios::binary}; + store.read(input); + return store; +} + +// a comment line added to the file; a save that writes the file drops it +void mark(std::filesystem::path const &Path) { + std::ofstream{Path, std::ios::binary | std::ios::app} << "# not written since\n"; +} + +bool marked(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str().find("# not written since") != std::string::npos; +} + +// the save of Late reads the file before the save of Early writes it, and puts its own file in place after: Late +// writes the file as it was before Early's save, Early's states are gone from it +void interleave(odometer::store &Early, odometer::store &Late, std::filesystem::path const &Path) { + auto const view{Path.parent_path() / "late_view" / Path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(Path, view, std::filesystem::copy_options::overwrite_existing); + REQUIRE(odometer::save(Early, Path)); + REQUIRE(odometer::save(Late, view)); + std::filesystem::rename(view, Path); +} + +} // namespace + +TEST_CASE("odometer: a save another simulation's save put its file over is written again") { + scratch_directory directory{"odometer_lost_save"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + first.record("first only", run(70.0, 1000.0)); + second.record("second only", run(80.0, 1000.0)); + + interleave(second, first, path); + // the race of the two saves: the second one's state is gone from the file + REQUIRE_FALSE(load_store(path).find("second only").has_value()); + REQUIRE(load_store(path).find("first only").has_value()); + + // the second one's next save, nothing recorded since, finds the file without its state and writes it again + CHECK_FALSE(second.modified()); + REQUIRE(odometer::save(second, path)); + auto const saved{load_store(path)}; + CHECK(saved.size() == 3); + CHECK(saved.find("second only").value_or(0.0) == doctest::Approx(81.0)); + CHECK(saved.find("first only").value_or(0.0) == doctest::Approx(71.0)); + CHECK(saved.find("shared").value_or(0.0) == 1000.0); + + // both find their states in the file now: their next saves don't write it + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); + CHECK(load_store(path).size() == 3); +} + +TEST_CASE("odometer: two simulations with different states of a vehicle settle on the newer one") { + scratch_directory directory{"odometer_lost_save_conflict"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n~20000 guessed by both\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + // the first one ran the shared vehicle further, and the made up one further from its made up state; the second + // one has a known state of the made up one, from a cab's counter + first.record("shared", run(1000.0, 10000.0)); + second.record("shared", run(1000.0, 5000.0)); + odometer::reading guessed; + guessed.begin(20000.0, odometer::origin::guessed); + guessed.run(9000.0); + first.record("guessed by both", guessed); + odometer::reading seeded; + seeded.begin(300.0, odometer::origin::counter); + second.record("guessed by both", seeded); + + // the second one's save is lost to the first one's, which holds the made up state + interleave(second, first, path); + REQUIRE(load_store(path).guessed("guessed by both")); + + // the second one writes its known state again. the first one takes it, and the second one the larger state of + // the shared vehicle the first one saved + REQUIRE(odometer::save(second, path)); + REQUIRE(odometer::save(first, path)); + auto const settled{load_store(path)}; + CHECK(settled.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + CHECK(settled.find("guessed by both").value_or(0.0) == 300.0); + CHECK_FALSE(settled.guessed("guessed by both")); + CHECK(first.find("guessed by both").value_or(0.0) == 300.0); + CHECK(second.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + + // neither one keeps writing the file over to have its own state there + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); +} + +TEST_CASE("odometer: a save with nothing recorded since doesn't write the file again") { + scratch_directory directory{"odometer_saved_once"}; + auto const path{directory.path / "eu07_odometers.txt"}; + odometer::store store; + // states the file holds rounded to its digits + store.record("known", run(1000.0, 1234.56789)); + odometer::reading guessed; + guessed.begin(12345.678912, odometer::origin::guessed); + guessed.run(98.76543); + store.record("guessed", guessed); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(store.modified()); + + // the next save finds the file holding the states, rounded as they are: it doesn't write it + mark(path); + REQUIRE(odometer::save(store, path)); + CHECK(marked(path)); + // and the saves after it don't look at the file any more + std::filesystem::remove(path); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(std::filesystem::exists(path)); +} + TEST_CASE("odometer: a test run neither reads nor saves the player's store") { if (false == Global.test.enabled) CHECK(odometer::persistent()); diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp new file mode 100644 index 000000000..32fadec03 --- /dev/null +++ b/tests/unit/test_physicslog.cpp @@ -0,0 +1,385 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/physicslog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to + +namespace { + +// a folder of its own for the logs of a test, in the build folder of the tests, removed with the object. the writer +// makes it itself +class log_folder { +public: + explicit log_folder(std::string const &Name) : m_path{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / std::format("eu07_physicslog_test_{}", Name)} { + std::filesystem::remove_all(m_path); + } + ~log_folder() { + std::error_code error; + std::filesystem::remove_all(m_path, error); + } + log_folder(log_folder const &) = delete; + log_folder &operator=(log_folder const &) = delete; + + std::filesystem::path const &path() const { return m_path; } + // the log as it stands, read in text mode as it is written: what was given to it + std::string read(std::string const &Name) const { return read_file(m_path / (Name + ".dat")); } + static std::string read_file(std::filesystem::path const &File) { + std::ifstream file{File}; + if (false == file.is_open()) + return {}; + std::ostringstream text; + text << file.rdbuf(); + return text.str(); + } + // waits up to five seconds for the log to read Text + bool reads(std::string const &Name, std::string const &Text) const { + auto const until{std::chrono::steady_clock::now() + std::chrono::seconds{5}}; + while (read(Name) != Text && std::chrono::steady_clock::now() < until) + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + return read(Name) == Text; + } + +private: + std::filesystem::path m_path; +}; + +constexpr auto header{"Time[s] Velocity[m/s]\r\n"}; + +} // namespace + +TEST_CASE("physicslog: a log begun is emptied and given its header, and its lines follow it at each writing") { + log_folder folder{"begin"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EU07-424", header); + logs.append("EU07-424", "0.0500 0.0000\r\n"); + CHECK(folder.read("EU07-424").empty()); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EU07-424", "0.1000 1.5000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n0.1000 1.5000\r\n"); + + // begun again: the lines not written yet are dropped along with those written + logs.append("EU07-424", "0.1500 3.0000\r\n"); + logs.begin("EU07-424", header); + logs.flush(); + CHECK(folder.read("EU07-424") == header); +} + +TEST_CASE("physicslog: no file is kept open between the writings, and a log not begun is added to as it stands") { + log_folder folder{"closed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("SM42-001", header); + logs.flush(); + // Windows doesn't let a file open in a program be removed. Linux does, so there it checks nothing; the log is + // written again below anyway + std::error_code error; + CHECK(std::filesystem::remove(folder.path() / "SM42-001.dat", error)); + CHECK_FALSE(error); + + logs.append("SM42-001", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SM42-001") == "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: the thread writes the logs by itself") { + log_folder folder{"thread"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("ET22-001", header); + logs.append("ET22-001", "0.0500 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n")); + logs.append("ET22-001", "0.1000 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n")); +} + +TEST_CASE("physicslog: stopping writes what is kept at once, and what comes after waits for a writing") { + log_folder folder{"stop"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EN57-1001", header); + logs.append("EN57-1001", "0.0500 0.0000\r\n"); + logs.stop(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EN57-1001", "0.1000 0.0000\r\n"); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { + log_folder folder{"closingwait"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.stop(); + // the writing of the stop, left behind, is waited for by the writer going + } + CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); +} + +TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { + log_folder folder{"failed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a folder in the way of the file: it can't be opened, as one held by another program + std::filesystem::create_directories(folder.path() / "EU07-005.dat"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("EU07-005", "0.1000 0.5000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-005.dat")); + + std::filesystem::remove(folder.path() / "EU07-005.dat"); + logs.append("EU07-005", "0.1500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { + log_folder folder{"failedvalues"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values second; + second.time = 0.10; + physicslog_values last; + last.time = 0.20; + std::filesystem::create_directories(folder.path() / "EU07-008.dat"); + logs.begin("EU07-008", header); + logs.append("EU07-008", first); + logs.flush(); + // given while the file can't be written: after the lines kept, as text and as values + logs.append("EU07-008", second); + logs.append("EU07-008", "text\r\n"); + logs.append("EU07-008", last); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); + + std::filesystem::remove(folder.path() / "EU07-008.dat"); + logs.flush(); + auto const text{folder.read("EU07-008")}; + CHECK(text.starts_with(std::string{header} + "0.0500 ")); + CHECK(text.find("\r\n0.1000 ") != std::string::npos); + CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); + CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); +} + +TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { + // the logs of a writing as the writer has them, by their names + std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; + std::vector *> order; + for (auto &log : taken) + order.push_back(&log); + physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); + std::vector names; + for (auto const *log : order) + names.push_back(log->first); + CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); +} + +TEST_CASE("physicslog: a log put first is written as the others are") { + log_folder folder{"first"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.put_first("SM42-002"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.begin("SM42-002", header); + logs.append("SM42-002", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { + log_folder folder{"failedbegun"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + std::filesystem::remove(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 2.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == std::string{header} + "0.0500 2.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written doesn't keep the others from theirs") { + log_folder folder{"failedother"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "EU07-006.dat"); + logs.begin("EU07-006", header); + logs.append("EU07-006", "0.0500 0.0000\r\n"); + logs.begin("EU07-007", header); + logs.append("EU07-007", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-006.dat")); + CHECK(folder.read("EU07-007") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a vehicle named in the code page of its scenery has its log, whatever the code page of the system") { + log_folder folder{"codepage"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // "SM42-Łódź" in 1250, as the sceneries have it: not UTF-8, which a Windows set to it would have thrown on + std::string const name{"SM42-\xA3\xF3" "d\x9F"}; // apart, or the d would be read as a digit of the \xF3 + logs.begin(name, header); + logs.append(name, "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(logs.file(name).parent_path() == folder.path()); + CHECK(log_folder::read_file(logs.file(name)) == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what no file name may have on Windows is replaced in the name of the file, on every system") { + log_folder folder{"filename"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a spawned vehicle's name has a ':', which on NTFS would write into a stream of the file "spawn_ezt" + CHECK(logs.file("spawn_ezt:12").filename() == "spawn_ezt_12.dat"); + CHECK(logs.file("ac\"d/e\\f|g?h*i\tj").filename() == "a_b_c_d_e_f_g_h_i_j.dat"); + CHECK(logs.file("EN57-1001 'a'.2").filename() == "EN57-1001 'a'.2.dat"); + // the devices of Windows, with an extension too, aren't files + CHECK(logs.file("nul").filename() == "_nul.dat"); + CHECK(logs.file("Com1.2").filename() == "_Com1.2.dat"); + CHECK(logs.file("con ").filename() == "_con .dat"); + CHECK(logs.file("console").filename() == "console.dat"); + CHECK(logs.file("com0").filename() == "com0.dat"); + CHECK(logs.shown("spawn_ezt:12") == folder.path().generic_string() + "/spawn_ezt_12.dat"); + + logs.begin("spawn_ezt:12", header); + logs.append("spawn_ezt:12", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("spawn_ezt_12") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(false == std::filesystem::exists(folder.path() / "spawn_ezt")); +} + +TEST_CASE("physicslog: stopping twice, from two threads at once, writes once and ends") { + log_folder folder{"stoptwice"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("EP09-001", header); + logs.append("EP09-001", "0.0500 0.0000\r\n"); + { + std::jthread other{[&logs] { logs.stop(); }}; + logs.stop(); + } + CHECK(folder.read("EP09-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a flush with a time limit writes, as flush does") { + log_folder folder{"flushfor"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("ET41-001", header); + logs.append("ET41-001", "0.0500 0.0000\r\n"); + CHECK(logs.flush_for(std::chrono::seconds{1})); + CHECK(folder.read("ET41-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what is kept is written when the writer goes") { + log_folder folder{"end"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + logs.begin("ST44-001", header); + logs.append("ST44-001", "0.0500 0.0000\r\n"); + } + CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { + log_folder folder{"after"}; + std::filesystem::create_directories(folder.path()); + { + std::ofstream before{folder.path() / "SU45-001.dat"}; + before << "earlier run\n"; + } + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("SU45-001", "0.1000 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { + using namespace std::chrono_literals; + using duration = std::chrono::steady_clock::duration; + // quick: the interval + CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); + CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); + // a third of the interval: still the interval + CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); + // longer: three times the writing, the disk busy with the logs a quarter of the time + CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); + // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still + CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); +} + +TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { + log_folder folder{"values"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values line; + line.time = 0.05; + line.wheelspeed = 1.23456; + line.acceleration = -0.5; + line.mainctrl = 3; + line.direction = 1; + line.command = "ShuntVelocity"; + line.value1 = 40.0; + // a float of the vehicle, widened as the stream widened it + line.enginetemperature = 50.1f; + line.vehiclespeed = 36.0; + logs.begin("SM31-001", header); + logs.append("SM31-001", line); + logs.flush(); + CHECK(folder.read("SM31-001") == std::string{header} + + "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " + "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); +} + +TEST_CASE("physicslog: lines given as values and as text are written in the order given") { + log_folder folder{"order"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values last; + last.time = 0.15; + logs.append("EP09-001", first); + logs.append("EP09-001", "text\r\n"); + logs.append("EP09-001", last); + logs.flush(); + auto const text{folder.read("EP09-001")}; + CHECK(text.starts_with("0.0500 ")); + CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); +} diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index c4226da40..6add4f008 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -285,16 +285,16 @@ constexpr std::array flood_module{ TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") { sent_commands().clear(); script_folder const folder{"wasm_paint"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); REQUIRE(queue.runs(script_language::wasm)); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; REQUIRE(screen != nullptr); // the same key, the same screen - CHECK(queue.acquire(request(script_language::wasm, module, "cab", &texture)) == screen); + CHECK(queue.acquire(request(script_language::wasm, module_path, "cab", &texture)) == screen); refresh(queue, screen, speed(5.0), 42); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); })); @@ -321,13 +321,13 @@ TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to TEST_CASE("wasm screens: the image goes up again when the texture is made anew, and waits while it isn't there") { sent_commands().clear(); script_folder const folder{"wasm_reupload"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; texture.ready = false; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; refresh(queue, screen, speed(9.0), 1); REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); queue.update(); @@ -350,12 +350,12 @@ TEST_CASE("wasm screens: the image goes up again when the texture is made anew, TEST_CASE("wasm screens: a screen outside the cab draws, but its commands are dropped") { sent_commands().clear(); script_folder const folder{"wasm_sign"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "sign", &texture, script_screen_kind::external))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "sign", &texture, script_screen_kind::external))}; refresh(queue, screen, speed(3.0), 0); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); queue.update(); @@ -388,13 +388,13 @@ TEST_CASE("wasm screens: a screen stuck in a loop is stopped, and the others kee TEST_CASE("wasm screens: the screens outlive the queue without harm") { script_folder const folder{"wasm_outlive"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; std::shared_ptr screen; recording_texture texture; { script_screen_queue queue; REQUIRE(queue.init()); - screen = queue.acquire(request(script_language::wasm, module, "cab", &texture)); + screen = queue.acquire(request(script_language::wasm, module_path, "cab", &texture)); refresh(queue, screen, speed(4.0), 1); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); } diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 11acb9b8f..48d10e8b1 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -578,6 +578,56 @@ TEST_CASE("utilities: a file is found by its name in another case") { CHECK(FileCased("eu07_unit_test_no_such_file.xyz").empty()); } +TEST_CASE("utilities: a file is found in folders named in another case, the way the parser gives the names in lowercase") { + test::scratch_folder const folder{"utilities_cased_folders"}; + folder.write("Scenery/Braniewo/rozklady/Os91121.txt", "x"); + folder.write("Textures/Tabl/L101-2m.BMP", "x"); + + // every part of the path in lowercase: the file as it's on the disk where the case matters, the name given where it doesn't + auto const timetable{FileCased(folder.path("scenery/braniewo/rozklady/os91121.txt"))}; + REQUIRE_FALSE(timetable.empty()); + CHECK(std::filesystem::exists(timetable)); + CHECK(ToLower(timetable) == ToLower(folder.path("Scenery/Braniewo/rozklady/Os91121.txt"))); + CHECK(FileOnDisk(folder.path("scenery/braniewo/rozklady/os91121.txt")) == timetable); + // the folders written the Windows way as well + CHECK_FALSE(FileCased(folder.path() + "scenery\\braniewo\\rozklady\\os91121.txt").empty()); + // a folder missing in any case + CHECK(FileCased(folder.path("scenery/nowhere/rozklady/os91121.txt")).empty()); + CHECK(FileOnDisk(folder.path("scenery/nowhere/rozklady/os91121.txt")) == folder.path("scenery/nowhere/rozklady/os91121.txt")); + + // among names and extensions: found in any case, given back as named, the name being the key of the banks + auto const texture{FileExists(std::vector{folder.path("textures/tabl/l101-2m")}, std::vector{".dds", ".bmp"})}; + REQUIRE_FALSE(texture.first.empty()); + CHECK(texture.first == folder.path("textures/tabl/l101-2m")); + CHECK(texture.second == ".bmp"); + CHECK(std::filesystem::exists(FileOnDisk(texture.first + texture.second))); + + // a file written after the folder was gone through is found as well + CHECK(FileCased(folder.path("textures/tabl/l7-2m.bmp")).empty()); + folder.write("Textures/Tabl/L7-2m.bmp", "x"); + auto const added{FileCased(folder.path("textures/tabl/l7-2m.bmp"))}; + REQUIRE_FALSE(added.empty()); + CHECK(std::filesystem::exists(added)); +} + +TEST_CASE("utilities: a terrain file is found in another case, by its text or by its binary file") { + test::scratch_folder const folder{"utilities_cased_terrain"}; + folder.write("Scenery/L204/Teren/Woda_ter.txtf", "x"); + folder.write("Scenery/Nmt/Gory_ter.btf", "x"); + auto const scenery{folder.path("Scenery/")}; + std::vector const extensions{".txtf", ".btf"}; + + // the name as the parser gives it: the files are there under the name given back, which differs only in case + auto const text{FileStemOnDisk(scenery, "l204/teren/woda_ter", extensions)}; + CHECK(ToLower(text) == "l204/teren/woda_ter"); + CHECK(std::filesystem::exists(scenery + text + ".txtf")); + auto const binary{FileStemOnDisk(scenery, "nmt/gory_ter", extensions)}; + CHECK(ToLower(binary) == "nmt/gory_ter"); + CHECK(std::filesystem::exists(scenery + binary + ".btf")); + // neither file in any case: the name stays as given + CHECK(FileStemOnDisk(scenery, "nmt/nowhere_ter", extensions) == "nmt/nowhere_ter"); +} + TEST_CASE("utilities: the time a file was changed is given, zero for a file which isn't there") { test::scratch_folder const folder{"utilities_modified"}; auto const name{folder.write("fresh.txt", "x")}; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 957f9fc50..90c206dfa 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -220,6 +220,65 @@ bool global_settings::ConfigParseAudio(cParser& Parser, const std::string& token return true; } + return ConfigParseAudioDevice(Parser, token); +} + +bool global_settings::ConfigParseAudioDevice(cParser& Parser, const std::string& token) +{ + if (token == "sound.outputmode") + { + AudioOutputMode = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf") + { + AudioHrtf = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf.profile") + { + AudioHrtfProfile = Parser.getToken(false); + return true; + } + + if (token == "sound.resampler") + { + AudioResampler = Parser.getToken(false); + return true; + } + + if (token == "sound.limiter") + { + AudioLimiter = Parser.getToken(true); + return true; + } + + if (token == "sound.frequency") + { + ParseOneClamped(Parser, AudioFrequency, 0, 192000); + return true; + } + + if (token == "sound.doppler") + { + ParseOneClamped(Parser, AudioDoppler, 0.f, 10.f); + return true; + } + + if (token == "sound.efx.lowpass") + { + ParseOne(Parser, AudioLowpass); + return true; + } + + if (token == "sound.efx.airabsorption") + { + ParseOneClamped(Parser, AudioAirAbsorption, 0.f, 10.f); + return true; + } + return false; } @@ -322,6 +381,8 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to if (token == "gfxrenderer") { ParseOne(Parser, GfxRenderer); + // read in any case, as the starter does: "Legacy" written by hand is the legacy renderer + GfxRenderer = ToLower(GfxRenderer); if (GfxRenderer == "full") GfxRenderer = "default"; @@ -546,9 +607,18 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the physics logs of the trains only, of the drivers of rail vehicles; "physicslog yes" writes them all anyway + if (token == "physicslog.trains") + { + ParseOne(Parser, WriteTrainLogFlag); + return true; + } + if (token == "blackbox") { - ParseOne(Parser, BlackBox); + bool blackbox{false}; + ParseOne(Parser, blackbox); + BlackBox = blackbox; return true; } @@ -1802,8 +1872,21 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.volume.positional", EnvironmentPositionalVolume ); export_as_text( Output, "sound.volume.ambient", EnvironmentAmbientVolume ); export_as_text( Output, "sound.asyncload", AudioAsyncLoad ); + export_as_text( Output, "sound.maxsources", audio_max_sources ); + export_as_text( Output, "sound.outputmode", AudioOutputMode ); + export_as_text( Output, "sound.hrtf", AudioHrtf ); + export_as_text( Output, "sound.hrtf.profile", AudioHrtfProfile ); + export_as_text( Output, "sound.resampler", AudioResampler ); + export_as_text( Output, "sound.limiter", AudioLimiter ); + export_as_text( Output, "sound.frequency", AudioFrequency ); + export_as_text( Output, "sound.doppler", AudioDoppler ); + export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); + export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); - export_as_text( Output, "blackbox", BlackBox ); + export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + if( BlackBox ) { + export_as_text( Output, "blackbox", *BlackBox ); + } export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); diff --git a/utilities/Globals.h b/utilities/Globals.h index efd532c6a..ceb9948c4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,7 +119,9 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; - bool BlackBox{ true }; // with the physics logs on, the black box of the session is written as well (blackbox_doc.md) + // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" + // never, and with no entry it is written along with the physics logs + std::optional BlackBox; bool ShowSystemConsole{ false }; // toggle visibility of the OS console window with log output unsigned int DisabledLogTypes{ 0 }; bool ParserLogIncludes{ true }; @@ -231,6 +233,16 @@ struct global_settings { int audio_max_sources = 30; std::string AudioRenderer; bool AudioAsyncLoad{ false }; // sound files are decoded by worker threads + // OpenAL Soft device and mixing options; the defaults leave the choice to the library, as before they existed + std::string AudioOutputMode{ "auto" }; // sound.outputmode: auto, mono, stereo, stereo-basic, uhj, headphones, quad, 5.1, 6.1, 7.1 + std::string AudioHrtf{ "auto" }; // sound.hrtf: auto, on, off + std::string AudioHrtfProfile; // sound.hrtf.profile: name of the HRTF data set, empty for the library's choice + std::string AudioResampler; // sound.resampler: name of the resampler, empty for the library's default + std::string AudioLimiter{ "auto" }; // sound.limiter: auto, on, off + int AudioFrequency{ 0 }; // sound.frequency: mixing rate in Hz, 0 for the device's + float AudioDoppler{ 0.25f }; // sound.doppler: strength of the Doppler effect + bool AudioLowpass{ false }; // sound.efx.lowpass: soundproofing also muffles the high frequencies + float AudioAirAbsorption{ 0.f }; // sound.efx.airabsorption: 0-10, high frequencies fade with distance // input float fMouseXScale{ 1.5f }; float fMouseYScale{ 0.2f }; @@ -437,6 +449,7 @@ struct global_settings { void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); + bool ConfigParseAudioDevice(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); bool ConfigParseInput(cParser& Parser, const std::string& token); bool ConfigParseSimulation(cParser& Parser, const std::string& token); diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp new file mode 100644 index 000000000..d37ea69e7 --- /dev/null +++ b/utilities/physicslog.cpp @@ -0,0 +1,491 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/physicslog.h" +#include "utilities/Logs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#endif + +physicslog_writer PhysicsLogs; + +namespace { + +// the most of all the logs kept while their files can't be written, shared by those, a log never less than the +// least: the oldest lines go beyond it +constexpr std::size_t keptwhilefailing{64 * 1024 * 1024}; +constexpr std::size_t keptwhilefailingleast{64 * 1024}; + +// the text cut to its last lines within Most +void keep_last(std::string &Text, std::size_t const Most) { + if (Text.size() <= Most) + return; + auto const cut{Text.find('\n', Text.size() - Most)}; + Text.erase(0, cut == std::string::npos ? Text.size() : cut + 1); +} + +// the name of the file of the log Name, its extension too. what no file name may have on Windows is replaced, on every +// system, so the logs are named alike everywhere: a spawned vehicle is named :, and on NTFS "a:1.dat" +// isn't even an error but the stream 1.dat of the file a, which nothing lists +std::string file_name(std::string const &Name) { + std::string name{Name}; + for (auto &character : name) { + if (static_cast(character) < 0x20 || std::string_view{R"(<>:"/\|?*)"}.find(character) != std::string_view::npos) + character = '_'; + } + // a device rather than a file, with any extension: con.dat is the console. told by the name before its first dot + auto stem{name.substr(0, name.find('.'))}; + while (false == stem.empty() && stem.back() == ' ') + stem.pop_back(); + std::ranges::transform(stem, stem.begin(), [](unsigned char const Character) { return static_cast(std::toupper(Character)); }); + auto const numbered{stem.size() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem[3] >= '1' && stem[3] <= '9'}; + if (numbered || stem == "CON" || stem == "PRN" || stem == "AUX" || stem == "NUL") + name.insert(0, 1, '_'); + return name + ".dat"; +} + +// told in the log of the simulator, if there's the memory for it +void tell(std::string const &Text) noexcept { + try { + ErrorLog(Text); + } catch (...) { + // out of memory for a line of the log too: nothing more to be done about it + } +} + +// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the +// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking +// when there are hundreds of them +void lower_disk_priority() noexcept { +#ifdef _WIN32 + // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of + // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a + // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without + // end. a thread which can't have it writes as it did before + static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); +#elif defined(__linux__) && defined(SYS_ioprio_set) + // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the + // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has + constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 + constexpr int classbesteffort{2}; + constexpr int classshift{13}; + constexpr int lowest{7}; + static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); +#endif +} + +} // namespace + +void physicslog_values::append_to(std::string &Text) const { + std::ostringstream line; + line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " + << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " + << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " + << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " + << wateraux << " " << vehiclespeed << "\r\n"; + Text.append(line.str()); +} + +void physicslog_writer::pending::to_text() { + if (values.empty()) + return; + // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was + std::string lines; + for (auto const &line : values) + line.append_to(lines); + text.append(lines); + values.clear(); +} + +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} + +physicslog_writer::~physicslog_writer() { + try { + stop(); + // the writings left behind by the stops use the object, which goes + std::vector> closings; + { + std::scoped_lock lock{m_mutex}; + closings.swap(m_closings); + } + for (auto const &closing : closings) + closing.wait(); + } catch (...) { + // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse + } +} + +void physicslog_writer::begin(std::string const &Name, std::string_view const Header) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + lines.fresh = true; + lines.header.assign(Header); + lines.text.clear(); + lines.values.clear(); + start(); +} + +void physicslog_writer::append(std::string const &Name, std::string_view const Line) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + // after the lines given as values before it + lines.to_text(); + lines.text.append(Line); + start(); +} + +void physicslog_writer::append(std::string const &Name, physicslog_values Values) { + std::scoped_lock lock{m_mutex}; + m_pending[Name].values.push_back(std::move(Values)); + start(); +} + +void physicslog_writer::put_first(std::string const &Name) { + std::scoped_lock lock{m_mutex}; + m_first.insert(Name); +} + +void physicslog_writer::flush() { + std::scoped_lock files{m_filemutex}; + write(writing::flush); +} + +bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { + // on a thread of its own, left behind if it doesn't end in time: a disk which doesn't answer holds it up in the + // writing, not only the lock. for the end of the process, which doesn't wait for it + auto done{std::make_shared>()}; + auto ended{done->get_future()}; + std::thread([this, done] { + flush_safely(writing::flush); + done->set_value(); + }).detach(); + return ended.wait_for(Timeout) == std::future_status::ready; +} + +void physicslog_writer::stop() { + std::jthread thread; + bool itself; + closing_time closeby; + { + std::scoped_lock lock{m_mutex}; + m_stopped = true; + // taken by the first to stop, so it's joined once + thread = std::move(m_thread); + itself = m_writer == std::this_thread::get_id(); + // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun + // ends at the log at hand, leaving the others to it + closeby = closing_begun(); + } + // the stop asked outside the lock, which waking the writer takes + if (thread.joinable()) + thread.request_stop(); + // stopped from the writer itself, by the end of a run which failed in it: the files may be held by it + if (itself) { + if (thread.joinable()) + thread.detach(); + return; + } + if (close_aside(thread, closeby)) + return; + // no thread for it, out of memory say: written here, the logs past the time dropped all the same + if (thread.joinable()) + thread.join(); + flush_safely(writing::closing); +} + +physicslog_writer::closing_time physicslog_writer::closing_begun() { + std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); + // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the + // longer, nor give the writing of the first more of it + if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) + return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; + auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; + m_closeby = closeby.time_since_epoch().count(); + return {closeby, true}; +} + +bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { + // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which + // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, + // the writing with it + auto started{false}; + try { + auto done{std::make_shared>()}; + std::shared_future const closing{done->get_future()}; + { + std::scoped_lock lock{m_mutex}; + m_closings.push_back(closing); + } + // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it + std::thread([this, done, writer = std::move(Thread)]() mutable { + if (writer.joinable()) + writer.join(); + flush_safely(writing::closing); + done->set_value(); + }).detach(); + started = true; + // told by the stop which gave the time, not again by one after it + if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) + tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", + std::chrono::duration{m_closingwait}.count())); + return true; + } catch (...) { + // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun + // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it + return started; + } +} + +std::filesystem::path physicslog_writer::file(std::string const &Name) const { + auto const name{file_name(Name)}; +#ifdef _WIN32 + // in the code page of the system, as the standard library would convert it, but with the bytes not of it replaced + // instead of an exception thrown: a vehicle of a scenery written in 1250 on a Windows set to UTF-8, say + auto const size{static_cast(name.size())}; + std::wstring wide(static_cast(::MultiByteToWideChar(CP_ACP, 0, name.data(), size, nullptr, 0)), L'\0'); + ::MultiByteToWideChar(CP_ACP, 0, name.data(), size, wide.data(), static_cast(wide.size())); + return m_folder / wide; +#else + // the bytes are the name of the file as they are + return m_folder / name; +#endif +} + +std::string physicslog_writer::shown(std::string const &Name) const { + return m_shownfolder + '/' + file_name(Name); +} + +std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { + // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the + // waits growing with no end, and a crash would lose more of them + return std::clamp(Took * 3, Interval, Interval * 5); +} + +void physicslog_writer::start() { + if (m_stopped || m_thread.joinable()) + return; + m_thread = std::jthread([this](std::stop_token const &Stop) { run(Stop); }); + m_writer = m_thread.get_id(); +} + +void physicslog_writer::run(std::stop_token const &Stop) { + lower_disk_priority(); + // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is + // either about to wait, and sees the stop, or waiting already + std::stop_callback const wake{Stop, [this] { + { std::scoped_lock lock{m_mutex}; } + m_wake.notify_all(); + }}; + std::chrono::steady_clock::duration wait{m_interval}; + while (false == Stop.stop_requested()) { + { + std::unique_lock lock{m_mutex}; + // woken early only to stop, which writes the rest itself + if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + return; + } + auto const start{std::chrono::steady_clock::now()}; + // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's + auto const logs{flush_safely(writing::thread)}; + auto const took{std::chrono::steady_clock::now() - start}; + wait = wait_after(m_interval, took); + if (wait > m_interval && false == m_slowtold) { + m_slowtold = true; + using seconds = std::chrono::duration; + try { + WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " + "written less often from now on, every {:.1f} s at most", + logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); + } catch (...) { + // out of memory for a line of the log: the logs are written all the same + } + } + } +} + +std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { + try { + std::scoped_lock files{m_filemutex}; + return write(Mode); + } catch (std::exception const &Error) { + tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); + } catch (...) { + tell("Bad physics log: the writing failed, the lines taken for it are lost"); + } + return 0; +} + +bool physicslog_writer::past_closing() const { + auto const closeby{m_closeby.load()}; + return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; +} + +void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; + for (auto &[name, lines] : Failed) { + // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as + // text they go before what came since + try { + lines.to_text(); + } catch (std::exception const &) { + // kept as values, below + } + keep_last(lines.text, most); + } + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : Failed) + put_back(name, lines); + for (auto *log : Left) + put_back(log->first, log->second); +} + +void physicslog_writer::put_back(std::string const &Name, pending &Lines) { + auto &now{m_pending[Name]}; + // a log begun anew since drops them + if (now.fresh) + return; + // the lines in the order given: those kept, then those come since, as text and as values. values kept before text + // come since are made into text first, as those before a line given as text are; values which can't be, out of + // memory, are dropped then, as the order can't be kept otherwise + if (false == now.text.empty() && false == Lines.values.empty()) { + try { + Lines.to_text(); + } catch (std::exception const &) { + Lines.values.clear(); + } + } + Lines.text.append(now.text); + // added at once, allocated first: one failing moves none of them + if (Lines.values.empty()) + Lines.values = std::move(now.values); + else + Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); + now = std::move(Lines); +} + +std::size_t physicslog_writer::write(writing const Mode) { + std::map taken; + std::set first; + std::vector *> order; + { + std::scoped_lock lock{m_mutex}; + if (m_pending.empty()) + return 0; + // a stop come before the thread's writing: the lines are all the closing's, left as they are + if (Mode == writing::thread && m_closeby.load() != 0) + return 0; + // had before the lines are taken: without the memory for it they're left for the next writing + first = m_first; + order.reserve(m_pending.size()); + taken.swap(m_pending); + } + auto const logs{taken.size()}; + std::error_code error; + std::filesystem::create_directories(m_folder, error); + std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); + writing_order(order, first); + std::map failed; + std::size_t dropped{0}; + std::size_t reached{0}; + for (auto *log : order) { + // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has + // them with the lines given since, those put first first + if (Mode == writing::thread && m_closeby.load() != 0) + break; + ++reached; + auto &[name, lines]{*log}; + // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer + if (Mode == writing::closing && past_closing()) { + ++dropped; + continue; + } + if (false == write_taken(name, lines)) + failed.emplace(name, std::move(lines)); + } + if (dropped > 0) + tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, + std::chrono::duration{m_closingwait}.count())); + // what is left of the order: the logs the thread hasn't come to + order.erase(order.begin(), order.begin() + static_cast(reached)); + if (false == failed.empty() || false == order.empty()) + keep(failed, order); + return logs; +} + +bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + // the text of the lines given as values, here on the writer's thread rather than the simulation's + Lines.to_text(); + if (Lines.text.empty() && false == Lines.fresh) + return true; + written = write_log(Name, Lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(Name) > 0) + WriteLog("Physics log: " + shown(Name) + " written again"); + return true; + } + if (m_failed.insert(Name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); + return false; +} + +bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { + auto const path{file(Name)}; + // one write to the file: the header of a log begun with its lines, not the one after the other + std::string begun; + if (Lines.fresh) + begun = Lines.header + Lines.text; + std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". + // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines + // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't + // asked for the length before, one access less of hundreds of logs + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; + if (false == stream.is_open()) + return false; + auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; + stream.write(text.data(), static_cast(text.size())); + stream.close(); + if (false == stream.fail()) + return true; + // a log begun is written anew from its header the next time anyway + if (false == Lines.fresh && before >= 0) { + std::error_code error; + std::filesystem::resize_file(path, static_cast(before), error); + } + return false; +} diff --git a/utilities/physicslog.h b/utilities/physicslog.h new file mode 100644 index 000000000..286df7e87 --- /dev/null +++ b/utilities/physicslog.h @@ -0,0 +1,189 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which +// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty +// lines a second each. the columns as physicslog_header of the driver names them +struct physicslog_values { + double time{0.0}; + double wheelspeed{0.0}; + double acceleration{0.0}; + double couplerdistance{0.0}; + double couplerforce{0.0}; + double tractionforce{0.0}; + double frictionforce{0.0}; + double brakeforce{0.0}; + double brakepressure{0.0}; + double pipepressure{0.0}; + double motorcurrent{0.0}; + int mainctrl{0}; + int scndctrl{0}; + double brakectrl{0.0}; + double localbrake{0.0}; + int direction{0}; + std::string command; + double value1{0.0}; + double value2{0.0}; + int security{0}; + int wheelslip{0}; + double enginetemperature{0.0}; + double oiltemperature{0.0}; + double watertemperature{0.0}; + double wateraux{0.0}; + double vehiclespeed{0.0}; + + // the line, as the logs always had it, at the end of Text + void append_to(std::string &Text) const; +}; + +// the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's +// has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, +// each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk +// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next +// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the +// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind +// them. the closing waits for the writing a second at most (below) +class physicslog_writer { +public: + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, + std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + physicslog_writer(physicslog_writer const &) = delete; + physicslog_writer &operator=(physicslog_writer const &) = delete; + // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, + // global, never goes this way: the process ends with _Exit + ~physicslog_writer(); + + // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. + // the lines of it not written yet are dropped + void begin(std::string const &Name, std::string_view Header); + // Line at the end of the log Name. a log not begun is added to as its file stands + void append(std::string const &Name, std::string_view Line); + // the same, a line of the values, made into text by the writer's thread when it writes the log + void append(std::string const &Name, physicslog_values Values); + // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the + // tested trains, which a closing short of time would otherwise drop by the order of their names + void put_first(std::string const &Name); + // writes what is kept, now + void flush(); + // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left + // behind. for the end of the process, the files held up or the disk not answering + bool flush_for(std::chrono::milliseconds Timeout); + // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by + // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a + // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with + // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + void stop(); + // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name + // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a + // scenery (1250) stay as they are, also on a Windows set to UTF-8, where the standard library would throw making a + // path of them: there they become U+FFFD + std::filesystem::path file(std::string const &Name) const; + // the same, for the log of the simulator + std::string shown(std::string const &Name) const; + // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long + // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the + // logs a quarter of the time rather than all of it, and their lines wait in memory the longer + static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); + // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: + // those put first (First) before the others, each in the order they were + template static void writing_order(std::vector &Logs, std::set const &First) { + std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); + } + +private: + // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the + // closing's, which drops the logs past the time the stop gives it + enum class writing { flush, thread, closing }; + + // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way + struct closing_time { + std::chrono::steady_clock::time_point by; + bool fresh{true}; + }; + + struct pending { + bool fresh{false}; // its file is to be emptied first, and the header written into it + std::string header; + std::string text; + // the lines given as values since, after the text: made into text when written + std::vector values; + + // the lines of the values at the end of the text + void to_text(); + }; + + // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held + closing_time closing_begun(); + // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no + // thread could be had for it, out of memory say; Thread may be the writer still then + bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; + // the thread, on the first line given, unless stopped. called with m_mutex held + void start(); + void run(std::stop_token const &Stop); + // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. + // returns: the number of logs there were to write + std::size_t flush_safely(writing Mode) noexcept; + // called with m_filemutex held. returns: the number of logs there were to write + std::size_t write(writing Mode); + // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if + // it wasn't, its lines to be kept for the next try + bool write_taken(std::string const &Name, pending &Lines); + // whether the time a stop gave the writing is over + bool past_closing() const; + // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, + // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as + // they were taken: their values are made into text by that writing, which drops them past its time, not on the way + // unless text was given since + void keep(std::map &Failed, std::vector *> const &Left); + // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held + void put_back(std::string const &Name, pending &Lines); + // the lines of the log Name written into its file. returns: true if they all were + bool write_log(std::string const &Name, pending const &Lines) const; + + std::filesystem::path const m_folder; + std::string const m_shownfolder; + std::chrono::milliseconds const m_interval; + std::chrono::milliseconds const m_closingwait; + // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop + std::atomic m_closeby{0}; + std::mutex m_mutex; // the lines kept and the thread + std::map m_pending; + std::set m_first; // the logs put first + bool m_stopped{false}; + std::condition_variable m_wake; + std::jthread m_thread; + std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it + std::vector> m_closings; // the writings of the stops, which may outlast them + std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order + std::set m_failed; // the logs whose file couldn't be written, told once + bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own +}; + +// the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles +extern physicslog_writer PhysicsLogs; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 238e276f5..edc694852 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -633,6 +633,140 @@ bool FileExists(std::string const &Filename) return std::filesystem::exists(Filename); } +#ifndef _WIN32 +namespace +{ + +// the names in a folder by their lowercase, the time the folder was changed and the time they were read +struct cased_folder +{ + bool read{false}; + std::filesystem::file_time_type changed{}; + std::filesystem::file_time_type listed{}; + // when the time of the change was last looked at + std::chrono::steady_clock::time_point checked{}; + std::unordered_map names; +}; + +std::mutex cased_mutex; +std::unordered_map cased_folders; +// a folder by the name it's given with (parts split by '/', a '/' at the end): as it's named on the disk, or missing in any case +// since the time given +struct cased_path +{ + std::string name; + bool missing{false}; + std::chrono::steady_clock::time_point checked{}; +}; +std::unordered_map cased_paths; + +// the names in the folder into Cached by their lowercase, with the time the folder was changed and the time they were read. a named +// function rather than a lambda capturing Cached, which Sonar takes for a reference to null (S2259) +void read_cased_folder(cased_folder &Cached, std::filesystem::path const &Folder, std::filesystem::file_time_type const Changed) +{ + Cached.names.clear(); + Cached.changed = Changed; + Cached.listed = std::filesystem::file_time_type::clock::now(); + std::error_code error; + for (std::filesystem::directory_iterator entry{Folder, error}, end; (false == bool(error)) && (entry != end); entry.increment(error)) + { + auto const name{entry->path().filename().string()}; + Cached.names.try_emplace(ToLower(name), name); + } + // a listing cut short isn't kept + Cached.read = (false == bool(error)); +} + +// the name in the folder matching the one given in any case, empty when there's none. the folder is read again once it was +// changed, as the editor writes files while it runs, the time of the change looked at once a second at most, which keeps a +// missing file as cheap as a single check; a name missing from a folder changed shortly before it was read is looked for again, +// the time of the change being as coarse as the clock of the file system. to be called with cased_mutex held +std::string cased_name(std::string const &Folder, std::string const &Name) +{ + std::filesystem::path const folder{Folder.empty() ? std::string{"."} : Folder}; + std::error_code error; + auto &cached{cased_folders[Folder]}; + auto const now{std::chrono::steady_clock::now()}; + auto changed{cached.changed}; + if ((false == cached.read) || (now - cached.checked >= std::chrono::seconds{1})) + { + changed = std::filesystem::last_write_time(folder, error); + if (error) + { + // a folder found before may have been renamed or removed since + cased_folders.erase(Folder); + cased_paths.clear(); + return {}; + } + cached.checked = now; + } + auto const wanted{ToLower(Name)}; + if ((false == cached.read) || (cached.changed != changed)) + read_cased_folder(cached, folder, changed); + auto found{cached.names.find(wanted)}; + // a folder changed in the future, as from another clock, isn't read again on every miss + if (auto const age{cached.listed - cached.changed}; (found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) + { + read_cased_folder(cached, folder, changed); + found = cached.names.find(wanted); + } + return found != cached.names.end() ? found->second : std::string{}; +} + +// keeps the folder by the name it's given with as Name, or as missing since the time given when Name is empty, and puts Name into +// Cased; false when it's missing +bool keep_cased_path(std::string const &Folder, std::string const &Name, std::chrono::steady_clock::time_point const Now, std::string &Cased) +{ + auto &path{cased_paths[Folder]}; + path.name = Name; + path.missing = Name.empty(); + path.checked = Now; + Cased = Name; + return false == Name.empty(); +} + +// the folder as it's named on the disk into Cased, from the one given with '/' between its parts and at its end ("" the current +// folder); false when it's missing in any case. the folders found are kept, and the missing ones for a second, so a file missing +// costs a check of its folder alone. to be called with cased_mutex held +bool cased_folder_path(std::string const &Folder, std::string &Cased) +{ + if (Folder.empty() || (Folder == "/")) + { + Cased = Folder; + return true; + } + auto const now{std::chrono::steady_clock::now()}; + if (auto const found{cased_paths.find(Folder)}; found != cased_paths.end()) + { + if (false == found->second.missing) + { + Cased = found->second.name; + return true; + } + if (now - found->second.checked < std::chrono::seconds{1}) + return false; + } + std::error_code error; + if (std::filesystem::is_directory(Folder, error)) + { + // named as it is on the disk + return keep_cased_path(Folder, Folder, now, Cased); + } + // the parent, then the last part among the names in it + auto const last{Folder.size() - 1}; + auto const split{Folder.rfind('/', last - 1)}; + auto const parent{split == std::string::npos ? std::string{} : Folder.substr(0, split + 1)}; + auto const part{Folder.substr(parent.size(), last - parent.size())}; + std::string casedparent; + if (false == cased_folder_path(parent, casedparent)) + return keep_cased_path(Folder, {}, now, Cased); + auto const name{((part == ".") || (part == "..")) ? part : cased_name(casedparent, part)}; + return keep_cased_path(Folder, name.empty() ? std::string{} : casedparent + name + '/', now, Cased); +} + +} // namespace +#endif + std::string FileCased(std::filesystem::path const &Filename) { std::error_code error; @@ -643,16 +777,59 @@ std::string FileCased(std::filesystem::path const &Filename) // code page to throw on return {}; #else - // only the name of the file itself, a folder named in another case isn't found - auto const directory{Filename.has_parent_path() ? Filename.parent_path() : std::filesystem::path{"."}}; - auto const wanted{ToLower(Filename.filename().string())}; - for (std::filesystem::directory_iterator entry{directory, error}, end; entry != end; entry.increment(error)) - if (ToLower(entry->path().filename().string()) == wanted) - return Filename.has_parent_path() ? (directory / entry->path().filename()).string() : entry->path().filename().string(); - return {}; + // the folder, then the file in it: the folders can be named in another case as well as the file + auto text{Filename.string()}; + std::replace(text.begin(), text.end(), '\\', '/'); + std::string folder{(false == text.empty()) && (text.front() == '/') ? "/" : ""}; + std::string file; + for (std::size_t start{0}; start < text.size();) + { + auto end{text.find('/', start)}; + if (end == std::string::npos) + end = text.size(); + if (end > start) + { + if (false == file.empty()) + folder += file + '/'; + file = text.substr(start, end - start); + } + start = end + 1; + } + if (file.empty()) + return {}; + std::string cased; + { + std::scoped_lock const lock{cased_mutex}; + if (false == cased_folder_path(folder, cased)) + return {}; + auto const name{((file == ".") || (file == "..")) ? file : cased_name(cased, file)}; + if (name.empty()) + return {}; + cased += name; + } + return std::filesystem::exists(cased, error) ? cased : std::string{}; #endif } +std::string FileOnDisk(std::string const &Filename) +{ + auto cased{FileCased(Filename)}; + return cased.empty() ? Filename : cased; +} + +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions) +{ + for (auto const &extension : Extensions) + { + auto const cased{FileCased(Folder + Name + extension)}; + if (cased.size() > Folder.size() + extension.size() && cased.starts_with(Folder) && cased.ends_with(extension)) + { + return cased.substr(Folder.size(), cased.size() - Folder.size() - extension.size()); + } + } + return Name; +} + std::pair FileExists(std::vector const &Names, std::vector const &Extensions) { @@ -660,7 +837,8 @@ std::pair FileExists(std::vector const &N { for (auto const &extension : Extensions) { - if (FileExists(name + extension)) + // found in any case, given back as named here: the name stays the key of the banks, the file is opened by FileOnDisk() + if (false == FileCased(name + extension).empty()) { return {name, extension}; } diff --git a/utilities/utilities.h b/utilities/utilities.h index 7e3a227f1..25ee3882c 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -233,10 +233,17 @@ template bool extract_value(Type_ &Variable, std::string const template <> bool extract_value(bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default); bool FileExists(std::string const &Filename); -// the file as it's named on the disk when only the case of its name differs, as in the sceneries made on Windows; empty when -// there's none. the folders have to be named in their case; on Windows, finding the names in any case itself, the file given or none +// the file as it's named on the disk when only the case of its name or of its folders differs, as in the sceneries made on Windows; +// empty when there's none. on Windows, finding the names in any case itself, the file given or none std::string FileCased(std::filesystem::path const &Filename); +// the file to open: as it's named on the disk, the name given when there's none +std::string FileOnDisk(std::string const &Filename); +// the name (relative to the folder, without extension) as it's named on the disk with the first of the extensions it has a file with, +// found in any case; the name given when there's none +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions); +// the first name with one of the extensions which has a file in any case, in the order given; given back as named here, the file +// is opened by FileOnDisk() std::pair FileExists(std::vector const &Names, std::vector const &Extensions); // returns time of last modification for specified file diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index bfa0e70c7..2b3633433 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" @@ -170,6 +171,7 @@ const double FSOverchargeCRP = 0.05; const double FSMaxTime = 10.0; const double DepartBlockedFSDelay = 10.0; bool WriteLogFlag = false; +bool WriteTrainLogFlag = false; double const deltalog = 0.05; // przyrost czasu std::string StopReasonTable[] = { @@ -2339,33 +2341,16 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd } - SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + if( mvOccupied != nullptr ) { + SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + } TableClear(); - if( WriteLogFlag ) { -#ifdef _WIN32 - CreateDirectory( "physicslog", nullptr); -#elif __unix__ - mkdir( "physicslog", 0740 ); -#endif - LogFile.open( std::string( "physicslog/" + VehicleName + ".dat" ), - std::ios::in | std::ios::out | std::ios::trunc ); -#if LOGPRESS == 0 - LogFile - << "Time[s] Velocity[m/s] Acceleration[m/ss] " - << "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " - << "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " - << "MCP SCP BCP LBP Direction Command CVal1 CVal2 " - << "Security Wheelslip " - << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " - << "VehicleVelocity[km/h]" - << "\r\n"; - LogFile << std::fixed << std::setprecision( 4 ); -#endif -#if LOGPRESS == 1 - LogFile << string( "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP" ).c_str() << "\n"; -#endif - LogFile.flush(); + // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line + // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles + // are made passive before it starts, so they get no file with only the header + if( WriteLogFlag && false == drives_road_vehicle() ) { + begin_physicslog(); } // HACK: give the simulation a small window to potentially replace the AI with a human driver @@ -2374,7 +2359,6 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, TController::~TController() { // wykopanie mechanika z roboty - // LogFile is closed by its own destructor }; // zamiana kodu rozkazu na opis @@ -5390,58 +5374,80 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N return false; // nierozpoznana - wysłać bezpośrednio do pojazdu }; -void TController::PhysicsLog() -{ // zapis logu - na razie tylko wypisanie parametrów - if (LogFile.is_open()) - { +std::string_view TController::physicslog_header() { + // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: + // a new one goes at the end + return "Time[s] Velocity[m/s] Acceleration[m/ss] " + "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " + "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " + "MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip " + "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + "VehicleVelocity[km/h]" + "\r\n"; +} + +physicslog_values TController::physicslog_line() const { + // the values only: the writer of the logs makes them into text on its own thread + physicslog_values line; + line.time = ElapsedTime; + line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); + line.acceleration = mvControlling->AccS; + line.couplerdistance = mvOccupied->Couplers[1].Dist; + line.couplerforce = mvOccupied->Couplers[1].CForce; + line.tractionforce = mvOccupied->Ft; + line.frictionforce = mvOccupied->Ff; + line.brakeforce = mvOccupied->Fb; + line.brakepressure = mvOccupied->BrakePress; + line.pipepressure = mvOccupied->PipePress; + line.motorcurrent = mvControlling->Im; + line.mainctrl = static_cast(mvControlling->MainCtrlPos); + line.scndctrl = static_cast(mvControlling->ScndCtrlPos); + line.brakectrl = mvOccupied->fBrakeCtrlPos; + line.localbrake = mvOccupied->LocalBrakePosA; + line.direction = static_cast(mvControlling->DirActive); + line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); + line.value1 = mvOccupied->CommandIn.Value1; + line.value2 = mvOccupied->CommandIn.Value2; + line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); + line.wheelslip = static_cast(mvControlling->SlippingWheels); + // floats, as the stream wrote them: widened to double + line.enginetemperature = mvControlling->dizel_heat.Ts; + line.oiltemperature = mvControlling->dizel_heat.To; + line.watertemperature = mvControlling->dizel_heat.temperatura1; + line.wateraux = mvControlling->dizel_heat.temperatura2; + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + line.vehiclespeed = mvOccupied->V * 3.6; + return line; +} + +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers #if LOGPRESS == 0 -/* -<< "Time[s] Velocity[m/s] Acceleration[m/ss] " -<< "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " -<< "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " -<< "MCP SCP BCP LBP DmgFlag Command CVal1 CVal2 " -<< "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]" -*/ - LogFile - << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " - << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " - << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << mvOccupied->V * 3.6 - << "\r\n"; + PhysicsLogs.begin( VehicleName, physicslog_header() ); #endif #if LOGPRESS == 1 - LogFile << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) - << "\t"; - LogFile << Controlling->AccS << "\t"; - LogFile << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - LogFile << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); +#endif + PhysicsLogBegun = true; +} + +void TController::PhysicsLog() +{ // zapis logu - na razie tylko wypisanie parametrów +#if LOGPRESS == 0 + PhysicsLogs.append( VehicleName, physicslog_line() ); +#endif +#if LOGPRESS == 1 + std::ostringstream line; + line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) + << "\t"; + line << mvControlling->AccS << "\t"; + line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" + << mvOccupied->BrakePress << "\t"; + line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.append( VehicleName, line.str() ); #endif - LogFile.flush(); - } }; void @@ -6392,6 +6398,10 @@ void TController::ControllingSet() // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT + if( pVehicle == nullptr ) { + // a driver of no vehicle has nothing to control + return; + } mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego @@ -6493,10 +6503,18 @@ TController::update_timers( double dt ) { void TController::update_logs( double const dt ) { // log vehicle data + if( false == writes_physicslog() ) { + // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, + // it would write a line every 0.05 s from then on, not one each update to make up for the time before + LastUpdatedTime = 0.0; + return; + } LastUpdatedTime += dt; - if( WriteLogFlag - && LastUpdatedTime > deltalog ) { + if( LastUpdatedTime > deltalog ) { // zapis do pliku DAT + if( false == PhysicsLogBegun ) { + begin_physicslog(); + } PhysicsLog(); LastUpdatedTime -= deltalog; } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 8aabf06e1..739ab8342 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include "utilities/Classes.h" #include "utilities/utilities.h" #include "MOVER.h" @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" +#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -197,6 +199,9 @@ static const bool Humandriver = false; static const int maxorders = 64; // ilość rozkazów w tabelce static const int maxdriverfails = 4; // ile błędów może zrobić AI zanim zmieni nastawienie extern bool WriteLogFlag; // logowanie parametrów fizycznych +// the physics logs of the trains only (physicslog.trains yes): of each driver of rail vehicles who drives them, not +// of the passengers nor of the vehicles of the roads +extern bool WriteTrainLogFlag; static const int BrakeAccTableSize = 20; static const int gbh_NP = -2; //odciecie w hamulcu ogolnym @@ -728,9 +733,12 @@ private: // logs // methods + // the line of the log, to PhysicsLogs (utilities/physicslog.h) void PhysicsLog(); + // its log begun anew, its file emptied and given the header + void begin_physicslog(); // members - std::ofstream LogFile; // zapis parametrow fizycznych + bool PhysicsLogBegun = false; // its log was begun, by this driver double LastUpdatedTime = 0.0; // czas od ostatniego logu double ElapsedTime = 0.0; // czas od poczatku logu @@ -738,6 +746,22 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } + // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with + // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. + // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + std::string const &physicslog_name() const { + return VehicleName; } + // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with + // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of + // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes + // the log of one the user is in + bool writes_physicslog() const { + return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } + // a driver of a road vehicle; not one of no vehicle + bool drives_road_vehicle() const { + return mvOccupied != nullptr && is_car(); } + static std::string_view physicslog_header(); + physicslog_values physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 6289fe5a2..c99448eed 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -211,15 +211,15 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu m_sourcemodel = nullptr; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { - // got what we wanted, bail out - m_sourcemodel = source; - break; + if( source == nullptr ) { + continue; } - // there's a possibility the default submodel was named with _off suffix - if( source != nullptr - && ( submodel = source->GetFromName( submodelname + "_off" ) ) != nullptr ) { + submodel = source->GetFromName( submodelname ); + if( submodel == nullptr ) { + // there's a possibility the default submodel was named with _off suffix + submodel = source->GetFromName( submodelname + "_off" ); + } + if( submodel != nullptr ) { // got what we wanted, bail out m_sourcemodel = source; break; @@ -231,8 +231,11 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu // see if we can locate optional submodel for active state, with _on suffix TSubModel *submodelon { nullptr }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodelon = source->GetFromName( submodelname + "_on" ) ) != nullptr ) { + if( source == nullptr ) { + continue; + } + submodelon = source->GetFromName( submodelname + "_on" ); + if( submodelon != nullptr ) { // got what we wanted, bail out break; } diff --git a/vehicle/aiwire.cpp b/vehicle/aiwire.cpp new file mode 100644 index 000000000..999d69075 --- /dev/null +++ b/vehicle/aiwire.cpp @@ -0,0 +1,78 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/aiwire.h" + +#include + +namespace ai_wire { + +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth) { + // Winger 170204: the parameter of the span's point in the plane of the pantograph's movement (the plane normal to + // Front through Point). the operations and their order are those the vehicles always had, so they find the same wire + auto const paramfrontdot = glm::dot(Parametric, Front); + auto const parameter = -(glm::dot(Point1, Front) - glm::dot(Point, Front)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + + contact result; + if (parameter < -0.001 || parameter > 1.001) { + return result; + } + // the point where the wire crosses the plane, against the pantograph + auto const crossing = Point1 + parameter * Parametric; + auto const offset = crossing - Point; + result.within = true; + result.vertical = glm::dot(offset, Up); + result.horizontal = std::abs(glm::dot(offset, Left)) - Halfwidth; + return result; +} + +bool reaches(contact const &Contact, double const Minheight, double const Maxheight) { + return Contact.within && Contact.horizontal <= 0.0 && Contact.vertical >= Minheight && Contact.vertical <= Maxheight; +} + +double wire_shortfall(std::function const &Covered, double const Pantograph, double const Stop, + double const Margin, double const Step, double const Walkback) { + if (!Covered || Step <= 0.0) { + return 0.0; + } + auto const fine{[&](double const Place) { return Covered(Place) && Covered(Place + Margin); }}; + // the pantograph at the target of the head + auto const target{Stop - Pantograph}; + if (fine(target)) { + return 0.0; + } + // the places back are counted from the target, not added up, so the steps don't drift + auto const steps{static_cast(std::floor(Walkback / Step + 1e-9))}; + for (int step = 1; step <= steps; ++step) { + auto const back{step * Step}; + if (fine(target - back)) { + return back; + } + } + return 0.0; +} + +bool stops_under_wire(bool const Collector, bool const Livetraction, bool const Overheadrestricted, stop_kind const Kind) { + if (!Collector || !Livetraction || Overheadrestricted) { + return false; + } + switch (Kind) { + case stop_kind::track_end: + case stop_kind::timetable_stop: + return true; + case stop_kind::signal: + case stop_kind::coupling: + default: + return false; + } +} + +} // namespace ai_wire diff --git a/vehicle/aiwire.h b/vehicle/aiwire.h new file mode 100644 index 000000000..89ccb1ecc --- /dev/null +++ b/vehicle/aiwire.h @@ -0,0 +1,75 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include + +// where the overhead contact wire is, for the AI driver to stop its train with the pantograph under the wire, not past +// the end of it. the geometry of a pantograph against a span of the wire is the one the vehicles use to find their wire +// (basic_cell::update_traction), so the AI sees the wire where the pantographs do +namespace ai_wire { + +// a pantograph against one span of the wire +struct contact { + // the plane of the pantograph's movement (across the vehicle, at the pantograph) cuts the span, between its ends + bool within{false}; + // height of the wire above the pantograph's base point, along the up vector. negative for a wire below it + double vertical{0.0}; + // sideways distance of the wire from the working part of the slide: |offset along the left vector| less the slide's + // half width. the wire is on the slide when it's not positive + double horizontal{0.0}; +}; + +// the pantograph with its base point at Point, on a vehicle whose front, up and left vectors are Front, Up and Left, and +// a slide of half width Halfwidth, against the span from Point1 along Parametric (the span's other end is Point1 + +// Parametric). for a span parallel to the plane of the pantograph's movement the distance to the plane is divided by +// 0.001 in place of 0 (the division by zero trap the vehicles always had), which puts the crossing outside the span +// unless the span lies in the plane +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double Halfwidth); + +// the span is a wire the pantograph can reach: it crosses the plane of the pantograph's movement on the slide, between +// Minheight and Maxheight above the pantograph's base point. the heights keep out the wires of the bridges above the +// line and of the lines below it +bool reaches(contact const &Contact, double Minheight, double Maxheight); + +// the default margin of wire ahead of the pantograph at a stop, the step and the farthest distance back the stop is +// looked for under the wire, in metres +double const stop_margin{3.0}; +double const stop_step{2.0}; +double const stop_walk_back{300.0}; + +// how far short of its target a train has to stop so its pantograph stays under the wire, in metres along the route. +// the distances are along the route from the head of the train: Stop the target of the head, Pantograph the pantograph +// the train relies on (the rearmost one it raises) behind the head. Covered tells whether there's a wire over the +// route at the given distance. the pantograph at the stop is fine when there's wire over it and Margin ahead of it; +// otherwise it's moved back by Step at a time, up to Walkback, to the first place it's fine at. 0 when it's fine at the +// target, and when no place within Walkback is (not an electrified stretch, or a gap too long to tell about: stopping +// short won't help there) +double wire_shortfall(std::function const &Covered, double Pantograph, double Stop, + double Margin = stop_margin, double Step = stop_step, double Walkback = stop_walk_back); + +// what makes the train stop at a place +enum class stop_kind { + track_end, // the end of the track, e.g. a buffer stop, in train or shunting mode + timetable_stop, // a stop of the timetable (W4 indicator) + signal, // a signal at stop + coupling, // a vehicle to couple to or to uncouple from +}; + +// the train stops with its pantograph under the wire. not when it runs without the wire: without a current collector, +// with the voltage made up (livetraction off), on a stretch the scenery tells to coast or to run with the pantographs +// down. not for a signal (a wait, the wire ending before a signal is a fault of the scenery) and not for a coupling +// (the vehicle to couple to may stand on a siding without the wire) +bool stops_under_wire(bool Collector, bool Livetraction, bool Overheadrestricted, stop_kind Kind); + +} // namespace ai_wire diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index 8612df1bd..fc05f7483 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -205,6 +205,7 @@ void writer::cab(cab_sample const &Sample) { out.f32(Sample.clutch); out.f32(Sample.converter_fill); out.f32(Sample.consist_brake_cylinder); + out.f32(Sample.wheel_speed_kmh); emit(record::cab); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 58735ff60..55ee06ca3 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -257,6 +257,9 @@ struct cab_sample { float clutch{0.0f}; // the clutch of a diesel's gearbox, 0 open .. 1 closed float converter_fill{0.0f}; // the filling of a diesel's hydraulic torque converter, 0..1 float consist_brake_cylinder{0.0f}; // the highest brake cylinder pressure of the vehicles of the train [bar] + // [km/h] of the wheels as they turn, which the speedometer shows, signed as speed_kmh: apart from it while the wheels + // slip, and 0 while they are locked in a skid + float wheel_speed_kmh{0.0f}; }; // a station of the timetable of the user's train; the times in minutes of the day, -1 none @@ -354,7 +357,7 @@ struct signal_passing { // sizes of the parts of fixed size, as the readers expect them inline constexpr std::size_t header_size{12}; inline constexpr std::size_t record_header_size{5}; -inline constexpr std::size_t cab_sample_size{190}; +inline constexpr std::size_t cab_sample_size{194}; inline constexpr std::size_t vehicle_state_size{25}; // writes the records to a stream. nothing is written until header() is diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 8f98cb084..484998e40 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -176,6 +176,13 @@ void store::merge(store const &Other) { } } +bool store::holds(store const &Other) const { + return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { + auto const lookup{m_states.find(Entry.first)}; + return lookup != m_states.end() && false == newer(Entry.second, lookup->second); + }); +} + std::optional read_legacy(std::istream &Input) { std::stringstream content; content << Input.rdbuf(); @@ -277,8 +284,21 @@ store &states() { return odometers; } +namespace { + +// the states as the file holds them once written, the km rounded to the digits written +store as_written(store const &States) { + std::stringstream text; + States.write(text); + store result; + result.read(text); + return result; +} + +} // namespace + bool save(store &States, std::filesystem::path const &File) { - if (false == States.modified()) + if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; if (File.has_parent_path()) @@ -286,11 +306,19 @@ bool save(store &States, std::filesystem::path const &File) { // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they // saved since this one read it is merged in, not overwritten { + store saved; std::ifstream input{File, std::ios::binary}; - if (input.is_open()) { - store saved; + if (input.is_open()) saved.read(input); - States.merge(saved); + States.merge(saved); + // another simulation that read the file before the last save of this one and put its own in place after it + // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write + if (false == States.modified()) { + if (saved.holds(as_written(States))) { + States.confirmed(); + return true; + } + WriteLog("Odometer states saved to \"" + File.string() + "\" are missing from it, saving them again"); } } // written aside first, a crash in the middle of a write doesn't lose the states. the file aside is this process' diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 9708311f4..c7aa0950f 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -46,10 +46,19 @@ public: // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles void merge(store const &Other); + // this store holds every state of the other one, the same or a newer one + bool holds(store const &Other) const; // there are states recorded since they were last saved bool modified() const { return m_modified; } - void saved() { m_modified = false; } + // the states were written to the file. until a later save finds them there (confirmed()), they may have been lost to + // another simulation's save, which read the file before this one wrote it and put its own in place after + void saved() { + m_modified = false; + m_unconfirmed = true; + } + bool unconfirmed() const { return m_unconfirmed; } + void confirmed() { m_unconfirmed = false; } std::size_t size() const { return m_states.size(); } private: @@ -62,6 +71,7 @@ private: std::map m_states; bool m_modified{false}; + bool m_unconfirmed{false}; }; // the vehicle is one the store keeps: one with a driver's cab, which can show its odometer on the cab's counter or a @@ -113,8 +123,9 @@ bool persistent(); store &states(); std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the -// file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the -// write failed +// file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, +// the file is read once more after a write, and written again when it lacks any of the states (another simulation's +// save put its file over this one's); otherwise left as it is. returns false when the write failed bool save(store &States, std::filesystem::path const &File); // saves the store of the simulation to its file. a test run doesn't save it bool save(); diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 041a25134..83221d696 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -49,13 +49,13 @@ void perfgraph_panel::render_contents() { if (!stopwatch) return; - history[pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); - const std::string label = std::to_string(history[pos]) + "ms"; + history[history_pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); + const std::string label = std::to_string(history[history_pos]) + "ms"; - pos++; - if (pos >= history.size()) - pos = 0; + history_pos++; + if (history_pos >= history.size()) + history_pos = 0; ImGui::SliderFloat(STR_C("Range"), &max, 0.1f, 250.0f); - ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); + ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(history_pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); } diff --git a/widgets/perfgraphs.h b/widgets/perfgraphs.h index d3ddb3c6d..961f98fcd 100644 --- a/widgets/perfgraphs.h +++ b/widgets/perfgraphs.h @@ -3,7 +3,7 @@ class perfgraph_panel : public ui_panel { std::array history = { 0 }; - size_t pos = 0; + size_t history_pos = 0; enum timers_e { gfx_total = 0, diff --git a/world/Road.cpp b/world/Road.cpp index 26b458c16..79fc54f84 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -875,7 +875,7 @@ glm::dvec3 road_node::state::tangent(double const T) const road_node::road_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} // restores content of the node from provided input stream; reads up to and including the closing 'endroad' -void road_node::import(cParser &Input, glm::dvec3 const &Offset) +void road_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const label{m_name.empty() ? std::string{"unnamed road"} : "road \"" + m_name + "\""}; @@ -2307,7 +2307,7 @@ std::vector junction_node::state::outline(std::vector roadpoint_node::parse_vehicles(std::st } // restores content of the node from provided input stream; reads up to and including the closing statement -void roadpoint_node::import(cParser &Input, glm::dvec3 const &Offset) +void roadpoint_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const type{keyword(m_state.kind)}; auto const label{type + " \"" + m_name + "\""}; diff --git a/world/RoadPoint.h b/world/RoadPoint.h index 3ad45b4c3..670eb0fb1 100644 --- a/world/RoadPoint.h +++ b/world/RoadPoint.h @@ -97,7 +97,7 @@ class roadpoint_node : public scene::basic_node explicit roadpoint_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing statement - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/Sweep.cpp b/world/Sweep.cpp index 31587fe7d..9c5638cf3 100644 --- a/world/Sweep.cpp +++ b/world/Sweep.cpp @@ -404,7 +404,7 @@ bool sweep_node::state::operator==(state const &Other) const sweep_node::sweep_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} -void sweep_node::import(cParser &Input, glm::dvec3 const &Offset) +void sweep_node::import_from(cParser &Input, glm::dvec3 const &Offset) { m_state = state{}; m_state.model = Input.getToken(); diff --git a/world/Sweep.h b/world/Sweep.h index 2e65f5fa9..b83b7fa12 100644 --- a/world/Sweep.h +++ b/world/Sweep.h @@ -91,7 +91,7 @@ class sweep_node : public scene::basic_node explicit sweep_node(scene::node_data const &Nodedata); - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); void define(state const &State); state const &definition() const { diff --git a/world/mtable.cpp b/world/mtable.cpp index ce10eaafd..23a48e3a7 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -310,6 +310,15 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach // (kolejny pociąg dostaje numer +2) fin.open(s.c_str()); // otwieranie pliku + if (false == fin.is_open()) + { + // the name of the train comes in lowercase, the file can be named in another case + if (auto const cased{FileCased(s)}; false == cased.empty()) + { + fin.clear(); + fin.open(cased); + } + } replace_slashes(s); if (!fin.is_open())