From 2acc8213eff67d11dcb6e529f462b5be23f224e8 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 20 Sep 2026 15:14:36 +0200 Subject: [PATCH 01/58] Enhance Windows build matrix with AVX2 variants --- .github/workflows/build_bin.yml | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index f0b1fdec9..8c900b8f5 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -28,9 +28,20 @@ jobs: # ============================================================ windows: - name: Windows x64 / MSVC + name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@v6 @@ -74,11 +85,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 @@ -106,7 +119,7 @@ jobs: - name: Upload Windows build uses: actions/upload-artifact@v4 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 @@ -115,7 +128,7 @@ jobs: - name: Upload Windows debug symbols uses: actions/upload-artifact@v4 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 From cb777e760da8eddd341e091ffc320407e7746d68 Mon Sep 17 00:00:00 2001 From: maj00r Date: Wed, 11 Nov 2026 21:49:17 +0100 Subject: [PATCH 02/58] fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint --- lang/editor_pl.po | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/lang/editor_pl.po b/lang/editor_pl.po index c85232dc6..74ca66800 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -12233,15 +12233,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" From d0a36946579ad55e27b7748c14293bcd4cf42660 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 15:41:40 +0100 Subject: [PATCH 03/58] fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case --- audio/audio.cpp | 4 +- editor/editorPreviews.cpp | 4 +- model/Model3d.cpp | 17 ++++--- model/Texture.cpp | 16 +++--- tests/unit/test_utilities.cpp | 32 ++++++++++++ utilities/utilities.cpp | 96 ++++++++++++++++++++++++++++++++--- utilities/utilities.h | 5 +- world/mtable.cpp | 9 ++++ 8 files changed, 157 insertions(+), 26 deletions(-) diff --git a/audio/audio.cpp b/audio/audio.cpp index 3be2810d1..c9aa56675 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -216,9 +216,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() ); } } 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/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..e09e8c8ab 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -549,13 +549,15 @@ opengl_texture::load() { data_state = resource_state::loading; - if( type == ".dds" ) { load_DDS(); } - else if( type == ".tga" ) { load_TGA(); } - else if( type == ".png" ) { load_STBI(); } - else if( type == ".ktx" ) { load_KTX(); } - else if( type == ".bmp" ) { load_STBI(); } - else if( type == ".jpg" ) { load_STBI(); } - else if( type == ".tex" ) { load_TEX(); } + // the extension as the file has it on the disk, in any case + auto const format { ToLower( type ) }; + if( format == ".dds" ) { load_DDS(); } + else if( format == ".tga" ) { load_TGA(); } + else if( format == ".png" ) { load_STBI(); } + else if( format == ".ktx" ) { load_KTX(); } + else if( format == ".bmp" ) { load_STBI(); } + else if( format == ".jpg" ) { load_STBI(); } + else if( format == ".tex" ) { load_TEX(); } else { goto fail; } } diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index f04d9e34a..b8ad0b95c 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -578,6 +578,38 @@ 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(FileExists(timetable)); + CHECK(ToLower(timetable) == ToLower(folder.path("Scenery/Braniewo/rozklady/Os91121.txt"))); + CHECK(FileExists(folder.path("scenery/braniewo/rozklady/os91121.txt"))); + // 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_FALSE(FileExists(folder.path("scenery/nowhere/rozklady/os91121.txt"))); + + // among names and extensions: given back as named on the disk, so it's opened by that name, the extension too + auto const texture{FileExists(std::vector{folder.path("textures/tabl/l101-2m")}, std::vector{".dds", ".bmp"})}; + REQUIRE_FALSE(texture.first.empty()); + CHECK(ToLower(texture.second) == ".bmp"); + CHECK(FileExists(texture.first + texture.second)); + CHECK(ToLower(texture.first) == ToLower(folder.path("Textures/Tabl/L101-2m"))); + + // 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(FileExists(added)); +} + 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/utilities.cpp b/utilities/utilities.cpp index 550ad016a..85b40d330 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -513,9 +513,55 @@ template <> bool extract_value(bool &Variable, std::string const &Key, std::stri bool FileExists(std::string const &Filename) { +#ifdef _WIN32 return std::filesystem::exists(Filename); +#else + // the names come in lowercase from the parser, the files of the data are named in any case + return false == FileCased(Filename).empty(); +#endif } +#ifndef _WIN32 +namespace +{ + +// the names in a folder by their lowercase, and the time the folder was changed when they were read +struct cased_folder +{ + std::filesystem::file_time_type changed{}; + std::unordered_map names; +}; + +std::mutex cased_mutex; +std::unordered_map cased_folders; + +// 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. 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 const changed{std::filesystem::last_write_time(folder, error)}; + if (error) + return {}; + auto &cached{cased_folders[Folder]}; + if (cached.names.empty() || cached.changed != changed) + { + cached.changed = changed; + cached.names.clear(); + 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); + } + } + auto const found{cached.names.find(ToLower(Name))}; + return found != cached.names.end() ? found->second : std::string{}; +} + +} // namespace +#endif + std::string FileCased(std::filesystem::path const &Filename) { std::error_code error; @@ -526,13 +572,40 @@ 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 {}; + // every part of the path in turn, the folders can be named in another case as well as the file + auto const text{Filename.string()}; + std::string cased; + std::size_t start{0}; + if ((false == text.empty()) && (text.front() == '/')) + { + cased = "/"; + start = 1; + } + while (start < text.size()) + { + auto end{text.find_first_of("/\\", start)}; + if (end == std::string::npos) + end = text.size(); + auto const part{text.substr(start, end - start)}; + start = end + 1; + if (part.empty()) + continue; + if ((part == ".") || (part == "..") || std::filesystem::exists(cased + part, error)) + { + cased += part; + } + else + { + std::scoped_lock const lock{cased_mutex}; + auto const name{cased_name(cased, part)}; + if (name.empty()) + return {}; + cased += name; + } + if (end < text.size()) + cased += '/'; + } + return std::filesystem::exists(cased, error) ? cased : std::string{}; #endif } @@ -543,10 +616,19 @@ std::pair FileExists(std::vector const &N { for (auto const &extension : Extensions) { +#ifdef _WIN32 if (FileExists(name + extension)) { return {name, extension}; } +#else + // given back as it's named on the disk, so it's opened by that name + if (auto const cased{FileCased(name + extension)}; cased.size() >= extension.size()) + { + auto const split{cased.size() - extension.size()}; + return {cased.substr(0, split), cased.substr(split)}; + } +#endif } } // nothing found diff --git a/utilities/utilities.h b/utilities/utilities.h index 748c4c8d9..2e347b933 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -222,10 +222,11 @@ 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 first name with one of the extensions which has a file, in the order given, as the file is named on the disk std::pair FileExists(std::vector const &Names, std::vector const &Extensions); // returns time of last modification for specified file diff --git a/world/mtable.cpp b/world/mtable.cpp index 123ae00f6..0ac08bc20 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -277,6 +277,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()) From afbc84c6bc9d5d06584d0ac6e43cef44f220dd23 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 15:47:52 +0100 Subject: [PATCH 04/58] fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept --- audio/audio.cpp | 3 ++- model/Texture.cpp | 28 ++++++++++---------- scripting/PyInt.cpp | 2 +- tests/unit/test_utilities.cpp | 16 ++++++------ utilities/utilities.cpp | 48 ++++++++++++++++++++--------------- utilities/utilities.h | 5 +++- 6 files changed, 55 insertions(+), 47 deletions(-) diff --git a/audio/audio.cpp b/audio/audio.cpp index c9aa56675..ad53d95de 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"); diff --git a/model/Texture.cpp b/model/Texture.cpp index e09e8c8ab..96fb3778d 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -549,15 +549,13 @@ opengl_texture::load() { data_state = resource_state::loading; - // the extension as the file has it on the disk, in any case - auto const format { ToLower( type ) }; - if( format == ".dds" ) { load_DDS(); } - else if( format == ".tga" ) { load_TGA(); } - else if( format == ".png" ) { load_STBI(); } - else if( format == ".ktx" ) { load_KTX(); } - else if( format == ".bmp" ) { load_STBI(); } - else if( format == ".jpg" ) { load_STBI(); } - else if( format == ".tex" ) { load_TEX(); } + if( type == ".dds" ) { load_DDS(); } + else if( type == ".tga" ) { load_TGA(); } + else if( type == ".png" ) { load_STBI(); } + else if( type == ".ktx" ) { load_KTX(); } + else if( type == ".bmp" ) { load_STBI(); } + else if( type == ".jpg" ) { load_STBI(); } + else if( type == ".tex" ) { load_TEX(); } else { goto fail; } } @@ -642,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; @@ -820,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 @@ -940,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; @@ -1002,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 @@ -1063,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 ); @@ -1110,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 ]; 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/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index b8ad0b95c..45a919568 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -586,28 +586,28 @@ TEST_CASE("utilities: a file is found in folders named in another case, the way // 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(FileExists(timetable)); + CHECK(std::filesystem::exists(timetable)); CHECK(ToLower(timetable) == ToLower(folder.path("Scenery/Braniewo/rozklady/Os91121.txt"))); - CHECK(FileExists(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_FALSE(FileExists(folder.path("scenery/nowhere/rozklady/os91121.txt"))); + CHECK(FileOnDisk(folder.path("scenery/nowhere/rozklady/os91121.txt")) == folder.path("scenery/nowhere/rozklady/os91121.txt")); - // among names and extensions: given back as named on the disk, so it's opened by that name, the extension too + // 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(ToLower(texture.second) == ".bmp"); - CHECK(FileExists(texture.first + texture.second)); - CHECK(ToLower(texture.first) == ToLower(folder.path("Textures/Tabl/L101-2m"))); + 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(FileExists(added)); + CHECK(std::filesystem::exists(added)); } TEST_CASE("utilities: the time a file was changed is given, zero for a file which isn't there") { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 85b40d330..deb63f2bd 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -513,22 +513,19 @@ template <> bool extract_value(bool &Variable, std::string const &Key, std::stri bool FileExists(std::string const &Filename) { -#ifdef _WIN32 return std::filesystem::exists(Filename); -#else - // the names come in lowercase from the parser, the files of the data are named in any case - return false == FileCased(Filename).empty(); -#endif } #ifndef _WIN32 namespace { -// the names in a folder by their lowercase, and the time the folder was changed when they were read +// 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{}; std::unordered_map names; }; @@ -536,7 +533,8 @@ std::mutex cased_mutex; std::unordered_map cased_folders; // 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. to be called with cased_mutex held +// changed, as the editor writes files while it runs; 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}; @@ -545,17 +543,27 @@ std::string cased_name(std::string const &Folder, std::string const &Name) if (error) return {}; auto &cached{cased_folders[Folder]}; - if (cached.names.empty() || cached.changed != changed) - { - cached.changed = changed; + auto const wanted{ToLower(Name)}; + auto const read{[&]() { cached.names.clear(); + cached.changed = changed; + cached.listed = std::filesystem::file_time_type::clock::now(); 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)); + }}; + if ((false == cached.read) || (cached.changed != changed)) + read(); + auto found{cached.names.find(wanted)}; + if ((found == cached.names.end()) && (cached.listed - cached.changed < std::chrono::seconds{2})) + { + read(); + found = cached.names.find(wanted); } - auto const found{cached.names.find(ToLower(Name))}; return found != cached.names.end() ? found->second : std::string{}; } @@ -609,6 +617,12 @@ std::string FileCased(std::filesystem::path const &Filename) #endif } +std::string FileOnDisk(std::string const &Filename) +{ + auto cased{FileCased(Filename)}; + return cased.empty() ? Filename : cased; +} + std::pair FileExists(std::vector const &Names, std::vector const &Extensions) { @@ -616,19 +630,11 @@ std::pair FileExists(std::vector const &N { for (auto const &extension : Extensions) { -#ifdef _WIN32 - 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}; } -#else - // given back as it's named on the disk, so it's opened by that name - if (auto const cased{FileCased(name + extension)}; cased.size() >= extension.size()) - { - auto const split{cased.size() - extension.size()}; - return {cased.substr(0, split), cased.substr(split)}; - } -#endif } } // nothing found diff --git a/utilities/utilities.h b/utilities/utilities.h index 2e347b933..d15e03234 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -225,8 +225,11 @@ bool FileExists(std::string const &Filename); // 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 first name with one of the extensions which has a file, in the order given, as the file is named on the disk +// 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 From a30b5f30e156cd0804f0148be5c550708f78c2a6 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 15:49:41 +0100 Subject: [PATCH 05/58] fix(files): a folder changed in the future isn't read again on every name missing from it --- utilities/utilities.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index deb63f2bd..6b869236e 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -559,7 +559,9 @@ std::string cased_name(std::string const &Folder, std::string const &Name) if ((false == cached.read) || (cached.changed != changed)) read(); auto found{cached.names.find(wanted)}; - if ((found == cached.names.end()) && (cached.listed - cached.changed < std::chrono::seconds{2})) + // a folder changed in the future, as from another clock, isn't read again on every miss + auto const age{cached.listed - cached.changed}; + if ((found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) { read(); found = cached.names.find(wanted); From 1e5b09515039aa81471553b3616196e82cb5aab9 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:18:27 +0100 Subject: [PATCH 06/58] perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. --- utilities/utilities.cpp | 133 ++++++++++++++++++++++++++++++---------- 1 file changed, 100 insertions(+), 33 deletions(-) diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 6b869236e..fbccbab6a 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -526,23 +526,46 @@ 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 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; 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 +// 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 const changed{std::filesystem::last_write_time(folder, error)}; - if (error) - return {}; 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)}; auto const read{[&]() { cached.names.clear(); @@ -569,6 +592,53 @@ std::string cased_name(std::string const &Folder, std::string const &Name) return found != cached.names.end() ? found->second : std::string{}; } +// 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; + } + auto const keep{[&](std::string const &Name) { + auto &path{cased_paths[Folder]}; + path.name = Name; + path.missing = Name.empty(); + path.checked = now; + Cased = Name; + return false == Name.empty(); + }}; + std::error_code error; + if (std::filesystem::is_directory(Folder, error)) + { + // named as it is on the disk + return keep(Folder); + } + // 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({}); + auto const name{((part == ".") || (part == "..")) ? part : cased_name(casedparent, part)}; + return keep(name.empty() ? std::string{} : casedparent + name + '/'); +} + } // namespace #endif @@ -582,38 +652,35 @@ std::string FileCased(std::filesystem::path const &Filename) // code page to throw on return {}; #else - // every part of the path in turn, the folders can be named in another case as well as the file - auto const text{Filename.string()}; - std::string cased; - std::size_t start{0}; - if ((false == text.empty()) && (text.front() == '/')) + // 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();) { - cased = "/"; - start = 1; - } - while (start < text.size()) - { - auto end{text.find_first_of("/\\", start)}; + auto end{text.find('/', start)}; if (end == std::string::npos) end = text.size(); - auto const part{text.substr(start, end - start)}; + if (end > start) + { + if (false == file.empty()) + folder += file + '/'; + file = text.substr(start, end - start); + } start = end + 1; - if (part.empty()) - continue; - if ((part == ".") || (part == "..") || std::filesystem::exists(cased + part, error)) - { - cased += part; - } - else - { - std::scoped_lock const lock{cased_mutex}; - auto const name{cased_name(cased, part)}; - if (name.empty()) - return {}; - cased += name; - } - if (end < text.size()) - cased += '/'; + } + 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 From f9b7e9174c7dcf3818cb01d6da06379e512add58 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 16:34:06 +0100 Subject: [PATCH 07/58] fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. --- simulation/simulationstateserializer.cpp | 2 ++ tests/unit/test_utilities.cpp | 18 ++++++++++++++++++ utilities/utilities.cpp | 13 +++++++++++++ utilities/utilities.h | 3 +++ 4 files changed, 36 insertions(+) diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..0a8670c4e 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -1200,6 +1200,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/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 45a919568..f8cd9a290 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -610,6 +610,24 @@ TEST_CASE("utilities: a file is found in folders named in another case, the way 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/utilities.cpp b/utilities/utilities.cpp index fbccbab6a..d7406f3bc 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -692,6 +692,19 @@ std::string FileOnDisk(std::string const &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) { diff --git a/utilities/utilities.h b/utilities/utilities.h index d15e03234..09c02d7fb 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -227,6 +227,9 @@ bool FileExists(std::string const &Filename); 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() From d76e6368b06ba17a2f107ab38a9815f0796ba32a Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 17:49:18 +0100 Subject: [PATCH 08/58] fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. --- model/MdlMngr.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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; } } From 38540d08f53b0b1d8f2be7b9aeea91153d997838 Mon Sep 17 00:00:00 2001 From: maj00r Date: Fri, 13 Nov 2026 17:49:18 +0100 Subject: [PATCH 09/58] refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. --- utilities/utilities.cpp | 62 +++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index d7406f3bc..d704fe9b7 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -543,6 +543,23 @@ struct cased_path }; 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, @@ -567,31 +584,30 @@ std::string cased_name(std::string const &Folder, std::string const &Name) cached.checked = now; } auto const wanted{ToLower(Name)}; - auto const read{[&]() { - cached.names.clear(); - cached.changed = changed; - cached.listed = std::filesystem::file_time_type::clock::now(); - 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)); - }}; if ((false == cached.read) || (cached.changed != changed)) - read(); + 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 - auto const age{cached.listed - cached.changed}; - if ((found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) + if (auto const age{cached.listed - cached.changed}; (found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) { - read(); + 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 @@ -613,19 +629,11 @@ bool cased_folder_path(std::string const &Folder, std::string &Cased) if (now - found->second.checked < std::chrono::seconds{1}) return false; } - auto const keep{[&](std::string const &Name) { - auto &path{cased_paths[Folder]}; - path.name = Name; - path.missing = Name.empty(); - path.checked = now; - Cased = Name; - return false == Name.empty(); - }}; std::error_code error; if (std::filesystem::is_directory(Folder, error)) { // named as it is on the disk - return keep(Folder); + 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}; @@ -634,9 +642,9 @@ bool cased_folder_path(std::string const &Folder, std::string &Cased) auto const part{Folder.substr(parent.size(), last - parent.size())}; std::string casedparent; if (false == cased_folder_path(parent, casedparent)) - return keep({}); + return keep_cased_path(Folder, {}, now, Cased); auto const name{((part == ".") || (part == "..")) ? part : cased_name(casedparent, part)}; - return keep(name.empty() ? std::string{} : casedparent + name + '/'); + return keep_cased_path(Folder, name.empty() ? std::string{} : casedparent + name + '/', now, Cased); } } // namespace From 0488519f39e320d8aa17de544cf3886a6869eeb0 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:04:54 +0100 Subject: [PATCH 10/58] fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. --- EU07.cpp | 24 ++++++++++++++++++++++++ gl/shader.cpp | 8 ++++++++ 2 files changed, 32 insertions(+) diff --git a/EU07.cpp b/EU07.cpp index 20f24aa5a..136882299 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -27,6 +27,11 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -136,10 +141,29 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } +// every vehicle with a driver keeps its physics log open for the whole run, and on a scenery with some five hundred +// of them the logs 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. so the limit is raised to the most +// either system allows +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); 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(); From 5ca2f7e38fc59cc77c74a8975f84381998e61a7f Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:04:55 +0100 Subject: [PATCH 11/58] feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. --- blackbox_doc.md | 15 ++++-- simulation/blackboxrecorder.cpp | 42 ++++++++++++++- simulation/blackboxrecorder.h | 8 +++ utilities/Globals.cpp | 8 ++- utilities/Globals.h | 4 +- vehicle/Driver.cpp | 95 +++++++++++++++++---------------- vehicle/Driver.h | 8 +++ 7 files changed, 126 insertions(+), 54 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index c58cae100..80ddbacf8 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -7,10 +7,17 @@ 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`. 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, written when the +recording ends: `physicslog/.dat`, the same file name, the same columns and the same line every +0.05 s as `physicslog yes` would write, but only of the times the user was there. A vehicle with no driver +of its own takes the log of the driver of its train. So the speed recorder's tape can be read from them as +before, without the simulator keeping a log of every vehicle open all the time. A simulator that crashes +leaves the recording, but not these logs. 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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index d886bddf0..b5465053b 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -42,6 +42,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}; @@ -233,7 +234,8 @@ 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) || Global.editor_session) return; open(); } @@ -246,6 +248,11 @@ void blackbox_recorder::update(double const Deltatime) { write_cab(); m_cabdue = std::max(m_cabdue + cabinterval, m_time); } + // with the physics logs on, each driver writes its own all the time + if (false == WriteLogFlag && m_time >= m_tapedue) { + keep_tape_line(); + m_tapedue = std::max(m_tapedue + tapeinterval, m_time); + } if (m_time >= m_cameradue) { write_camera(); m_cameradue = std::max(m_cameradue + camerainterval, m_time); @@ -273,6 +280,7 @@ void blackbox_recorder::close() { m_writer->end(m_time); m_writer.reset(); m_file.close(); + write_tapes(); using milliseconds = std::chrono::duration; WriteLog(std::format("Black box: recording closed; {} looks around, {:.3f} ms each on average, the longest {:.3f} ms", m_looks, m_looks > 0 ? milliseconds{m_looktime}.count() / m_looks : 0.0, milliseconds{m_looklongest}.count())); @@ -478,6 +486,38 @@ 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. in a vehicle without one, the driver of its train + auto const *driver{vehicle->Mechanik != nullptr ? vehicle->Mechanik : vehicle->ctOwner}; + if (driver == nullptr) + return; + m_tapes[driver->physicslog_name()] += driver->physicslog_line(); +} + +void blackbox_recorder::write_tapes() { + for (auto const &[name, lines] : m_tapes) { + // opened as the driver opens its log, so the file is the same to the byte + auto const filename{"physicslog/" + name + ".dat"}; + std::fstream file{filename, std::ios::in | std::ios::out | std::ios::trunc}; + if (false == file.is_open()) { + ErrorLog(std::format("Black box: can't create the physics log \"{}\"", filename)); + continue; + } + file << TController::physicslog_header() << lines; + file.close(); + if (file.fail()) + ErrorLog(std::format("Black box: the physics log \"{}\" wasn't written whole", filename)); + else + WriteLog(std::format("Black box: the physics log \"{}\" written from the recording", filename)); + } + m_tapes.clear(); +} + 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..b7715e04c 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -86,6 +87,10 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); + // with the physics logs off, the line of the log of the driver the user is with, kept for the end + void keep_tape_line(); + // the kept lines, each driver's to its log, physicslog/.dat, as the physics logs would have it + void write_tapes(); // the clock, the user's vehicle, the vehicles, the switches and the signals void look_around(bool Keyframe); void look_at_vehicles(bool Keyframe); @@ -109,6 +114,9 @@ private: bool m_started{false}; // tried to start, made or not double m_time{0.0}; double m_cabdue{0.0}; + double m_tapedue{0.0}; + // the lines of the physics log by the name of its file, of the times the user was with its driver + std::map m_tapes; double m_lookdue{0.0}; double m_keyframedue{0.0}; std::unordered_map m_vehicles; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..9c0c10279 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -540,7 +540,9 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "blackbox") { - ParseOne(Parser, BlackBox); + bool blackbox{false}; + ParseOne(Parser, blackbox); + BlackBox = blackbox; return true; } @@ -1735,7 +1737,9 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.volume.ambient", EnvironmentAmbientVolume ); export_as_text( Output, "sound.asyncload", AudioAsyncLoad ); export_as_text( Output, "physicslog", WriteLogFlag ); - export_as_text( Output, "blackbox", BlackBox ); + 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 8d32a463c..c4a9a7267 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -113,7 +113,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 }; diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..8255a93cc 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2344,16 +2344,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, 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 ); + LogFile << physicslog_header(); #endif #if LOGPRESS == 1 LogFile << string( "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP" ).c_str() << "\n"; @@ -5367,47 +5358,59 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N return false; // nierozpoznana - wysłać bezpośrednio do pojazdu }; +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"; +} + +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << 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"; + return line.str(); +} + void TController::PhysicsLog() { // zapis logu - na razie tylko wypisanie parametrów if (LogFile.is_open()) { #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"; + LogFile << physicslog_line(); #endif #if LOGPRESS == 1 LogFile << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) diff --git a/vehicle/Driver.h b/vehicle/Driver.h index cfa27757e..02b2c60e2 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" @@ -730,6 +731,13 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } + // the physics log (physicslog/.dat): the name of its file without the extension, its first line and + // a line of it as the vehicle is now, each with its line end. the black box keeps the lines of the vehicle the + // user is in, to write its log at the end when the logs of all the vehicles are off + std::string const &physicslog_name() const { + return VehicleName; } + static std::string_view physicslog_header(); + std::string physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: From 03a3b4c09a0e010756daebb0c3637974185173e3 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:48:17 +0100 Subject: [PATCH 12/58] feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. --- CMakeLists.txt | 1 + EU07.cpp | 11 ++- application/application.cpp | 4 + blackbox_doc.md | 15 ++-- simulation/blackboxrecorder.cpp | 30 ++------ simulation/blackboxrecorder.h | 12 +-- simulation/simulationtest.cpp | 2 + tests/unit/test_physicslog.cpp | 131 ++++++++++++++++++++++++++++++++ utilities/physicslog.cpp | 98 ++++++++++++++++++++++++ utilities/physicslog.h | 67 ++++++++++++++++ vehicle/Driver.cpp | 35 ++++----- vehicle/Driver.h | 2 +- 12 files changed, 347 insertions(+), 61 deletions(-) create mode 100644 tests/unit/test_physicslog.cpp create mode 100644 utilities/physicslog.cpp create mode 100644 utilities/physicslog.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..3c12c51a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -546,6 +546,7 @@ set(CORE_SOURCES "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" "vehicle/blackbox.cpp" +"utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" "vehicle/handover.cpp" diff --git a/EU07.cpp b/EU07.cpp index 136882299..4ccbd6f56 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,6 +22,7 @@ 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 @@ -112,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 two seconds of the physics logs, which the runner of the tests reads + PhysicsLogs.stop(); finish_log(); fflush(stdout); fflush(stderr); @@ -141,10 +144,10 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } -// every vehicle with a driver keeps its physics log open for the whole run, and on a scenery with some five hundred -// of them the logs 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. so the limit is raised to the most -// either system allows +// 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 diff --git a/application/application.cpp b/application/application.cpp index 96f578514..ba62fe467 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "utilities/physicslog.h" #include #include #include @@ -745,6 +746,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 + PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) mode.reset(); diff --git a/blackbox_doc.md b/blackbox_doc.md index 80ddbacf8..ea7322ca8 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -12,12 +12,15 @@ starter, a viewer) can replay the session on the map, or set the user's driving 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, written when the -recording ends: `physicslog/.dat`, the same file name, the same columns and the same line every -0.05 s as `physicslog yes` would write, but only of the times the user was there. A vehicle with no driver -of its own takes the log of the driver of its train. So the speed recorder's tape can be read from them as -before, without the simulator keeping a log of every vehicle open all the time. A simulator that crashes -leaves the recording, but not these logs. +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. A log begins when the user first is in the vehicle, and goes on while the +user looks around outside it, until the user takes another vehicle, whose log begins then. Back in a +vehicle, its log goes on after the gap in its time. A vehicle with no driver of its own 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. 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 them. 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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index b5465053b..141ff070e 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 @@ -280,7 +281,6 @@ void blackbox_recorder::close() { m_writer->end(m_time); m_writer.reset(); m_file.close(); - write_tapes(); using milliseconds = std::chrono::duration; WriteLog(std::format("Black box: recording closed; {} looks around, {:.3f} ms each on average, the longest {:.3f} ms", m_looks, m_looks > 0 ? milliseconds{m_looktime}.count() / m_looks : 0.0, milliseconds{m_looklongest}.count())); @@ -492,30 +492,16 @@ void blackbox_recorder::keep_tape_line() { 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. in a vehicle without one, the driver of its train - auto const *driver{vehicle->Mechanik != nullptr ? vehicle->Mechanik : vehicle->ctOwner}; + // 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; - m_tapes[driver->physicslog_name()] += driver->physicslog_line(); -} - -void blackbox_recorder::write_tapes() { - for (auto const &[name, lines] : m_tapes) { - // opened as the driver opens its log, so the file is the same to the byte - auto const filename{"physicslog/" + name + ".dat"}; - std::fstream file{filename, std::ios::in | std::ios::out | std::ios::trunc}; - if (false == file.is_open()) { - ErrorLog(std::format("Black box: can't create the physics log \"{}\"", filename)); - continue; - } - file << TController::physicslog_header() << lines; - file.close(); - if (file.fail()) - ErrorLog(std::format("Black box: the physics log \"{}\" wasn't written whole", filename)); - else - WriteLog(std::format("Black box: the physics log \"{}\" written from the recording", filename)); + auto const &name{driver->physicslog_name()}; + if (m_tapes.insert(name).second) { + PhysicsLogs.begin(name, TController::physicslog_header()); + WriteLog(std::format("Black box: the physics log \"physicslog/{}.dat\" begun", name)); } - m_tapes.clear(); + PhysicsLogs.append(name, driver->physicslog_line()); } void blackbox_recorder::look_around(bool const Keyframe) { diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index b7715e04c..093f22d1d 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -15,9 +15,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include #include +#include #include #include #include @@ -87,10 +87,10 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); - // with the physics logs off, the line of the log of the driver the user is with, kept for the end + // with the physics logs off, the line of the log of the driver the user is with, to its log, physicslog/.dat, + // as the physics logs would have it. a log is begun at the first line of the recording, and goes on while the user + // looks around outside, until the user takes another vehicle; back in the vehicle, it goes on after the gap void keep_tape_line(); - // the kept lines, each driver's to its log, physicslog/.dat, as the physics logs would have it - void write_tapes(); // the clock, the user's vehicle, the vehicles, the switches and the signals void look_around(bool Keyframe); void look_at_vehicles(bool Keyframe); @@ -115,8 +115,8 @@ private: double m_time{0.0}; double m_cabdue{0.0}; double m_tapedue{0.0}; - // the lines of the physics log by the name of its file, of the times the user was with its driver - std::map m_tapes; + // 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/simulationtest.cpp b/simulation/simulationtest.cpp index 89a8a1046..8f1856663 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -15,6 +15,7 @@ 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/DynObj.h" #include "world/Event.h" @@ -262,6 +263,7 @@ void test_manager::check_wall_clock(double const Elapsed) 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 + PhysicsLogs.flush(); StopLogService(); std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::_Exit(exit_code()); diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp new file mode 100644 index 000000000..afcd0f8c7 --- /dev/null +++ b/tests/unit/test_physicslog.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/physicslog.h" + +#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 { + std::ifstream file{m_path / (Name + ".dat")}; + 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 + 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: 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"); +} diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp new file mode 100644 index 000000000..cb57d5ca3 --- /dev/null +++ b/utilities/physicslog.cpp @@ -0,0 +1,98 @@ +/* +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 + +physicslog_writer PhysicsLogs; + +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : m_folder{std::move(Folder)}, m_interval{Interval} {} + +physicslog_writer::~physicslog_writer() { + stop(); +} + +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.text.assign(Header); + start(); +} + +void physicslog_writer::append(std::string const &Name, std::string_view const Line) { + std::scoped_lock lock{m_mutex}; + m_pending[Name].text.append(Line); + start(); +} + +void physicslog_writer::flush() { + write(); +} + +void physicslog_writer::stop() { + { + std::scoped_lock lock{m_mutex}; + m_stopped = true; + } + // started only before m_stopped was set, so no one else touches it now + if (m_thread.joinable()) { + m_thread.request_stop(); + m_thread.join(); + } + write(); +} + +void physicslog_writer::start() { + if (m_stopped || m_thread.joinable()) + return; + m_thread = std::jthread([this](std::stop_token const &Stop) { run(Stop); }); +} + +void physicslog_writer::run(std::stop_token const &Stop) { + 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, Stop, m_interval, [] { return false; }) || Stop.stop_requested()) + return; + } + write(); + } +} + +void physicslog_writer::write() { + std::scoped_lock files{m_filemutex}; + std::map taken; + { + std::scoped_lock lock{m_mutex}; + taken.swap(m_pending); + } + if (taken.empty()) + return; + std::error_code error; + std::filesystem::create_directories(m_folder, error); + for (auto const &[name, lines] : taken) { + if (lines.text.empty() && false == lines.fresh) + continue; + auto const path{m_folder / (name + ".dat")}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" + std::ofstream file{path, lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; + if (file.is_open()) + file << lines.text; + file.close(); + if (file.fail() && m_failed.insert(name).second) + ErrorLog("Bad physics log: can't write " + path.string()); + } +} diff --git a/utilities/physicslog.h b/utilities/physicslog.h new file mode 100644 index 000000000..2963c29a9 --- /dev/null +++ b/utilities/physicslog.h @@ -0,0 +1,67 @@ +/* +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 + +// the physics logs, /.dat. 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 them +class physicslog_writer { +public: + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); + physicslog_writer(physicslog_writer const &) = delete; + physicslog_writer &operator=(physicslog_writer const &) = delete; + // stops, writing what is kept + ~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); + // writes what is kept, now + void flush(); + // writes what is kept and ends the thread. what is given after is written by a flush, or at the end + void stop(); + +private: + struct pending { + bool fresh{false}; // its file is to be emptied first + std::string text; + }; + + // the thread, on the first line given, unless stopped. called with m_mutex held + void start(); + void run(std::stop_token const &Stop); + void write(); + + std::filesystem::path const m_folder; + std::chrono::milliseconds const m_interval; + std::mutex m_mutex; // the lines kept and the thread + std::map m_pending; + bool m_stopped{false}; + std::condition_variable_any m_wake; + std::jthread m_thread; + 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 +}; + +// 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/vehicle/Driver.cpp b/vehicle/Driver.cpp index 8255a93cc..cde6ed99f 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" @@ -2336,20 +2337,13 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, 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 ); + // physicslog/.dat, written every two seconds along with the logs of the other drivers #if LOGPRESS == 0 - LogFile << physicslog_header(); + PhysicsLogs.begin( VehicleName, physicslog_header() ); #endif #if LOGPRESS == 1 - LogFile << string( "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP" ).c_str() << "\n"; + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); #endif - LogFile.flush(); } // HACK: give the simulation a small window to potentially replace the AI with a human driver @@ -2358,7 +2352,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 @@ -5407,21 +5400,19 @@ std::string TController::physicslog_line() const { void TController::PhysicsLog() { // zapis logu - na razie tylko wypisanie parametrów - if (LogFile.is_open()) - { #if LOGPRESS == 0 - LogFile << physicslog_line(); + PhysicsLogs.append( VehicleName, physicslog_line() ); #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"; + 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 diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 02b2c60e2..306287311 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -721,9 +721,9 @@ private: // logs // methods + // the line of the log, to PhysicsLogs (utilities/physicslog.h) void PhysicsLog(); // members - std::ofstream LogFile; // zapis parametrow fizycznych double LastUpdatedTime = 0.0; // czas od ostatniego logu double ElapsedTime = 0.0; // czas od poczatku logu From 7b7529e24e51628516b249baff54f38f97954e2b Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 00:48:18 +0100 Subject: [PATCH 13/58] feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. --- blackbox_doc.md | 6 ++++-- simulation/blackboxrecorder.cpp | 2 ++ tests/unit/test_blackbox.cpp | 3 +++ vehicle/blackbox.cpp | 1 + vehicle/blackbox.h | 5 ++++- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index ea7322ca8..d81b143bc 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -172,14 +172,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) | @@ -231,6 +232,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, 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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 141ff070e..bc572afbd 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -418,6 +418,8 @@ 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 + sample.wheel_speed_kmh = static_cast(M_PI * occupied->WheelDiameter * occupied->nrot * 3.6); sample.acceleration = static_cast(controlling->AccS); sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { 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/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 473cf677c..62fc1df38 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 From 73d535f73ee66483273a5f8563a4d198193fba43 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 14 Nov 2026 20:58:04 +0100 Subject: [PATCH 14/58] fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build_bin.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 041eea4f0..f5bab9ca2 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -221,8 +221,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 +254,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 \ From 4558976733d38616975f6c6a87cf18700d5574ca Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 20:42:13 +0100 Subject: [PATCH 15/58] fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. --- editor/editorHttp.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 12569ebd0..60606331e 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,8 @@ 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()); ::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 From 465300df8d19ce17176a95ef014061ced0b97431 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 20:43:08 +0100 Subject: [PATCH 16/58] fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. --- editor/editorHttp.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 60606331e..81a195aeb 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -239,7 +239,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st ::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 From 348a814ce2b1aa01bc724663306fa0c73b011039 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 21:18:22 +0100 Subject: [PATCH 17/58] fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. --- .github/workflows/build_bin.yml | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index d3c33f032..2ad948828 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -32,11 +32,14 @@ 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 / ${{ 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: @@ -45,7 +48,7 @@ jobs: variant: - name: "AVX2" suffix: "avx2" - cmake_flags: "" + cmake_flags: "-DENABLE_AVX2=ON" - name: "No AVX2" suffix: "noavx2" cmake_flags: "-DENABLE_AVX2=OFF" @@ -393,12 +396,19 @@ 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 Windows build (no AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64-noavx2 + - name: Download Linux build uses: actions/download-artifact@v4 with: @@ -415,6 +425,7 @@ jobs: fi (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 . ls -la @@ -435,6 +446,7 @@ 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" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" @@ -442,6 +454,7 @@ jobs: 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 \ --target "$SHA" \ --prerelease \ @@ -451,4 +464,5 @@ 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" From 507fcd8cb33fb5550230ac54a82d2d8837e7bfce Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 21:22:14 +0100 Subject: [PATCH 18/58] build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64___noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. --- CMakeLists.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..09fe4bd7d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -475,6 +475,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 "") From 09161042934ebb0a717d5b8be2ccf7d353e39046 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 21:25:30 +0100 Subject: [PATCH 19/58] ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07___noavx2. --- .github/workflows/build_bin.yml | 45 +++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 2ad948828..fed45a44b 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -205,13 +205,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 @@ -308,6 +319,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" @@ -373,7 +385,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 @@ -409,24 +421,34 @@ jobs: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64-noavx2 - - name: Download Linux build + - name: Download Linux build (AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + 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 @@ -448,6 +470,7 @@ jobs: "- 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")" @@ -456,6 +479,7 @@ jobs: 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 \ @@ -466,3 +490,4 @@ jobs: 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" From 88522fe600f8d07488a85b76ade555dcca64439f Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:09:49 +0100 Subject: [PATCH 20/58] fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. --- rendering/openglrenderer.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 71bd7d0ef..d27f56099 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 From 68c33922a6b47b892831886ba24eb62ee5db5fbb Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:20:18 +0100 Subject: [PATCH 21/58] fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. --- application/application.cpp | 15 +++++++++++++++ rendering/renderer.cpp | 5 +++++ rendering/renderer.h | 1 + 3 files changed, 21 insertions(+) diff --git a/application/application.cpp b/application/application.cpp index 96f578514..c18042c26 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -1323,6 +1323,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/rendering/renderer.cpp b/rendering/renderer.cpp index d9d4b5df0..c120f4222 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) diff --git a/rendering/renderer.h b/rendering/renderer.h index 5ad805c4a..b45435256 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -151,6 +151,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(); From aaff0a430ba82d34ac257a6493cd4e98ccf883fe Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:22:50 +0100 Subject: [PATCH 22/58] fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. --- utilities/Globals.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..bcd5037e2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -321,6 +321,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"; From 7547e6bf07072eb74b842f06643b9da3a8ecdec1 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:32:38 +0100 Subject: [PATCH 23/58] fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. --- EU07.cpp | 3 ++ simulation/simulationtest.cpp | 5 ++- tests/unit/test_physicslog.cpp | 60 +++++++++++++++++++++++++++- utilities/physicslog.cpp | 73 ++++++++++++++++++++++++++++------ utilities/physicslog.h | 11 +++-- 5 files changed, 134 insertions(+), 18 deletions(-) diff --git a/EU07.cpp b/EU07.cpp index 4ccbd6f56..1c2c36aab 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -242,6 +242,9 @@ int main(int argc, char *argv[]) MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); } #endif + // the last two seconds of the physics logs, 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/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 8f1856663..11aca23c4 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -262,8 +262,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 - PhysicsLogs.flush(); + // what was logged last gets written, unless the log is held up by a hung thread, or the physics logs by a disk + // which doesn't answer: the run ends anyway + 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/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index afcd0f8c7..3189c424f 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -83,7 +83,8 @@ TEST_CASE("physicslog: no file is kept open between the writings, and a log not logs.begin("SM42-001", header); logs.flush(); - // Windows doesn't let a file open in a program be removed + // 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); @@ -120,6 +121,63 @@ TEST_CASE("physicslog: stopping writes what is kept at once, and what comes afte CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); } +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 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: 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"}; { diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index cb57d5ca3..8a9ec2434 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -17,6 +17,13 @@ http://mozilla.org/MPL/2.0/. physicslog_writer PhysicsLogs; +namespace { + +// the most of a log kept while its file can't be written; the oldest lines go beyond it +constexpr std::size_t keptwhilefailing{4 * 1024 * 1024}; + +} // namespace + physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : m_folder{std::move(Folder)}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { @@ -27,7 +34,8 @@ void physicslog_writer::begin(std::string const &Name, std::string_view const He std::scoped_lock lock{m_mutex}; auto &lines{m_pending[Name]}; lines.fresh = true; - lines.text.assign(Header); + lines.header.assign(Header); + lines.text.clear(); start(); } @@ -38,20 +46,36 @@ void physicslog_writer::append(std::string const &Name, std::string_view const L } void physicslog_writer::flush() { + std::scoped_lock files{m_filemutex}; write(); } +bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { + std::unique_lock files{m_filemutex, Timeout}; + if (false == files.owns_lock()) + return false; + write(); + return true; +} + void physicslog_writer::stop() { + std::jthread thread; { 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); } - // started only before m_stopped was set, so no one else touches it now - if (m_thread.joinable()) { - m_thread.request_stop(); - m_thread.join(); + if (thread.joinable()) { + if (thread.get_id() == std::this_thread::get_id()) { + // stopped from the thread itself, by the end of a run which failed in it: the files may be held by it + thread.detach(); + return; + } + thread.request_stop(); + thread.join(); } - write(); + flush(); } void physicslog_writer::start() { @@ -68,12 +92,11 @@ void physicslog_writer::run(std::stop_token const &Stop) { if (m_wake.wait_for(lock, Stop, m_interval, [] { return false; }) || Stop.stop_requested()) return; } - write(); + flush(); } } void physicslog_writer::write() { - std::scoped_lock files{m_filemutex}; std::map taken; { std::scoped_lock lock{m_mutex}; @@ -83,16 +106,42 @@ void physicslog_writer::write() { return; std::error_code error; std::filesystem::create_directories(m_folder, error); - for (auto const &[name, lines] : taken) { + std::map failed; + for (auto &[name, lines] : taken) { if (lines.text.empty() && false == lines.fresh) continue; auto const path{m_folder / (name + ".dat")}; // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" std::ofstream file{path, lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; - if (file.is_open()) + if (file.is_open()) { + if (lines.fresh) + file << lines.header; file << lines.text; + } file.close(); - if (file.fail() && m_failed.insert(name).second) - ErrorLog("Bad physics log: can't write " + path.string()); + if (false == file.fail()) { + if (m_failed.erase(name) > 0) + WriteLog("Physics log: " + path.string() + " written again"); + continue; + } + if (m_failed.insert(name).second) + ErrorLog("Bad physics log: can't write " + path.string() + ", its lines are kept for the next try"); + failed.emplace(name, std::move(lines)); + } + if (failed.empty()) + return; + // 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. a log begun anew since drops them + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : failed) { + auto &now{m_pending[name]}; + if (now.fresh) + continue; + lines.text.append(now.text); + if (lines.text.size() > keptwhilefailing) { + auto const cut{lines.text.find('\n', lines.text.size() - keptwhilefailing)}; + lines.text.erase(0, cut == std::string::npos ? lines.text.size() : cut + 1); + } + now = std::move(lines); } } diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 2963c29a9..024ae8fba 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -22,7 +22,8 @@ http://mozilla.org/MPL/2.0/. // the physics logs, /.dat. 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 them +// the simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them. lines whose file +// can't be written, held by another program say, are kept for the next try class physicslog_writer { public: explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); @@ -38,18 +39,22 @@ public: void append(std::string const &Name, std::string_view Line); // writes what is kept, now void flush(); + // as flush, unless the files are being written for longer than Timeout: then false, and nothing done + bool flush_for(std::chrono::milliseconds Timeout); // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); private: struct pending { - bool fresh{false}; // its file is to be emptied first + bool fresh{false}; // its file is to be emptied first, and the header written into it + std::string header; std::string text; }; // the thread, on the first line given, unless stopped. called with m_mutex held void start(); void run(std::stop_token const &Stop); + // called with m_filemutex held void write(); std::filesystem::path const m_folder; @@ -59,7 +64,7 @@ private: bool m_stopped{false}; std::condition_variable_any m_wake; std::jthread m_thread; - std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order + std::timed_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 }; From 5d0bf6ed004a3c0719fa5c1e98c328ef5f57f99c Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:32:39 +0100 Subject: [PATCH 24/58] fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. --- blackbox_doc.md | 15 +++++++++------ simulation/blackboxrecorder.cpp | 10 ++++++++-- simulation/blackboxrecorder.h | 4 ++-- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index d81b143bc..33757788a 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -14,13 +14,16 @@ recording started at), next to the `.dat` logs of the vehicles when those are on 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. A log begins when the user first is in the vehicle, and goes on while the -user looks around outside it, until the user takes another vehicle, whose log begins then. Back in a -vehicle, its log goes on after the gap in its time. A vehicle with no driver of its own 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 +`physicslog yes` would write. 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. 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 them. +of real time of them (at a higher time speed, more of the simulated time). A file another program holds +for a while doesn't lose its lines: they are written once it can be. 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 @@ -232,7 +235,7 @@ files written before the speed of the wheels was added at the end). | `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, signed as the speed of the vehicle: apart from it while the wheels slip, 0 while they are locked in a skid | +| `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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index bc572afbd..d53180744 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -418,8 +418,14 @@ 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 - sample.wheel_speed_kmh = static_cast(M_PI * occupied->WheelDiameter * occupied->nrot * 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 + auto *powered{train->Dynamic()->FindPowered()}; + if (powered == nullptr) + powered = train->Dynamic(); + 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()) { diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 093f22d1d..67742b24e 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -88,8 +88,8 @@ private: static std::vector> stop_point_headings(); void write_cab(); // with the physics logs off, the line of the log of the driver the user is with, to its log, physicslog/.dat, - // as the physics logs would have it. a log is begun at the first line of the recording, and goes on while the user - // looks around outside, until the user takes another vehicle; back in the vehicle, it goes on after the gap + // 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); From 043b9fb2f0143cd2d0ccc6048f02e06423d8d3fb Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:38:24 +0100 Subject: [PATCH 25/58] fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. --- blackbox_doc.md | 2 +- simulation/blackboxrecorder.cpp | 5 ++- simulation/simulationtest.cpp | 4 +-- utilities/physicslog.cpp | 62 ++++++++++++++++++++++++--------- utilities/physicslog.h | 8 +++-- 5 files changed, 55 insertions(+), 26 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index 33757788a..704d1e954 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -23,7 +23,7 @@ the driver of its train. So the speed recorder's tape can be read from them as b simulator runs, without a log of every vehicle. 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). A file another program holds -for a while doesn't lose its lines: they are written once it can be. +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 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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index d53180744..28e453926 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -421,9 +421,8 @@ void blackbox_recorder::write_cab() { // 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 - auto *powered{train->Dynamic()->FindPowered()}; - if (powered == nullptr) - powered = train->Dynamic(); + // 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); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 11aca23c4..d32fd0e72 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -262,8 +262,8 @@ 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, or the physics logs by a disk - // which doesn't answer: the run ends anyway + // 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)); diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index 8a9ec2434..299b74221 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -11,7 +11,10 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "utilities/Logs.h" +#include #include +#include +#include #include #include @@ -19,8 +22,18 @@ physicslog_writer PhysicsLogs; namespace { -// the most of a log kept while its file can't be written; the oldest lines go beyond it -constexpr std::size_t keptwhilefailing{4 * 1024 * 1024}; +// 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); +} } // namespace @@ -51,11 +64,15 @@ void physicslog_writer::flush() { } bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { - std::unique_lock files{m_filemutex, Timeout}; - if (false == files.owns_lock()) - return false; - write(); - return true; + // 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(); + done->set_value(); + }).detach(); + return ended.wait_for(Timeout) == std::future_status::ready; } void physicslog_writer::stop() { @@ -63,15 +80,19 @@ void physicslog_writer::stop() { { std::scoped_lock lock{m_mutex}; m_stopped = true; + // stopped from the writer itself, by the end of a run which failed in it: the files may be held by it, and + // another thread may be joining it already + if (m_writer == std::this_thread::get_id()) { + if (m_thread.joinable()) { + m_thread.request_stop(); + m_thread.detach(); + } + return; + } // taken by the first to stop, so it's joined once thread = std::move(m_thread); } if (thread.joinable()) { - if (thread.get_id() == std::this_thread::get_id()) { - // stopped from the thread itself, by the end of a run which failed in it: the files may be held by it - thread.detach(); - return; - } thread.request_stop(); thread.join(); } @@ -82,6 +103,7 @@ 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) { @@ -111,6 +133,10 @@ void physicslog_writer::write() { if (lines.text.empty() && false == lines.fresh) continue; auto const path{m_folder / (name + ".dat")}; + // how long it was, to be 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 + auto const before{lines.fresh ? 0 : std::filesystem::file_size(path, error)}; + auto const existed{false == lines.fresh && false == static_cast(error)}; // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" std::ofstream file{path, lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; if (file.is_open()) { @@ -124,12 +150,18 @@ void physicslog_writer::write() { WriteLog("Physics log: " + path.string() + " written again"); continue; } + if (existed) + std::filesystem::resize_file(path, before, error); if (m_failed.insert(name).second) - ErrorLog("Bad physics log: can't write " + path.string() + ", its lines are kept for the next try"); + ErrorLog("Bad physics log: can't write " + path.string() + ", its last lines are kept for the next try"); failed.emplace(name, std::move(lines)); } if (failed.empty()) return; + // 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 / failed.size())}; + for (auto &[name, lines] : failed) + 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. a log begun anew since drops them std::scoped_lock lock{m_mutex}; @@ -138,10 +170,6 @@ void physicslog_writer::write() { if (now.fresh) continue; lines.text.append(now.text); - if (lines.text.size() > keptwhilefailing) { - auto const cut{lines.text.find('\n', lines.text.size() - keptwhilefailing)}; - lines.text.erase(0, cut == std::string::npos ? lines.text.size() : cut + 1); - } now = std::move(lines); } } diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 024ae8fba..44d04b4c3 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -23,7 +23,7 @@ http://mozilla.org/MPL/2.0/. // the physics logs, /.dat. 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. lines whose file -// can't be written, held by another program say, are kept for the next try +// can't be written, held by another program say, are kept for the next try: the last 64 MB of them all at most class physicslog_writer { public: explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); @@ -39,7 +39,8 @@ public: void append(std::string const &Name, std::string_view Line); // writes what is kept, now void flush(); - // as flush, unless the files are being written for longer than Timeout: then false, and nothing done + // 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. what is given after is written by a flush, or at the end void stop(); @@ -64,7 +65,8 @@ private: bool m_stopped{false}; std::condition_variable_any m_wake; std::jthread m_thread; - std::timed_mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order + std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it + 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 }; From b7950af6b62794f94e3fb7ded4373e0c5849c5ef Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:48:23 +0100 Subject: [PATCH 26/58] feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. --- blackbox_doc.md | 10 +++++++--- simulation/blackboxrecorder.cpp | 5 ++++- utilities/Globals.cpp | 8 ++++++++ vehicle/Driver.cpp | 35 +++++++++++++++++++++++---------- vehicle/Driver.h | 10 ++++++++++ 5 files changed, 54 insertions(+), 14 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index 704d1e954..3573b4271 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -8,7 +8,9 @@ the timetable and how the train kept to it at each station, and where it was tol starter, a viewer) can replay the session on the map, or set the user's driving against the AI's. `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`. It is never written in an +`blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. +The latter writes the `.dat` logs of the trains only: of each driver who drives rail vehicles, not of the +passengers nor of the vehicles of the roads, so a big scenery gives far fewer of them. 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. @@ -20,7 +22,8 @@ moves to another cab of the unit or another vehicle of the same train. Taking a 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. Like those of `physicslog yes`, they are written every +simulator runs, without a log of every vehicle. A driver who writes a log of its own, with +`physicslog.trains yes`, isn't written twice. 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). 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. @@ -300,7 +303,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/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 28e453926..6d0f76502 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -236,7 +236,7 @@ void blackbox_recorder::update(double const Deltatime) { return; m_started = true; // "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) || Global.editor_session) + if (false == Global.BlackBox.value_or(WriteLogFlag || WriteTrainLogFlag) || Global.editor_session) return; open(); } @@ -503,6 +503,9 @@ void blackbox_recorder::keep_tape_line() { auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; if (driver == nullptr) return; + // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice + if (driver->writes_physicslog()) + return; auto const &name{driver->physicslog_name()}; if (m_tapes.insert(name).second) { PhysicsLogs.begin(name, TController::physicslog_header()); diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 9c0c10279..db9e0ba79 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -538,6 +538,13 @@ 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") { bool blackbox{false}; @@ -1737,6 +1744,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.volume.ambient", EnvironmentAmbientVolume ); export_as_text( Output, "sound.asyncload", AudioAsyncLoad ); export_as_text( Output, "physicslog", WriteLogFlag ); + export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); if( BlackBox ) { export_as_text( Output, "blackbox", *BlackBox ); } diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index cde6ed99f..03c3f9d8f 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -169,6 +169,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[] = { @@ -2336,14 +2337,8 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych TableClear(); - if( WriteLogFlag ) { - // physicslog/.dat, written every two seconds along with the logs of the other drivers -#if LOGPRESS == 0 - PhysicsLogs.begin( VehicleName, physicslog_header() ); -#endif -#if LOGPRESS == 1 - PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); -#endif + if( writes_physicslog() ) { + begin_physicslog(); } // HACK: give the simulation a small window to potentially replace the AI with a human driver @@ -5398,6 +5393,18 @@ std::string TController::physicslog_line() const { return line.str(); } +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers +#if LOGPRESS == 0 + PhysicsLogs.begin( VehicleName, physicslog_header() ); +#endif +#if LOGPRESS == 1 + 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 @@ -6463,10 +6470,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: a driver which begins to, made primary, writes 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 306287311..bfeeb1b16 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -198,6 +198,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 @@ -723,7 +726,10 @@ private: // 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 + 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 @@ -736,6 +742,10 @@ public: // user is in, to write its log at the end when the logs of all the vehicles are off std::string const &physicslog_name() const { return VehicleName; } + // whether it writes its physics log itself: all with "physicslog yes", with "physicslog.trains yes" one who drives + // rail vehicles. a driver made primary later begins its log then + bool writes_physicslog() const { + return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); std::string physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { From b421550cbedf4939fe8935787e6d7494c2034ef7 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 15 Nov 2026 23:56:30 +0100 Subject: [PATCH 27/58] fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. --- vehicle/Driver.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 03c3f9d8f..23d778bdb 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2337,7 +2337,10 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych TableClear(); - if( writes_physicslog() ) { + // the logs of all, 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 ) { begin_physicslog(); } @@ -6471,8 +6474,8 @@ void TController::update_logs( double const dt ) { // log vehicle data if( false == writes_physicslog() ) { - // not counted while it isn't logged: a driver which begins to, made primary, writes a line every 0.05 s - // from then on, not one each update to make up for the time before + // 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; } From 4525023777a7c007603ab21b131dc158866d8b46 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 01:54:40 +0100 Subject: [PATCH 28/58] fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. --- application/editormode.cpp | 1 + application/editormode.h | 10 +++++++++- application/editormodetextures.cpp | 28 +++++++++++++++++++++++++--- application/editormodetrackprops.cpp | 6 ++++-- model/Texture.cpp | 28 ++++++++++++++++++++++++++++ model/Texture.h | 4 ++++ rendering/opengl33renderer.cpp | 5 +++++ rendering/opengl33renderer.h | 2 ++ rendering/openglrenderer.cpp | 6 ++++++ rendering/openglrenderer.h | 2 ++ rendering/renderer.h | 3 +++ 11 files changed, 89 insertions(+), 6 deletions(-) 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..68746cdf4 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -745,13 +745,21 @@ 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 + double shown{0.0}; // when it was last asked for, ImGui time + }; + std::map thumbnails; // texture shown for the item of the name 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..8d5fcd3be 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -102,16 +102,36 @@ std::uint64_t editor_mode::texture_thumbnail(texture_browser::item const &Item) } else texture = GfxRenderer->Fetch_Texture(Item.name, true); - lookup = browser.thumbnails.emplace(Item.name, texture).first; + lookup = browser.thumbnails.emplace(Item.name, texture_browser::thumbnail{texture}).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 + auto constexpr kept{3.0}; + auto const now{ImGui::GetTime()}; + auto &thumbnails{m_textures.thumbnails}; + for (auto entry{thumbnails.begin()}; entry != thumbnails.end();) + { + if (entry->second.texture == null_handle || now - entry->second.shown < kept) + { + ++entry; + continue; + } + // the scene's own textures stay; shown again, the image is read anew within the few a frame + GfxRenderer->Unload_Texture(entry->second.texture); + entry = thumbnails.erase(entry); + } +} + void editor_mode::render_texture_browser() { auto &browser{m_textures}; @@ -173,6 +193,8 @@ void editor_mode::render_texture_browser() if (ImGui::Button(STR_C("Refresh"))) { browser.listed = false; + for (auto const &[name, thumbnail] : browser.thumbnails) + GfxRenderer->Unload_Texture(thumbnail.texture); browser.thumbnails.clear(); } ImGui::SameLine(); 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/model/Texture.cpp b/model/Texture.cpp index cd275c9e0..36757bd08 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -1886,6 +1886,34 @@ 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 == opengl_texture::invalid_id ) + || ( texture.id == 0 ) + || ( true == texture.is_static ) + || ( true == texture.is_rendertarget ) + || ( texture.type == "make:" ) + || ( texture.type == "internalsrc:" ) ) { + return; + } + texture.release(); + texture.data = std::vector(); + texture.data_state = resource_state::none; + texture.reload_on_use = true; + // 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; + } +} + // 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..d177592cc 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; 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/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..737c4b379 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -1922,6 +1922,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.h b/rendering/renderer.h index 5ad805c4a..337d63925 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -102,6 +102,9 @@ 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 ) {} // utility methods virtual void Pick_Control_Callback( std::function Callback ) = 0; virtual void Pick_Node_Callback( std::function Callback ) = 0; From 94b7c7f01b6c45512aa9b28ffa7bd889459f7488 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 02:08:04 +0100 Subject: [PATCH 29/58] fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing --- utilities/physicslog.cpp | 11 +++++++++-- utilities/physicslog.h | 2 +- vehicle/Driver.cpp | 4 ++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index 299b74221..19f18684b 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -40,7 +40,11 @@ void keep_last(std::string &Text, std::size_t const Most) { physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : m_folder{std::move(Folder)}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { - stop(); + // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse + try { + stop(); + } catch (...) { + } } void physicslog_writer::begin(std::string const &Name, std::string_view const Header) { @@ -94,6 +98,9 @@ void physicslog_writer::stop() { } if (thread.joinable()) { thread.request_stop(); + // the writer waits under the lock: taken once, it's either about to wait, seeing the stop, or waiting already + { std::scoped_lock lock{m_mutex}; } + m_wake.notify_all(); thread.join(); } flush(); @@ -111,7 +118,7 @@ void physicslog_writer::run(std::stop_token const &Stop) { { std::unique_lock lock{m_mutex}; // woken early only to stop, which writes the rest itself - if (m_wake.wait_for(lock, Stop, m_interval, [] { return false; }) || Stop.stop_requested()) + if (m_wake.wait_for(lock, m_interval, [&Stop] { return Stop.stop_requested(); })) return; } flush(); diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 44d04b4c3..9ecb88349 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -63,7 +63,7 @@ private: std::mutex m_mutex; // the lines kept and the thread std::map m_pending; bool m_stopped{false}; - std::condition_variable_any m_wake; + 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::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 23d778bdb..d2ebd1fd7 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -6372,6 +6372,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 From 0bbf07bf1191fb430640b21ef0d7e1ffa60b2926 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 02:10:59 +0100 Subject: [PATCH 30/58] fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. --- application/editormode.h | 2 ++ application/editormodetextures.cpp | 35 ++++++++++++++++++------------ model/Texture.cpp | 32 +++++++++++++++++++++------ model/Texture.h | 2 +- rendering/opengl33renderer.cpp | 12 ++++++++++ rendering/opengl33renderer.h | 2 ++ rendering/openglrenderer.cpp | 15 +++++++++++++ rendering/openglrenderer.h | 2 ++ rendering/renderer.h | 2 ++ 9 files changed, 82 insertions(+), 22 deletions(-) diff --git a/application/editormode.h b/application/editormode.h index 68746cdf4..81347c950 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -748,9 +748,11 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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; diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index 8d5fcd3be..ecf846431 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -93,16 +93,17 @@ 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_browser::thumbnail{texture}).first; + thumbnail.texture = GfxRenderer->Fetch_Texture(Item.name, true); + lookup = browser.thumbnails.emplace(Item.name, thumbnail).first; } lookup->second.shown = ImGui::GetTime(); if (lookup->second.texture == null_handle) @@ -116,20 +117,27 @@ std::uint64_t editor_mode::texture_thumbnail(texture_browser::item const &Item) 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 &thumbnails{m_textures.thumbnails}; - for (auto entry{thumbnails.begin()}; entry != thumbnails.end();) + auto &browser{m_textures}; + for (auto entry{browser.thumbnails.begin()}; entry != browser.thumbnails.end();) { - if (entry->second.texture == null_handle || now - entry->second.shown < kept) + auto const &thumbnail{entry->second}; + if (false == browser.refresh && (thumbnail.texture == 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 - GfxRenderer->Unload_Texture(entry->second.texture); - entry = thumbnails.erase(entry); + 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() @@ -193,9 +201,8 @@ void editor_mode::render_texture_browser() if (ImGui::Button(STR_C("Refresh"))) { browser.listed = false; - for (auto const &[name, thumbnail] : browser.thumbnails) - GfxRenderer->Unload_Texture(thumbnail.texture); - 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/model/Texture.cpp b/model/Texture.cpp index 36757bd08..eb24a0de6 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -1896,22 +1896,40 @@ texture_manager::unload( texture_handle const Texture ) { auto const &record { m_textures[ Texture ] }; auto &texture { *record.first }; if( ( record.second != resource_timestamp() ) - || ( texture.id == opengl_texture::invalid_id ) - || ( texture.id == 0 ) + || ( texture.id == 0 ) // failed to load || ( true == texture.is_static ) || ( true == texture.is_rendertarget ) || ( texture.type == "make:" ) || ( texture.type == "internalsrc:" ) ) { return; } - texture.release(); + 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; - // 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; - } } // releases gl textures of vehicles not needed nor drawn for a while diff --git a/model/Texture.h b/model/Texture.h index d177592cc..20221fcea 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -182,7 +182,7 @@ public: 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; it's read again when it's used. textures the scene draws are left to the resource sweep + // 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 diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..d3dfef6e9 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2575,6 +2575,18 @@ void opengl33_renderer::Unload_Texture(texture_handle const Texture) m_textures.unload(Texture); } +void opengl33_renderer::Unload_Material(material_handle const Material) +{ + if (Material == null_handle) + return; + auto const &material{m_materials.material(Material)}; + for (auto const texture : material.textures) + m_textures.unload(texture); + for (auto const &variant : material.texture_variants) + for (auto const texture : variant) + 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 4322cc2db..c4af00c4f 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -112,6 +112,8 @@ class opengl33_renderer : public gfx_renderer { Texture( texture_handle const Texture ) const override; void Unload_Texture( texture_handle const Texture ) override; + void + Unload_Material( material_handle const Material ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 737c4b379..9f48c40b5 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -1928,6 +1928,21 @@ opengl_renderer::Unload_Texture( texture_handle const Texture ) { m_textures.unload( Texture ); } +void +opengl_renderer::Unload_Material( material_handle const Material ) { + + if( Material == null_handle ) { return; } + auto const &material { m_materials.material( Material ) }; + for( auto const texture : material.textures ) { + m_textures.unload( texture ); + } + for( auto const &variant : material.texture_variants ) { + for( auto const texture : variant ) { + m_textures.unload( texture ); + } + } +} + void opengl_renderer::Pick_Control_Callback( std::function Callback ) { diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index ef3a9f0f3..768acc19a 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -97,6 +97,8 @@ public: Texture( texture_handle const Texture ) const override; void Unload_Texture( texture_handle const Texture ) override; + void + Unload_Material( material_handle const Material ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/renderer.h b/rendering/renderer.h index 337d63925..7e3ef2eb2 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -105,6 +105,8 @@ public: // 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 + virtual 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; From 423d49b42cf7c69170d6004ec4d4e3f5480840e0 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 02:12:01 +0100 Subject: [PATCH 31/58] fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle --- utilities/physicslog.cpp | 33 ++++++++++++++++++--------------- vehicle/Driver.cpp | 4 +++- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index 19f18684b..d51d119b4 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -40,10 +40,10 @@ void keep_last(std::string &Text, std::size_t const Most) { physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : m_folder{std::move(Folder)}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { - // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse try { stop(); } catch (...) { + // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse } } @@ -81,28 +81,25 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { void physicslog_writer::stop() { std::jthread thread; + bool itself; { std::scoped_lock lock{m_mutex}; m_stopped = true; - // stopped from the writer itself, by the end of a run which failed in it: the files may be held by it, and - // another thread may be joining it already - if (m_writer == std::this_thread::get_id()) { - if (m_thread.joinable()) { - m_thread.request_stop(); - m_thread.detach(); - } - return; - } // taken by the first to stop, so it's joined once thread = std::move(m_thread); + itself = m_writer == std::this_thread::get_id(); } - if (thread.joinable()) { + // the stop asked outside the lock, which waking the writer takes + if (thread.joinable()) thread.request_stop(); - // the writer waits under the lock: taken once, it's either about to wait, seeing the stop, or waiting already - { std::scoped_lock lock{m_mutex}; } - m_wake.notify_all(); - thread.join(); + // 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 (thread.joinable()) + thread.join(); flush(); } @@ -114,6 +111,12 @@ void physicslog_writer::start() { } void physicslog_writer::run(std::stop_token const &Stop) { + // 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(); + }}; while (false == Stop.stop_requested()) { { std::unique_lock lock{m_mutex}; diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index d2ebd1fd7..07eaf4575 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2334,7 +2334,9 @@ 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(); // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every From b832d2fab957f87772f12a7a79454f647d20f879 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 02:13:09 +0100 Subject: [PATCH 32/58] fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. --- application/editormodetextures.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index ecf846431..e3423de5e 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -125,7 +125,7 @@ void editor_mode::thumbnails_trim() for (auto entry{browser.thumbnails.begin()}; entry != browser.thumbnails.end();) { auto const &thumbnail{entry->second}; - if (false == browser.refresh && (thumbnail.texture == null_handle || now - thumbnail.shown < kept)) + if (false == browser.refresh && ((thumbnail.texture == null_handle && thumbnail.material == null_handle) || now - thumbnail.shown < kept)) { ++entry; continue; From 99b93abd64ece61377dfdfbeda6ef30055144b75 Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 12:47:22 +0100 Subject: [PATCH 33/58] fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_physicslog.cpp | 32 +++++++++++- utilities/physicslog.cpp | 96 +++++++++++++++++++++++++++------- utilities/physicslog.h | 11 ++++ 3 files changed, 117 insertions(+), 22 deletions(-) diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index 3189c424f..b61755d4d 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -32,8 +32,9 @@ public: 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 { - std::ifstream file{m_path / (Name + ".dat")}; + 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; @@ -155,6 +156,33 @@ TEST_CASE("physicslog: a log begun anew while its file can't be written drops wh 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: stopping twice, from two threads at once, writes once and ends") { log_folder folder{"stoptwice"}; physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index d51d119b4..25ab2556d 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include +#include #include #include #include @@ -35,9 +36,19 @@ void keep_last(std::string &Text, std::size_t const Most) { Text.erase(0, cut == std::string::npos ? Text.size() : cut + 1); } +// 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 + } +} + } // namespace -physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : m_folder{std::move(Folder)}, m_interval{Interval} {} +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { try { @@ -73,7 +84,7 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { auto done{std::make_shared>()}; auto ended{done->get_future()}; std::thread([this, done] { - flush(); + flush_safely(); done->set_value(); }).detach(); return ended.wait_for(Timeout) == std::future_status::ready; @@ -100,7 +111,26 @@ void physicslog_writer::stop() { } if (thread.joinable()) thread.join(); - flush(); + flush_safely(); +} + +std::filesystem::path physicslog_writer::file(std::string const &Name) const { + auto const name{Name + ".dat"}; +#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 + '/' + Name + ".dat"; } void physicslog_writer::start() { @@ -124,7 +154,17 @@ void physicslog_writer::run(std::stop_token const &Stop) { if (m_wake.wait_for(lock, m_interval, [&Stop] { return Stop.stop_requested(); })) return; } + flush_safely(); + } +} + +void physicslog_writer::flush_safely() noexcept { + try { flush(); + } 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"); } } @@ -142,28 +182,22 @@ void physicslog_writer::write() { for (auto &[name, lines] : taken) { if (lines.text.empty() && false == lines.fresh) continue; - auto const path{m_folder / (name + ".dat")}; - // how long it was, to be 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 - auto const before{lines.fresh ? 0 : std::filesystem::file_size(path, error)}; - auto const existed{false == lines.fresh && false == static_cast(error)}; - // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" - std::ofstream file{path, lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; - if (file.is_open()) { - if (lines.fresh) - file << lines.header; - file << lines.text; + // 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 { + written = write_log(name, lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; } - file.close(); - if (false == file.fail()) { + if (written) { if (m_failed.erase(name) > 0) - WriteLog("Physics log: " + path.string() + " written again"); + WriteLog("Physics log: " + shown(name) + " written again"); continue; } - if (existed) - std::filesystem::resize_file(path, before, error); if (m_failed.insert(name).second) - ErrorLog("Bad physics log: can't write " + path.string() + ", its last lines are kept for the next try"); + ErrorLog("Bad physics log: " + problem + " " + shown(name) + ", its last lines are kept for the next try"); failed.emplace(name, std::move(lines)); } if (failed.empty()) @@ -183,3 +217,25 @@ void physicslog_writer::write() { now = std::move(lines); } } + +bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { + auto const path{file(Name)}; + std::error_code error; + // how long it was, to be 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 + auto const before{Lines.fresh ? 0 : std::filesystem::file_size(path, error)}; + auto const existed{false == Lines.fresh && false == static_cast(error)}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; + if (stream.is_open()) { + if (Lines.fresh) + stream << Lines.header; + stream << Lines.text; + } + stream.close(); + if (false == stream.fail()) + return true; + if (existed) + std::filesystem::resize_file(path, before, error); + return false; +} diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 9ecb88349..59ed34828 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -44,6 +44,9 @@ public: bool flush_for(std::chrono::milliseconds Timeout); // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); + // the file of the log Name, made of its bytes as they are: those of the code page of a scenery (1250) too, on a + // Windows set to UTF-8, where the standard library throws making a path of them. there they become U+FFFD + std::filesystem::path file(std::string const &Name) const; private: struct pending { @@ -55,10 +58,18 @@ private: // 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 + void flush_safely() noexcept; // called with m_filemutex held void write(); + // 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; + // the file of the log Name, for the log of the simulator + std::string shown(std::string const &Name) const; std::filesystem::path const m_folder; + std::string const m_shownfolder; std::chrono::milliseconds const m_interval; std::mutex m_mutex; // the lines kept and the thread std::map m_pending; From 549899567258f891f62241a55185d5639239833f Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 12:47:22 +0100 Subject: [PATCH 34/58] fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 --- blackbox_doc.md | 3 ++- simulation/blackboxrecorder.cpp | 16 ++++++++++------ simulation/blackboxrecorder.h | 6 ++++-- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index 3573b4271..8b4e23e0f 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -30,7 +30,8 @@ for a while doesn't lose its lines: they are written once it can be, the last 64 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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 6d0f76502..efd92c3fc 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -238,22 +238,26 @@ void blackbox_recorder::update(double const Deltatime) { // "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; - if (m_time >= m_cabdue) { - write_cab(); - m_cabdue = std::max(m_cabdue + cabinterval, m_time); - } - // with the physics logs on, each driver writes its own all the time + // with the physics logs on, each driver writes its own all the time. 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 (false == WriteLogFlag && 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); + } if (m_time >= m_cameradue) { write_camera(); m_cameradue = std::max(m_cameradue + camerainterval, m_time); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 67742b24e..a3aaf5d0f 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -32,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. @@ -112,6 +113,7 @@ 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}; From 0a1c4fd42505a5b80b0a6e7fb2da7a87205fa14d Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 13:00:16 +0100 Subject: [PATCH 35/58] fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named :, and its log went to physicslog/:.dat. On NTFS that isn't even an error: it is the stream .dat of the file , which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 --- blackbox_doc.md | 5 ++++- simulation/blackboxrecorder.cpp | 2 +- tests/unit/test_physicslog.cpp | 23 +++++++++++++++++++++++ utilities/physicslog.cpp | 26 ++++++++++++++++++++++++-- utilities/physicslog.h | 19 +++++++++++-------- 5 files changed, 63 insertions(+), 12 deletions(-) diff --git a/blackbox_doc.md b/blackbox_doc.md index 8b4e23e0f..5dc8f7b71 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -16,7 +16,10 @@ recording started at), next to the `.dat` logs of the vehicles when those are on 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. A log is the driver's, named after the vehicle that driver began in: it +`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 diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index efd92c3fc..b30d8a6c7 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -513,7 +513,7 @@ void blackbox_recorder::keep_tape_line() { auto const &name{driver->physicslog_name()}; if (m_tapes.insert(name).second) { PhysicsLogs.begin(name, TController::physicslog_header()); - WriteLog(std::format("Black box: the physics log \"physicslog/{}.dat\" begun", name)); + WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); } PhysicsLogs.append(name, driver->physicslog_line()); } diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index b61755d4d..7a341b4f1 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -183,6 +183,29 @@ TEST_CASE("physicslog: a vehicle named in the code page of its scenery has its l 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}}; diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index 25ab2556d..208fc7b01 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -12,10 +12,12 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include +#include #include #include #include #include +#include #include #include @@ -36,6 +38,26 @@ void keep_last(std::string &Text, std::size_t const 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 { @@ -115,7 +137,7 @@ void physicslog_writer::stop() { } std::filesystem::path physicslog_writer::file(std::string const &Name) const { - auto const name{Name + ".dat"}; + 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 @@ -130,7 +152,7 @@ std::filesystem::path physicslog_writer::file(std::string const &Name) const { } std::string physicslog_writer::shown(std::string const &Name) const { - return m_shownfolder + '/' + Name + ".dat"; + return m_shownfolder + '/' + file_name(Name); } void physicslog_writer::start() { diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 59ed34828..0f397d27c 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -20,10 +20,11 @@ http://mozilla.org/MPL/2.0/. #include #include -// the physics logs, /.dat. 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. 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 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. 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 class physicslog_writer { public: explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); @@ -44,9 +45,13 @@ public: bool flush_for(std::chrono::milliseconds Timeout); // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); - // the file of the log Name, made of its bytes as they are: those of the code page of a scenery (1250) too, on a - // Windows set to UTF-8, where the standard library throws making a path of them. there they become U+FFFD + // 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; private: struct pending { @@ -65,8 +70,6 @@ private: void write(); // 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; - // the file of the log Name, for the log of the simulator - std::string shown(std::string const &Name) const; std::filesystem::path const m_folder; std::string const m_shownfolder; From bcecfe29645ab7a16b1bc330a1b040a89965b91b Mon Sep 17 00:00:00 2001 From: maj00r Date: Mon, 16 Nov 2026 15:59:57 +0100 Subject: [PATCH 36/58] refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 --- global_include/interfaces/IMaterial.h | 6 ++++++ model/material.h | 7 +++++++ rendering/opengl33renderer.cpp | 12 ------------ rendering/opengl33renderer.h | 2 -- rendering/openglrenderer.cpp | 15 --------------- rendering/openglrenderer.h | 2 -- rendering/renderer.cpp | 10 ++++++++++ rendering/renderer.h | 2 +- 8 files changed, 24 insertions(+), 32 deletions(-) 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/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/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index d3dfef6e9..800f33dcf 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2575,18 +2575,6 @@ void opengl33_renderer::Unload_Texture(texture_handle const Texture) m_textures.unload(Texture); } -void opengl33_renderer::Unload_Material(material_handle const Material) -{ - if (Material == null_handle) - return; - auto const &material{m_materials.material(Material)}; - for (auto const texture : material.textures) - m_textures.unload(texture); - for (auto const &variant : material.texture_variants) - for (auto const texture : variant) - 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 c4af00c4f..4322cc2db 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -112,8 +112,6 @@ class opengl33_renderer : public gfx_renderer { Texture( texture_handle const Texture ) const override; void Unload_Texture( texture_handle const Texture ) override; - void - Unload_Material( material_handle const Material ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 9f48c40b5..737c4b379 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -1928,21 +1928,6 @@ opengl_renderer::Unload_Texture( texture_handle const Texture ) { m_textures.unload( Texture ); } -void -opengl_renderer::Unload_Material( material_handle const Material ) { - - if( Material == null_handle ) { return; } - auto const &material { m_materials.material( Material ) }; - for( auto const texture : material.textures ) { - m_textures.unload( texture ); - } - for( auto const &variant : material.texture_variants ) { - for( auto const texture : variant ) { - m_textures.unload( texture ); - } - } -} - void opengl_renderer::Pick_Control_Callback( std::function Callback ) { diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index 768acc19a..ef3a9f0f3 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -97,8 +97,6 @@ public: Texture( texture_handle const Texture ) const override; void Unload_Texture( texture_handle const Texture ) override; - void - Unload_Material( material_handle const Material ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/renderer.cpp b/rendering/renderer.cpp index d9d4b5df0..7e7d93e94 100644 --- a/rendering/renderer.cpp +++ b/rendering/renderer.cpp @@ -39,6 +39,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 7e3ef2eb2..7edf135da 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -106,7 +106,7 @@ public: // 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 - virtual void Unload_Material( material_handle const Material ) {} + 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; From 267d5b3a8f5c01dbe77f25255c4237665f8e6efe Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:55:33 +0100 Subject: [PATCH 37/58] AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table since ce87aa0e (#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was before ce87aa0e and as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r --- CMakeLists.txt | 1 + tests/unit/test_braking_curve.cpp | 195 ++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 115 +++++------------- vehicle/Driver.h | 1 + vehicle/brakingcurve.cpp | 86 +++++++++++++ vehicle/brakingcurve.h | 54 +++++++++ 6 files changed, 366 insertions(+), 86 deletions(-) create mode 100644 tests/unit/test_braking_curve.cpp create mode 100644 vehicle/brakingcurve.cpp create mode 100644 vehicle/brakingcurve.h diff --git a/CMakeLists.txt b/CMakeLists.txt index f80a93d21..1d5c0ad33 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -554,6 +554,7 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp new file mode 100644 index 000000000..7102d06e0 --- /dev/null +++ b/tests/unit/test_braking_curve.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakingcurve.h" + +#include +#include + +// the deceleration the AI asks for on its way down to a stop or a lower speed ahead, outside of the final approach +// (TController::adjust_desired_speed_for_braking_curve). in shunting the brake table of the consist isn't worked out +// and stays at zero; planned from it, the curve asked for next to no braking, and shunting engines ran through the +// signals they were to stop at. + +namespace { + +auto constexpr tablesize{20}; +using brake_values = std::array; + +// what the AI holds in shunting: nothing worked out +struct zeroed_table { + brake_values a0{}; + brake_values a1{}; + + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 100.0}; } +}; + +// a train brake that gives the same deceleration at every speed, full service 0.05 + 12 * 0.1 = 1.25 m/s2 +struct flat_table { + brake_values a0{}; + brake_values a1{}; + + flat_table() { + a0.fill(0.05); + a1.fill(0.1); + } + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 120.0}; } +}; + +braking_curve::approach stop_at(double const Speed, double const Distance) { + braking_curve::approach approach{}; + approach.speed = Speed; + approach.target = 0.0; + approach.distance = Distance; + approach.offset = 0.0; // the braking point of a stop, outside of a train, is the stop itself (VelNext * multiplier) + approach.speedup_horizon = 30.0 / 3.6; + approach.fill_horizon = 30.0 / 3.6; + return approach; +} + +// the AI in shunting leaves the brake alone for a demand weaker than this (TController::fAccThreshold) +auto constexpr shunting_brake_threshold{-0.2}; + +struct shunting_run { + double speed; // [km/h] + double left; // to the stop point [m] + bool braked_at_once; +}; + +// a shunting engine braking to a stop point the way the AI drives it: the brake follows the demand once it is past +// the threshold, the engine coasts otherwise. the braking curve gives way near the point to the final approach, at +// walking pace (10 km/h, 5 km/h in the last 10 m) +shunting_run brake_to_point(double const Speed, double const Distance, zeroed_table const &Table) { + auto const table{Table.table()}; + auto const timestep{0.1}; + shunting_run run{Speed, Distance, false}; + run.braked_at_once = braking_curve::demand(stop_at(run.speed, run.left), &table) < shunting_brake_threshold; + while ((run.speed > (run.left > 10.0 ? 10.0 : 5.0)) && (run.left > -50.0)) { + auto const demand{braking_curve::demand(stop_at(run.speed, run.left), &table)}; + auto const acceleration{demand < shunting_brake_threshold ? demand : 0.0}; + run.speed = std::max(0.0, run.speed + 3.6 * acceleration * timestep); + run.left -= run.speed / 3.6 * timestep; + } + return run; +} + +} // namespace + +TEST_CASE("braking curve: a brake table left at zero isn't known, one worked out is") { + CHECK_FALSE(zeroed_table{}.table().known()); + CHECK(flat_table{}.table().known()); +} + +TEST_CASE("braking curve: shunting to a point asks for the constant deceleration over the distance left") { + zeroed_table const shunting; + auto const table{shunting.table()}; + auto approach{stop_at(33.0, 186.0)}; + SUBCASE("coasting") { approach.acceleration = 0.0; } + SUBCASE("still speeding up") { approach.acceleration = 0.2; } + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(-33.0 * 33.0 / (25.92 * 186.0 + 0.1))); + CHECK(demand == doctest::Approx(braking_curve::demand(approach, nullptr))); + // enough for the AI to put the brake on + CHECK(demand < shunting_brake_threshold); +} + +TEST_CASE("braking curve: a shunting engine braking to a point gets down to walking pace short of it") { + zeroed_table const shunting; + auto speed{0.0}; + auto distance{0.0}; + SUBCASE("33 km/h, 186 m") { + speed = 33.0; + distance = 186.0; + } + SUBCASE("40 km/h, 186 m") { + speed = 40.0; + distance = 186.0; + } + SUBCASE("33 km/h, 120 m") { + speed = 33.0; + distance = 120.0; + } + SUBCASE("25 km/h, 60 m") { + speed = 25.0; + distance = 60.0; + } + CAPTURE(speed); + CAPTURE(distance); + + auto const run{brake_to_point(speed, distance, shunting)}; + + CHECK(run.braked_at_once); + CHECK(run.left > 0.0); + CHECK(run.speed <= 10.0); +} + +TEST_CASE("braking curve: a train with a worked out brake table plans along the shape of its brake") { + flat_table const train; + auto const table{train.table()}; + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.fill_horizon = 6.0; + approach.speedup_horizon = 5.0; + + SUBCASE("before the brake is applied, the room it takes to fill is kept") { + auto const room{580.0 - 80.0 / 3.6 * 6.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, room + 0.1 / 25.92, 0.0, table))); + // with the same deceleration at every speed the shape is the constant deceleration over that room + CHECK(demand == doctest::Approx(-(80.0 / 3.6) * (80.0 / 3.6) / (2.0 * room)).epsilon(0.01)); + } + SUBCASE("once the brake is applied, the whole distance is used") { + approach.brake_applied = true; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, 580.0 + 0.1 / 25.92, 0.0, table))); + } + SUBCASE("still speeding up, it plans from the speed reached once the brake acts") { + approach.acceleration = 0.3; + auto const reached{80.0 + 3.6 * 5.0 * 0.3}; + auto const distance{600.0 - (80.0 + reached) * 0.5 / 3.6 * 5.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(reached, 0.0, distance - 20.0 + 0.1 / 25.92, 0.0, table))); + } +} + +TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { + // a table that grips harder as the train slows, on a gradient; the demands were worked out with the + // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) + brake_values a0{}; + brake_values a1{}; + for (auto i{1}; i <= tablesize; ++i) { + a0[i] = 0.12 - 0.003 * i; + a1[i] = 0.06 - 0.001 * i; + } + braking_curve::brake_table const table{a0.data(), a1.data(), tablesize, 120.0}; + REQUIRE(table.full_braking(80.0) == doctest::Approx(0.645)); + REQUIRE(table.full_braking(10.0) == doctest::Approx(0.825)); + + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.gravity = 0.1; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + auto expected{0.0}; + SUBCASE("downhill, coasting, the brake still to be applied") { expected = -0.4926656801067293; } + SUBCASE("downhill, the brake applied") { + approach.brake_applied = true; + expected = -0.37739905908238147; + } + SUBCASE("downhill, still speeding up") { + approach.acceleration = 0.3; + expected = -0.5330117415264249; + } + SUBCASE("uphill, down to 40 km/h") { + approach = stop_at(100.0, 900.0); + approach.target = 40.0; + approach.gravity = -0.08; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + expected = -0.40930710539221765; + } + + CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 07eaf4575..0d80e105f 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "world/mtable.h" #include "vehicle/DynObj.h" @@ -210,6 +211,7 @@ void TSpeedPos::Clear() fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; fDist = 0.0; + bSeenAhead = false; vPos = glm::dvec3(0, 0, 0); trTrack = nullptr; // brak wskaźnika }; @@ -326,6 +328,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -411,9 +416,18 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } +// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] +constexpr double SeenAheadTolerance { 5.0 }; + bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) { // zapamiętanie zdarzenia fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the + // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head + // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than + // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't + // be told from one stopped just short of it, which really passes the signal if it goes on + bSeenAhead = ( dist >= -SeenAheadTolerance ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -908,6 +922,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { if( Passedbefore || false == TestFlag( Point.iFlags, spElapsed ) + || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -8189,54 +8204,6 @@ uphill_coasting_speed( double const Distance, double const Gravity ) { return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); } -// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train -// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the -// consist brake table says it does (cast iron blocks grip harder as the train slows) -struct consist_brake_table { - double const *a0; // deceleration at handle position 1, by speed - double const *a1; // deceleration added by each quarter of a position, by speed - int size; // entries, up to the vehicle's top speed - double vmax; // the vehicle's top speed [km/h] - - // deceleration [m/s2] of a full service application at Kmh - double full_braking( double const Kmh ) const { - auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) }; - return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); } -}; - -static double -shaped_braking_demand( - double const Velocity, double const Target, double const Distance, double const Gravity, - consist_brake_table const &Table ) { - - auto const fullbraking = [&Table]( double const Kmh ) { - return Table.full_braking( Kmh ); }; - auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) { - auto const steps { 24 }; - auto const step { ( Velocity - Target ) / steps }; - auto distance { 0.0 }; - for( auto i { 0 }; i < steps; ++i ) { - auto const kmh { Target + ( i + 0.5 ) * step }; - auto const deceleration { Ratio * fullbraking( kmh ) - Gravity }; - if( deceleration <= 0.001 ) { - return std::numeric_limits::max(); - } - distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration; - } - return distance; }; - - auto low { 0.0 }; - auto high { 3.0 }; - if( travel( high ) > Distance ) { - return Gravity - high * fullbraking( Velocity ); - } - for( auto i { 0 }; i < 30; ++i ) { - auto const middle { 0.5 * ( low + high ) }; - ( travel( middle ) > Distance ? low : high ) = middle; - } - return Gravity - high * fullbraking( Velocity ); -} - // outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the // direction of travel void @@ -8263,43 +8230,19 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? stopping_margin() : // the same stopping point as the final approach VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // a pneumatic brake acts on the state the train will be in once it has responded; while the - // train is still speeding up, plan the deceleration from there, so more is asked for at once - auto velocity { Vel }; - auto distance { ActualProximityDist }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AbsAccS > 0.0 ) ) { - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - velocity = Vel + 3.6 * horizon * AbsAccS; - distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon ); - } - auto const brakingroom { - std::max( - distance - brakingpointoffset, - std::min( - distance, - brakingpointoffset ) ) }; - auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) { - // follow the shape of the consist brake force over speed rather than assume a constant - // deceleration, over the distance left once the brake has had time to fill (while the - // train is still speeding up, the prediction above has taken that off already) - auto room { brakingroom }; - if( ( AbsAccS <= 0.0 ) - && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const brakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - room = std::max( - 0.5 * brakingroom, - brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, brakea0 ) ); - } - deceleration = shaped_braking_demand( - velocity, VelNext, room + 0.1 / 25.92, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ); - } + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { return; @@ -8350,7 +8293,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { AccDesired = ( BrakeSystem == TBrakeSystem::Pneumatic ? // cast iron blocks grip harder as the train comes to a stand - shaped_braking_demand( + braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index bfeeb1b16..0794799dc 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -164,6 +164,7 @@ class TSpeedPos int iFlags{ spNone }; // flagi typu wpisu do tabelki bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) + bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train glm::dvec3 vPos; // współrzędne XYZ do liczenia odległości struct { diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp new file mode 100644 index 000000000..d39ee2868 --- /dev/null +++ b/vehicle/brakingcurve.cpp @@ -0,0 +1,86 @@ +/* +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/brakingcurve.h" + +#include +#include + +namespace braking_curve { + +double brake_table::full_braking(double const Kmh) const { + auto const index{std::clamp(static_cast(size * Kmh / std::max(1.0, vmax)), 1, size)}; + return std::max(0.01, a0[index] + 12.0 * a1[index]); +} + +bool brake_table::known() const { + // a worked out table holds at least the rolling resistance term at every speed + return a0[size] > 0.0; +} + +double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { + + auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { + auto const steps{24}; + auto const step{(Velocity - Target) / steps}; + auto distance{0.0}; + for (auto i{0}; i < steps; ++i) { + auto const kmh{Target + (i + 0.5) * step}; + auto const deceleration{Ratio * Table.full_braking(kmh) - Gravity}; + if (deceleration <= 0.001) { + return std::numeric_limits::max(); + } + distance += (kmh / 3.6) * (step / 3.6) / deceleration; + } + return distance; + }; + + auto low{0.0}; + auto high{3.0}; + if (travel(high) > Distance) { + return Gravity - high * Table.full_braking(Velocity); + } + for (auto i{0}; i < 30; ++i) { + auto const middle{0.5 * (low + high)}; + (travel(middle) > Distance ? low : high) = middle; + } + return Gravity - high * Table.full_braking(Velocity); +} + +double demand(approach const &Approach, brake_table const *Pneumatictable) { + + // a pneumatic brake acts on the state the train will be in once it has responded; while the + // train is still speeding up, plan the deceleration from there, so more is asked for at once + // both plans are made from the brake table of the consist; with none (in shunting it isn't worked out, and planning + // from its zeroes would ask for no braking at all) the braking curve is the constant deceleration over the distance left + auto const *table{(Pneumatictable != nullptr) && Pneumatictable->known() ? Pneumatictable : nullptr}; + auto velocity{Approach.speed}; + auto distance{Approach.distance}; + if ((table != nullptr) && (Approach.acceleration > 0.0)) { + auto const horizon{Approach.speedup_horizon}; + velocity = Approach.speed + 3.6 * horizon * Approach.acceleration; + distance = std::max(0.5 * Approach.distance, Approach.distance - (Approach.speed + velocity) * 0.5 / 3.6 * horizon); + } + auto const brakingroom{std::max(distance - Approach.offset, std::min(distance, Approach.offset))}; + if ((table == nullptr) || (velocity <= Approach.target)) { + return (Approach.target * Approach.target - velocity * velocity) / (25.92 * brakingroom + 0.1); + } + // follow the shape of the consist brake force over speed rather than assume a constant + // deceleration, over the distance left once the brake has had time to fill (while the + // train is still speeding up, the prediction above has taken that off already) + auto room{brakingroom}; + if ((Approach.acceleration <= 0.0) && (false == Approach.brake_applied)) { + // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + room = std::max(0.5 * brakingroom, brakingroom - Approach.speed / 3.6 * Approach.fill_horizon); + } + return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); +} + +} // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h new file mode 100644 index 000000000..6ed40d9bb --- /dev/null +++ b/vehicle/brakingcurve.h @@ -0,0 +1,54 @@ +/* +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 + +// the deceleration the AI asks for on its way down to a lower speed or a stop ahead, outside of the final +// approach (TController::adjust_desired_speed_for_braking_curve) +namespace braking_curve { + +// the deceleration table of the consist brake, by speed (TController::fBrake_a0, fBrake_a1). it is worked out +// for a train only (Obey_train, Bank); in shunting it stays at zero +struct brake_table { + double const *a0; // deceleration at handle position 1, by speed; a0[1..size] + double const *a1; // deceleration added by each quarter of a position, by speed + int size; // entries, up to the vehicle's top speed + double vmax; // the vehicle's top speed [km/h] + + // deceleration [m/s2] of a full service application at Kmh + double full_braking(double Kmh) const; + // whether the table is worked out + bool known() const; +}; + +// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train +// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the +// table says it does (cast iron blocks grip harder as the train slows) +double shaped_demand(double Velocity, double Target, double Distance, double Gravity, brake_table const &Table); + +// where the train is on its way down to Target +struct approach { + double speed; // present speed in the direction of travel [km/h] + double target; // speed to get down to [km/h] + double distance; // to where the speed is to be down [m] + double offset; // the braking point that far short of it [m] + double gravity; // tangential acceleration of the gradient [m/s2], negative uphill + double acceleration; // present acceleration of the train [m/s2] + bool brake_applied; // the train brake handle is past running + double speedup_horizon; // how long the present acceleration lasts while speeding up [s] + double fill_horizon; // how long the brake takes to fill once applied [s] +}; + +// acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake +// (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has +// responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at +// zero, as in shunting) it is the constant deceleration over the distance left +double demand(approach const &Approach, brake_table const *Pneumatictable); + +} // namespace braking_curve From 8bda0275f3e8bacd66c6280848c975f874e4b7c8 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:24:28 +0100 Subject: [PATCH 38/58] fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414) 623c4f82 (#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r --- vehicle/Camera.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index e2fe58464..55d4691d1 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -192,9 +192,12 @@ void TCamera::Update() bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { + // the roll (z) is multiplied in first, so it acts last, about the line of sight: the sway of the cab tilts the view + // the same way wherever the head is turned, as it did in 26.05. the order matters only with a roll (the cab shake, + // or the angles of a camera entry of the scenery) + Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia - Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie if( m_owner != nullptr && false == DebugCameraFlag ) { From 4b80d3c4285f278d2b5f08f01e6013c0def17dc0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:24:42 +0100 Subject: [PATCH 39/58] fix(particles): the smoke of a cold diesel keeps the colour of its template (#413) bcb9e644 (#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r --- rendering/particles.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 8ccb728dd..517fec751 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -168,9 +168,9 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { if( m_ownertype == owner_type::vehicle ) { auto const &mover { *m_owner.vehicle->MoverParameters }; - if( Global.AirTemperature <= 5.f || mover.dizel_heat.Ts < 45.f ) { - m_emitter.color = glm::vec3{ 128, 128, 128 }; - } + // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant + // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the + // emitter colour, so the smoke turned pure white, glowing at night, and never changed back // a vehicle taken off the tracks (gone through a portal, or waiting in the pool of the road traffic) puffs no more, // the particles it already let out fade away as usual m_spawncount = ( From 72c69d9249cbffb09ee079522f4b9fa32cb0e5f0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:01 +0100 Subject: [PATCH 40/58] Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and since e230d7b9 it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r --- application/application.cpp | 36 ++++++++++++++++++++++++++++++++++ model/Texture.cpp | 28 +++++++++++++++++++++++--- model/Texture.h | 10 ++++++++++ rendering/opengl33renderer.cpp | 2 ++ 4 files changed, 73 insertions(+), 3 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index b8decc5f1..12bc9020a 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -54,6 +54,7 @@ http://mozilla.org/MPL/2.0/. #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "version.lib") +#include #endif #ifdef __unix__ @@ -65,6 +66,36 @@ eu07_application Application; screenshot_manager screenshot_man; ui_layer uilayerstaticinitializer; +namespace +{ +#ifdef _WIN32 +// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms. +// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up +// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or +// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the +// main loop, as it costs some power for as long as it's held +bool timer_period_set{false}; +#endif + +// asks for the finer timer once, when fpslimit is set +void begin_timer_period() +{ +#ifdef _WIN32 + if (!timer_period_set && Global.minframetime.count() > 0.f) + timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR); +#endif +} + +void end_timer_period() +{ +#ifdef _WIN32 + if (timer_period_set) + timeEndPeriod(1); + timer_period_set = false; +#endif +} +} // namespace + #ifdef _WIN32 extern "C" { @@ -352,6 +383,8 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; } + // fpslimit is known now + begin_timer_period(); // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is @@ -686,6 +719,8 @@ int eu07_application::run() // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { + // fpslimit may come from the config block of the scenery, read after the settings + begin_timer_period(); std::this_thread::sleep_until(*nextframe); } } @@ -782,6 +817,7 @@ void eu07_application::exit() if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + end_timer_period(); step("done"); StopLogService(); auto it = Global.threads.find("LogService"); diff --git a/model/Texture.cpp b/model/Texture.cpp index 9b428202b..bd13ecf2c 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -323,6 +323,7 @@ GLint readback_format( GLint const Internalformat ) { std::array opengl_texture::units = { 0 }; GLint opengl_texture::m_activeunit = -1; +std::atomic opengl_texture::m_unitcachestale { false }; std::unordered_map opengl_texture::precompressed_formats = { @@ -729,9 +730,10 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 is_static = true; is_ready = true; } - // the name may be a new one, and the unit active took the texture past the unit cache - for (auto &unit : units) - unit = -1; + // the name may be a new one, and the unit active took the texture past the unit cache. this runs on the python upload + // thread too (python.threadedupload), so the cache is only marked here: clearing it outright raced the drawing thread + // filling it for a multi-bind, and an object got the texture of the one drawn before it for a frame + invalidate_unit_cache(); } void @@ -1263,6 +1265,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; if (GLAD_GL_ARB_direct_state_access) @@ -1630,6 +1633,25 @@ opengl_texture::reset_unit_cache() { m_activeunit = -1; } +void +opengl_texture::invalidate_unit_cache() { + + m_unitcachestale.store( true ); +} + +void +opengl_texture::sync_unit_cache() { + + // a plain load first: bind() calls this for every texture, and a read-modify-write each time would cost more + if( ( false == m_unitcachestale.load() ) + || ( false == m_unitcachestale.exchange( false ) ) ) { + return; + } + for( auto &unit : units ) { + unit = -1; + } +} + void opengl_texture::set_filtering() const { diff --git a/model/Texture.h b/model/Texture.h index 20221fcea..2fbd76a4f 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include "winheaders.h" @@ -47,6 +48,13 @@ struct opengl_texture : public ITexture { set_components_hint( GLint hint ) override; static void reset_unit_cache(); + // marks the unit cache as not to be trusted. safe to call from any thread: the cache itself is + // cleared by the thread drawing with it, the next time it binds textures (sync_unit_cache) + static void + invalidate_unit_cache(); + // clears the unit cache if a thread marked it as not to be trusted since. called before the cache is read + static void + sync_unit_cache(); virtual int get_width() const override { return data_width; } @@ -100,6 +108,8 @@ struct opengl_texture : public ITexture { GLenum target = GL_TEXTURE_2D; static std::array units; static GLint m_activeunit; + // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread + static std::atomic m_unitcachestale; public: // methods diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..80ef4f670 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2457,6 +2457,8 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel if (GLAD_GL_ARB_multi_bind) { + // the cache may have been marked stale by the python upload thread + opengl_texture::sync_unit_cache(); GLuint lastdiff = 0; size_t i; for (i = 0; i < gl::MAX_TEXTURES; i++) From a1fbdf47c6c9bc1808a08ef8d52eaeeb2d7939c3 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:03 +0100 Subject: [PATCH 41/58] fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r --- application/drivermode.cpp | 19 +++++++++++++++---- application/drivermode.h | 1 + vehicle/DynObj.cpp | 31 +++++++++++++++++++++++++++++-- vehicle/DynObj.h | 5 +++++ 4 files changed, 50 insertions(+), 6 deletions(-) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index cde7e80d7..8c3b3665f 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" + +#include + /* namespace input { @@ -627,6 +630,12 @@ bool driver_mode::is_command_processor() const return true; } +double driver_mode::shake_fraction() const +{ + // how far the simulation time has got from the last step of the shake towards the next one + return std::clamp(m_secondaryupdateaccumulator / m_secondaryupdaterate, 0.0, 1.0); +} + void driver_mode::update_camera(double const Deltatime) { @@ -770,7 +779,8 @@ void driver_mode::update_camera(double const Deltatime) // ale bez odbicia Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 } - auto const shakeangles{simulation::Train->Dynamic()->shake_angles()}; + auto const *dynamic{simulation::Train->Dynamic()}; + auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* @@ -791,8 +801,9 @@ void driver_mode::update_camera(double const Deltatime) } float const shakescale{FreeFlyModeFlag ? 5.0f : 1.0f}; - auto shakencamerapos{Camera.m_owneroffset + - shakescale * glm::vec3(1.5 * Camera.m_owner->ShakeState.offset.x, 2.0 * Camera.m_owner->ShakeState.offset.y, 1.5 * Camera.m_owner->ShakeState.offset.z)}; + // the shake steps at a fixed rate, the frames come at their own: taken at the frame's moment between the steps, it moves as smoothly as the vehicle + auto const shake{Camera.m_owner->shake_between(shake_fraction())}; + auto shakencamerapos{Camera.m_owneroffset + shakescale * glm::vec3(1.5 * shake.offset.x, 2.0 * shake.offset.y, 1.5 * shake.offset.z)}; Camera.Pos = Camera.m_owner->GetWorldPosition(FreeFlyModeFlag ? glm::dvec3(shakencamerapos) : // TODO: vehicle collision box for the external vehicle camera simulation::Train->clamp_inside(shakencamerapos)); @@ -800,7 +811,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index e0406043d..06ce32ee4 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -91,6 +91,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..453dd743a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -2369,6 +2370,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ShakeSpring.Init( 125.0 ); BaseShake = baseshake_config {}; ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; // McZapkie-250202 /* @@ -8236,6 +8238,8 @@ void TDynamicObject::OverheadTrack(float o) void TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu @@ -8360,9 +8364,32 @@ TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int con std::pair TDynamicObject::shake_angles() const { + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + return { - std::atan( ShakeState.velocity.x * BaseShake.angle_scale.x ), - std::atan( ShakeState.velocity.z * BaseShake.angle_scale.z ) }; + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } void diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..3089258e6 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -918,6 +918,11 @@ public: glm::dvec3 velocity{}; // current shaking vector glm::dvec3 offset{}; // overall shake-driven offset from base position } ShakeState; + shake_state ShakeStateBefore; // the state before the last step of update_shake + // the shake between the last two steps of update_shake: 0 the state before the last step, 1 the state after it. + // the steps are fixed and the frames aren't, so the camera takes the state at its own moment between the two + shake_state shake_between( double const Fraction ) const; + std::pair shake_angles( shake_state const &State ) const; glm::dvec3 modelShake; }; From 1b26caca2455e7f106e836b89bd6183c7bd46978 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:29 +0100 Subject: [PATCH 42/58] fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1 d1f16411 (#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again; fa2ed089 swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as before d1f16411. The call added since (stepped_uc_value, 00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers and go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged is included twice, which is harmless. --------- Co-authored-by: maj00r --- McZapkie/Mover.cpp | 34 ++++++++++++++++++---------------- rendering/opengl33renderer.cpp | 2 +- rendering/openglparticles.cpp | 4 +++- rendering/openglrenderer.cpp | 4 ++-- tests/unit/test_utilities.cpp | 29 +++++++++++++++++++++++++---- utilities/utilities.h | 17 +++++++++-------- vehicle/DynObj.cpp | 19 ++++++++++--------- vehicle/Train.cpp | 13 ++++++++----- 8 files changed, 76 insertions(+), 46 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..15aa396c2 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -900,7 +900,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem PantPress = ScndPipePress; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = std::clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else @@ -912,7 +912,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } - PantPress = std::clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s @@ -3950,7 +3950,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not auto const initialstate{CompressorListPos}; - CompressorListPos = std::clamp(State, 0, CompressorListPosNo); + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); if (Notify != range_t::local) { @@ -5602,7 +5602,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; @@ -5900,7 +5900,7 @@ double TMoverParameters::TractionForce(double dt) if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -7755,7 +7755,9 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr { Progress = 0.0; } - return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); } } // namespace @@ -7839,18 +7841,18 @@ void TMoverParameters::CheckEIMIC(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -7957,7 +7959,7 @@ void TMoverParameters::CheckEIMIC(double dt) eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } void TMoverParameters::CheckSpeedCtrl(double dt) @@ -8015,7 +8017,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -8944,7 +8946,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun } LoadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); ComputeMass(); return true; } @@ -8989,7 +8991,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam { // pusto lub rozładowano żądaną ilość LoadStatus = 4; // skończony rozładunek - LoadAmount = std::clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny } if (LoadAmount == 0.f) { @@ -12853,7 +12855,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); return OK; } @@ -13255,7 +13257,7 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "DoorPermit") diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 80ef4f670..3a3008a44 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -4340,7 +4340,7 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) }; if( Lightlevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place - light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * std::clamp( 1.25f - (float)luminance, 0.f, 1.f ) ); + light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ); light_ubo->update( light_ubs ); } diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 3b8de9469..706e5d871 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -65,7 +65,9 @@ opengl_particles::update( opengl_camera const &Camera ) { vertex.color[ 0 ] = static_cast( particlecolor.r ); vertex.color[ 1 ] = static_cast( particlecolor.g ); vertex.color[ 2 ] = static_cast( particlecolor.b ); - vertex.color[ 3 ] = static_cast( std::clamp( particle.opacity * 255, 0.f, 255.f ) ); + // as up to 26.05.1, when clamp made the alpha a byte before clamping it: an opacity over 1 wraps + // round. through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion + vertex.color[ 3 ] = static_cast( static_cast( particle.opacity * 255 ) ); auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 5083c6f2f..8bef3352d 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -4370,8 +4370,8 @@ glm::dvec3 opengl_renderer::Update_Mouse_Position() { glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size; - mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 ); - mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); + mousepos.x = safe_clamp( mousepos.x, 0, Global.fb_size.x - 1 ); + mousepos.y = safe_clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); GLfloat pointdepth; ::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth ); diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index f8cd9a290..d26472248 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -2,6 +2,9 @@ #include "doctest.h" #include "scratch.h" +#include +#include + #include "utilities/Globals.h" #include "utilities/utilities.h" @@ -681,12 +684,30 @@ TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one" CHECK(Round(-2.5) == -2); } -TEST_CASE("utilities: a value is kept within bounds, given in any order") { +TEST_CASE("utilities: a value is kept within bounds; inverted bounds give the upper one, as the old clamp did") { CHECK(safe_clamp(5, 0, 3) == 3); - CHECK(safe_clamp(5, 3, 0) == 3); - CHECK(safe_clamp(-1, 3, 0) == 0); - CHECK(safe_clamp(2.0, 3.0, 1.0) == 2.0); + CHECK(safe_clamp(-1, 0, 3) == 0); + CHECK(safe_clamp(2, 0, 3) == 2); CHECK(safe_clamp(2.0, 2.0, 2.0) == 2.0); + // inverted bounds: always the upper bound, whatever the value + CHECK(safe_clamp(5, 3, 0) == 0); + CHECK(safe_clamp(-1, 3, 0) == 0); + CHECK(safe_clamp(2.0, 3.0, 1.0) == 1.0); + // NaN as the old clamp had it: a NaN value stays NaN, a NaN bound doesn't clamp + auto const notanumber{std::numeric_limits::quiet_NaN()}; + CHECK(std::isnan(safe_clamp(notanumber, 0.0, 1.0))); + CHECK(safe_clamp(2.0, 0.0, notanumber) == 2.0); + CHECK(safe_clamp(-1.0, notanumber, 1.0) == -1.0); + // what the helper gives for arguments in the order and of the signs of two calls (these checks don't call + // them): the AI braking test, whose demand is the stronger of the two (negative) bounds, as up to 26.05.1 + double const threshold{-0.45}; + CHECK(safe_clamp(0.3, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + CHECK(safe_clamp(-0.6, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + // and the bump at a rail joint, 0 in place of the value as up to 26.05.1: the figure is capped from above + // only, and above 68% of the top speed it is negative + CHECK(safe_clamp(0.0, 160.0, 160.0 - (150.0 + 160.0 * 0.32)) == doctest::Approx(-41.2)); + CHECK(safe_clamp(0.0, 4.0, -0.5) == -0.5); + CHECK(safe_clamp(0.0, 4.0, 5.0) == 4.0); } TEST_CASE("utilities: a value is wrapped into a range, as an angle into the full circle") { diff --git a/utilities/utilities.h b/utilities/utilities.h index 09c02d7fb..8c4181475 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -282,17 +282,18 @@ template bool is_equal(T const &Left, T const &Right, T const Epsil return Left == Right; } -// Tolerant clamp. Unlike std::clamp, this does NOT invoke undefined behaviour when -// the bounds are inverted (Lo > Hi) - it normalizes them instead. This restores the -// pre-refactor behaviour of the old custom clamp() for code paths where the bounds are -// computed at runtime and can legitimately cross (e.g. AI acceleration/braking limits, -// physics jolt calculations), where std::clamp's UB produced wrong results. +// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike +// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted +// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted +// bounds give the upper bound, as the old clamp() did. Every call of the old clamp() +// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are +// computed from such values) uses it, so it gives what it gave before the move to +// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same. +// New code uses std::clamp. template constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi ) { - return ( Hi < Lo ) - ? std::clamp( Value, Hi, Lo ) - : std::clamp( Value, Lo, Hi ); + return std::min( std::max( Value, Lo ), Hi ); } // keeps the provided value in specified range 0-Range, as if the range was circular buffer diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 453dd743a..757930596 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -1102,7 +1102,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) continue; } - auto const dist { std::clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -2529,7 +2529,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = std::clamp( + fAxleDist = safe_clamp( std::max( MoverParameters->BDist, MoverParameters->ADist ), 0.2, //żeby się dało wektory policzyć MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" @@ -3127,7 +3127,7 @@ TDynamicObject::update_load_offset() { 0.0 : 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, loadpercentage * 0.01, 1.0 ) ); + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void @@ -3766,20 +3766,21 @@ bool TDynamicObject::Update(double dt, double dt1) // crude bump simulation, drop down on even axles, move back up on // the odd ones // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - double const headroom = std::clamp( - MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ), - 0.0, MoverParameters->Vmax ); + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { - double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1); + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); MoverParameters->AccS += accHorizontal; MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } ++axleindex; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..41ee88ea5 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9760,7 +9760,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = std::clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9768,7 +9768,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = std::clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9776,7 +9776,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = std::clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -11390,8 +11390,11 @@ glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const return Point; } - return {std::clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), std::clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - std::clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; } const TTrain::screenentry_sequence &TTrain::get_screens() From 79c88c1793b7569132c1f55199035642f5688920 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:42 +0100 Subject: [PATCH 43/58] Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of 8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of 939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r --- global_include/interfaces/ITexture.h | 13 ++++ model/Texture.cpp | 95 ++++++++++++++++++++++++++++ model/Texture.h | 17 +++++ scripting/PyInt.cpp | 65 ++++++++++++++----- scripting/PyInt.h | 11 ++++ scripting/pythonscreenviewer.cpp | 16 ++++- scripting/pythonscreenviewer.h | 4 ++ 7 files changed, 204 insertions(+), 17 deletions(-) diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index ce123829f..f5b4d29a5 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -21,6 +21,19 @@ struct ITexture virtual void set_components_hint(int hint) = 0; virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) = 0; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; + // uploads an image from a thread with a gl context of its own, sharing the objects with the drawing one. a texture that + // can keeps the image apart until commit_thread_upload(), called on the drawing thread, puts it in place + virtual void upload_from_thread(size_t width, size_t height, const uint8_t *data) + { + update_from_memory(width, height, data); + } + // puts in place the image of the last upload_from_thread() once the gpu has it, without waiting for it. called on the + // drawing thread; false while the upload isn't done yet, to be asked again later + virtual bool commit_thread_upload() + { + // the image went in place right away + return true; + } static ITexture *null_texture() { struct NullTexture : public ITexture diff --git a/model/Texture.cpp b/model/Texture.cpp index bd13ecf2c..bba3ba763 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -736,6 +737,100 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 invalidate_unit_cache(); } +namespace +{ +// gl objects of an image uploaded by another thread that was never put in place +void delete_thread_upload(GLuint const Texture, GLsync const Fence) +{ + if (Fence != nullptr) + glDeleteSync(Fence); + glDeleteTextures(1, &Texture); +} +} // namespace + +void opengl_texture::upload_from_thread(size_t width, size_t height, const uint8_t *raw) +{ + // a texture of its own each time: the one drawn from may be in use by the gpu for the drawing context, and writing it from + // here, with nothing to order the two contexts, could leave it incomplete or half written for a frame + texture_thread_upload upload; + upload.width = width; + upload.height = height; + glGenTextures(1, &upload.id); + glBindTexture(target, upload.id); + set_filtering(); + glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap_mode_s); + glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap_mode_t); + if (!glGenerateMipmap) + glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); + glTexImage2D(target, 0, GL_SRGB8_ALPHA8, static_cast(width), static_cast(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, raw); + if (glGenerateMipmap) + glGenerateMipmap(target); + glBindTexture(target, 0); + if (glFenceSync) + { + upload.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + } + if (upload.fence == nullptr) + { + // no sync objects, or no fence made: the drawing context can only be sure of the image once the upload is done + glFinish(); + } + else + { + // the drawing context asks for the fence, which signals only once it is on its way to the gpu + glFlush(); + } + + std::optional superseded; + { + std::scoped_lock lock{m_threaduploadmutex}; + superseded = std::exchange(m_threadupload, upload); + } + if (superseded.has_value()) + { + // the drawing thread didn't take it, so nothing drew from it + delete_thread_upload(superseded->id, superseded->fence); + } +} + +bool opengl_texture::commit_thread_upload() +{ + texture_thread_upload upload; + { + std::scoped_lock lock{m_threaduploadmutex}; + if (false == m_threadupload.has_value()) + return true; + // asked without waiting. the image goes in place only once the upload is done, so every context binding it after + // has it whole: the extra viewports and the windows of python.displaywindows draw in contexts of their own + if (m_threadupload->fence != nullptr) + { + // a failed query (GL_WAIT_FAILED) isn't asked again: the image would never go in place + if (glClientWaitSync(m_threadupload->fence, 0, 0) == GL_TIMEOUT_EXPIRED) + return false; + glDeleteSync(m_threadupload->fence); + } + upload = *m_threadupload; + m_threadupload.reset(); + } + + if (id != invalid_id) + glDeleteTextures(1, &id); + id = upload.id; + data_width = static_cast(upload.width); + data_height = static_cast(upload.height); + data_format = GL_SRGB8_ALPHA8; + data_components = GL_RGBA; + if (type == "internalsrc:") + { + is_static = true; + is_ready = true; + } + // the name deleted may come back for another texture, and a deleted texture isn't bound any more + for (auto &unit : units) + unit = -1; + return true; +} + void opengl_texture::make_request() { diff --git a/model/Texture.h b/model/Texture.h index 2fbd76a4f..3934565a5 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include "winheaders.h" #include #include "model/ResourceManager.h" @@ -20,6 +22,14 @@ http://mozilla.org/MPL/2.0/. struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming +// an image uploaded by another thread into a texture of its own, waiting for the drawing thread to put it in place +struct texture_thread_upload { + GLuint id { 0 }; + GLsync fence { nullptr }; // set after the upload in the uploading context; none where the driver has no sync objects + size_t width { 0 }; + size_t height { 0 }; +}; + struct opengl_texture : public ITexture { static DDSURFACEDESC2 deserialize_ddsd(std::istream&); static DDCOLORKEY deserialize_ddck(std::istream&); @@ -93,6 +103,10 @@ struct opengl_texture : public ITexture { virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override; + // the image goes into a texture of its own, and the drawing thread swaps it in after the gpu has it (commit_thread_upload). + // the texture drawn from is never written by the uploading thread + void upload_from_thread(size_t width, size_t height, const uint8_t *data) override; + bool commit_thread_upload() override; // members static constexpr GLuint invalid_id { std::numeric_limits::max() }; // id value of texture without GL resource @@ -111,6 +125,9 @@ struct opengl_texture : public ITexture { // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread static std::atomic m_unitcachestale; + std::mutex m_threaduploadmutex; + std::optional m_threadupload; // guarded by m_threaduploadmutex + public: // methods void make_request(); diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fac540019..b95b310d8 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -142,18 +142,24 @@ void render_task::run() } else { - std::lock_guard guard(m_target->mutex); + // the lock may be held by the drawing thread for a whole upload: waited for without the gil. the bytes stay + // valid without it, the object is immutable and held by its reference here + Py_BEGIN_ALLOW_THREADS + { + std::scoped_lock guard(m_target->mutex); - if (m_target->image.size() != expectedBytes) - m_target->image.resize(expectedBytes); + if (m_target->image.size() != expectedBytes) + m_target->image.resize(expectedBytes); - std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); + std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); - m_target->width = screenWidth; - m_target->height = screenHeight; - m_target->components = glComponents; - m_target->format = glFormat; - m_target->timestamp = std::chrono::high_resolution_clock::now(); + m_target->width = screenWidth; + m_target->height = screenHeight; + m_target->components = glComponents; + m_target->format = glFormat; + m_target->timestamp = std::chrono::high_resolution_clock::now(); + } + Py_END_ALLOW_THREADS } } @@ -232,6 +238,35 @@ void render_task::upload() const } } +void render_task::upload_from_thread() +{ + m_uploadedbyworker = true; + if (Global.python_uploadmain && m_target && m_target->shared_tex) + { + m_target->shared_tex->upload_from_thread(m_target->width, m_target->height, reinterpret_cast(m_target->image.data())); + } +} + +bool render_task::finish_upload() const +{ + if (false == Global.python_uploadmain || nullptr == m_target || nullptr == m_target->shared_tex) + return true; + // the old texture is deleted and the new name published under the lock the windows of python.displaywindows bind under, + // so none of them binds the old name once it is gone: a name bound before stays alive in its context while bound there + std::scoped_lock lock(m_target->mutex); + if (m_uploadedbyworker) + { + if (false == m_target->shared_tex->commit_thread_upload()) + return false; + } + else + { + upload(); + } + m_target->texture_id = m_target->shared_tex->get_id(); + return true; +} + void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success @@ -569,9 +604,11 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo // execute python code task->run(); if (Context) - task->upload(); - else { + task->upload_from_thread(); + } + { + // the drawing thread uploads the image, or puts in place the one uploaded here std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } @@ -609,10 +646,8 @@ void python_taskqueue::update() { std::scoped_lock lock(m_uploadtasks.mutex); - for (auto const &task : m_uploadtasks.data) - task->upload(); - - m_uploadtasks.data.clear(); + // a task whose image a worker uploaded stays until the gpu has the image + std::erase_if(m_uploadtasks.data, [](std::shared_ptr const &Task) { return Task->finish_upload(); }); } void python_taskqueue::error() diff --git a/scripting/PyInt.h b/scripting/PyInt.h index c8c410397..3259b418a 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -67,6 +67,9 @@ struct python_rt int width; int height; std::string image; + // gl name of the texture with the last image put in place, for the windows of python.displaywindows (0: none yet). the image + // uploaded by a worker gets a texture of its own, so the name changes with each one + size_t texture_id{0}; std::chrono::high_resolution_clock::time_point timestamp; }; @@ -80,7 +83,13 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); + // uploads the image on the drawing thread void upload() const; + // uploads the image on a worker with a gl context of its own (python.threadedupload); finish_upload() puts it in place + void upload_from_thread(); + // on the drawing thread: uploads the image, or puts in place the one a worker uploaded. false while the gpu hasn't got + // the latter yet, to be called again + bool finish_upload() const; void cancel() const; auto target() const -> std::shared_ptr { @@ -92,6 +101,8 @@ class render_task PyObject *m_renderer{nullptr}; std::shared_ptr m_input{nullptr}; std::shared_ptr m_target{nullptr}; + // set by upload_from_thread(); read by the drawing thread after the task was handed over under the lock of the queue + bool m_uploadedbyworker{false}; }; class python_taskqueue diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4da50151e..5a3491af7 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -30,7 +30,7 @@ void texture_window_cursor_pos(GLFWwindow *win, double x, double y) } python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) - : m_rt(rt), m_touchlist(touchlist) + : m_rt(rt), m_touchlist(touchlist), m_initialtexture(rt->shared_tex->get_id()) { for (const auto &viewport : Global.python_viewports) { @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); + bind_shared_texture(); } else { GLuint tex; @@ -146,6 +146,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -188,6 +190,16 @@ void python_screen_viewer::threadfunc() } } +void python_screen_viewer::bind_shared_texture() const +{ + // bound each frame: each image uploaded by a worker comes in a texture of its own, and a name deleted comes back for + // a later one, so a name seen before may be another texture already. bound under the lock the drawing thread deletes + // the old texture under, so the name read here is never one already gone + std::scoped_lock guard(m_rt->mutex); + size_t const texture = m_rt->texture_id; + glBindTexture(GL_TEXTURE_2D, static_cast(texture != 0 ? texture : m_initialtexture)); +} + void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { for (auto const &conf : m_windows) { diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index ccd78f0ef..41b52a7e2 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -31,8 +31,12 @@ class python_screen_viewer gl::scene_ubs m_ubs; std::atomic_bool m_exit = false; + // the texture of the screen when the viewer was made, read on the drawing thread: shown until an image is put in place + size_t m_initialtexture{0}; void threadfunc(); + // with python.sharectx, binds the texture with the last image of the screen, in the context of the window made current + void bind_shared_texture() const; public: python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); From 8794c80c5896375a5e8e199ab0a964d6b206a16a Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:52 +0100 Subject: [PATCH 44/58] fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Since d13c27a7 (the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Before d13c27a7 the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from before d13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r --- model/AnimModel.cpp | 9 +++++++-- model/AnimModel.h | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 23af295e4..757ccd2b8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -597,6 +597,10 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { if( Framestamp == m_framestamp ) { return; } auto const timedelta { Timer::GetDeltaTime() }; + // the opacities change step by step from where they are, and they start at 1. the first time the instance is + // drawn its lights take their current state at once, whether it came from the definition or from an event since: + // a fade from 1 showed a light that is off as lit for a moment, the first time it came into view + bool const transition { m_transition && m_lightsanimated }; // interpretacja ułamka zależnie od typu // case ls_Off: ustalenie czasu migotania, t<1s (f>1Hz), np. 0.1 => t=0.1 (f=10Hz) @@ -637,12 +641,13 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { const float transitionontime = std::min(0.25f, std::min(ontime, offtime) * 0.95f); const float transitionofftime = std::min(0.45f, std::min(ontime, offtime) * 0.95f); if (on) - opacity += m_transition ? timedelta / transitionontime : 1.f; // increase to max value + opacity = static_cast( opacity + ( transition ? timedelta / transitionontime : 1.0 ) ); // increase to max value else - opacity -= m_transition ? timedelta / transitionofftime : 1.f; // reduce to zero + opacity = static_cast( opacity - ( transition ? timedelta / transitionofftime : 1.0 ) ); // reduce to zero // Clamp the opacity opacity = std::clamp(opacity, 0.f, 1.f); } + m_lightsanimated = true; // Ra 2F1I: to by można pomijać dla modeli bez animacji, których jest większość for (const auto entry : m_animlist) { diff --git a/model/AnimModel.h b/model/AnimModel.h index e5a6841b6..7cf50fa44 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -225,6 +225,7 @@ public: float fOffTime { 1.f / 2 };// { 60.f / 45.f / 2 }; // były stałymi, teraz mogą być zmienne dla każdego egzemplarza // float fTransitionTime { fOnTime * 0.9f }; // time bool m_transition { true }; // smooth transition between light states + bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame // true if this instance is eligible for the batched/instanced render path: From ba372e9830d364aed06568f6b4025c826b8a9567 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:40:21 +0100 Subject: [PATCH 45/58] Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or :event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after _.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to _dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after _.scm, any included file named *_.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. _.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial : opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here from the lineside tool, and danger_ahead finds where a train first comes to a switch: the start of one it runs onto from its start, or the fouling point of one it runs onto from behind, which may lie behind the point (a signal in the fouling zone). - The card of the selected signal: its distance from the axis of its track, and along it to the start or the fouling point of the switch ahead, in red when it stands inside the fouling zone. The overlay draws the same as a dimension line beside the track on the side of the signal, with the distance at the place. - Placed, dragged along or moved with the gizmo, a signal goes to a round distance to the switch ahead (50 m steps) when within 2.5 m of one; Alt keeps it where it is. The drag of a new one is measured from where it was pressed. - The fixes of the review of the split: the click label of the station tools in their own branch and a plain select in Signals, the card of a signal picked from the check lists shown in Station signals, and the help texts naming the Templates table and the Signals tool. - Self-tests: signalprobe logs the distance from the axis and to the switch ahead, signal snap=1 snaps as placing does. * feat(editor): the fouling point widened in the curves under 250 m, as the standard of the gauge says Standardy techniczne PKP PLK, tom II (from 2025-07-17), 6.5-6.6: the W17 marker stands where the axes of the tracks are nominally 3.50 m apart; where one of the tracks lies there in a curve under 250 m that spacing grows by the widening of the gauge from its radius (annex 1, table 1), the widenings of both summed when both lie in curves. - editor/editorFouling: the fouling point found along the axes of the main track and the branch, standing on its own: at each point of the branch the spacing wanted is the nominal one plus, for each track, the widening on the side of the other track from its radius there (taken over 5 m each way): 50000/R - 185 mm towards the centre of the curve, 60000/R - 225 mm away from it, none from 250 m up. - gauge::curve_widening gives table 1 of the gauge the editor checks already. - The W17 tool and the distance of a signal to the switch ahead both use it; the card of a signal shows how far apart the axes are at the fouling point, the help of the W17 tool says where the figures come from. - Unit tests: a straight branch at 1:9, a branch in a curve of 300 m (no widening) and of 200 m (outer widening), both tracks in curves (both widenings summed) and a straight branch off a curving track. * feat(editor): the cant leans the cars into the fouling point, and the fixes of the review of the metre - The fouling point takes the cant in, as Ie-1 wants it placed "with the gauge, the cant and the widening in the curves": the cars of a track on a cant lean towards the inside of its curve by D Hi / 1500 (bD of table 1 of the standard of the gauge), so when the other track lies on that side the spacing wanted grows by it, taken at 3.05 m over the rail top, the top of the widest part of GPL-1. The cant of each point comes from the roll of its path as the gauge tool takes it. At any radius, as the table has it; the track leaning away adds nothing. - Below 150 m, where table 1 ends, the widening from the radius is that of 150 m rather than the formula run on. - A switch run onto from behind has its fouling point looked for once its own path is walked too, so one lying on that path is found rather than skipped for a farther switch. - A point behind a signal lies on the track of the farther end of its segment, so a signal snapped back over a joint lands at the round distance rather than at the joint. - Alt keeping a signal off the round distances reads the key from ImGui, which Global.altState misses while ImGui holds the keyboard. The gizmo doesn't snap a signal: a1d10bb0 says it does, it's placing and dragging with the tool only. - The help of the distance on the card stays on the distance, the spacing of the axes under it. The unused track_trace::nearest_on is gone. - Unit tests: the cant leaning towards the other track in a curve and at 300 m, nothing when leaning away, and the table ending at 150 m. * fix(editor): the cars lean the way the cant of their track tips them, taken 3.25 m up - The cant along the trace keeps its sign: a roll above 0 lowers the left rail of the path (as the editor lifts its terrain by it), turned to the way the track is walked. A track adds the leaning of its cars to the spacing wanted at the fouling point when the other track lies on the side its lower rail is, whichever way it curves: a branch on a cant against its own curve leans towards the main track on its outer side, which d70f189c missed, and a cant on the straight counts too. - The leaning is taken 3.25 m over the rail top, the top of the widest part of the cars, rather than 3.05 m of GPL-1. - Unit tests: a cant against the curve, a cant on the straight, and the leaning away still adding nothing. * fix(editor): the station tools tell by the mouse what a button came to, and the fields of a station read as empty What a button of the Station, Station signals and Line block tools came to was written at the foot of the panel, under the lists, scrolled away: a click which refused for want of the code of the station looked as if nothing happened. It's told now by the mouse which clicked, a refusal in red as the other tools do, and in the status bar. The fields of a station still empty show their examples as such, "e.g. BPd", not as values typed in; the Station tool says above its steps that the code is to be typed first, Station signals that the code and the track circuits are wanted, the code marked there as needed. The check of a warning disc and of a block section went by the braking distance of the station, while Set the line signals places them by the one of their line: on lk357 a disc placed 700 m before Z, the line run at 100 km/h, was marked as standing nearer than the 1000 m of the station. A signal of a line out is checked by the braking distance of its line now. * feat(editor): the joints of the track circuits put, moved and taken away by hand, kept by the station The Station tool gets Edit the joints by hand: LMB on a plain track of the station puts a joint there, LMB on a joint takes it, then on a track moves it, on it again takes it away. The circuits are set again at once, one step of undo each. The joints so changed are kept in the //$s record of the station (joints +x/y/z for one put, -x/y/z for a planned one taken away), so Set the track circuits keeps them; As planned forgets them. The undo step carries the hand joints of the station with the tracks. srkjoint drives it in the self-tests. * feat(editor): the indicators under the lights reordered, a signal set from the axis and raised, standing on the ground by default The indicators under the lights of the selected signal get arrows up and down: one changes places with the indicator above or below it, a plate at the foot keeps its own. One step of undo each. The distance of the selected signal from the axis of its track is typed in the panel, it moves across as far along the track as it stands, the gauge pushing it out again where it comes too near. Its height is set the same way, raised over where it stands by default, over the rail heads on a gantry. A signal is put on the ground by default, the zero of its model 0.38 m under the rail heads: the ground lies 0.35 m under them as Ie-102 draws it (Lx), the foot of the mast stands on the foundation 3 cm over it in the models of pctga, and the sceneries made by hand (Wrzosy, Baltyk) stand their signals 0.20 m under the rail foot so. It stood on the rail heads. signalindicatorswap and signalacross drive it in the self-tests. * fix(editor): the hand joints of a station without a record, of its ends and of another station; a dragged signal keeps its place across and its height - Edit the joints by hand on a station not described yet read the record of index -1: the hand joints are shown only for a station with one. - The joint between the station and a line out of it can't be taken: taken away, the circuit of the switch ran on over the tracks of the line. - A joint held is let go when another station opens, a move by less than half a metre lets it go, and a change no step of the history takes is undone, so the undo knows every change of the joints. - A signal dragged or snapped along its track keeps its distance from the axis and its height over the default, set by hand or standing so before. * fix(editor): a dragged signal carries what it had by its own track; As planned forgets the hand joints that change nothing The distance from the axis and the height of a dragged signal were taken against the track it was dropped onto: dropped on the next piece of its line, on a grade or by a parallel track it came out too far, in the gauge or off the ground. They are taken as it stood by its own track at the start of the drag. As planned clears the hand joints even where the circuits come out the same. * fix(editor): a signal stands as high over the rail heads as its include gives, lowered only where its bottom would hang over the ground The default height of a signal was 0.38 m under the rail heads for every model. It is now read from the description of its include, `//$e signal: {..., height: , depth: }`: height is where the zero of the model stands over the rail heads (by Ie-117 § 15 the top of the foundation of a mast 0.10 m under them, of a dwarf 0.20 m), depth how far the model reaches under its zero. With a depth, a signal whose bottom would hang over the ground, down an embankment, goes down onto it, by at most 3 m (more is taken for a bridge). Without a height the zero stands at the rail heads. "Raised" in the panel, a signal moved across or dragged, all count from that default height. * fix(editor): a signal flipped, given another template or its variant for the other side stays as raised as it was The default height now depends on the template and on the ground under the signal, so keeping the height as it was no longer keeps the raise. Flipped to the other side of the track, the signal is raised over the default there as it was over the default on its own side. Given another template (Swap), or the variant of its template for the other side when moved or placed, it goes up or down by how much the default height of the new template differs from the old one. * fix(editor): As planned forgetting hand joints that change nothing is a step of undo of its own With nothing in the circuits to change no step of the history took the forgotten joints, so they went with no undo for it: Ctrl+Z took back the step before. The anchor of the station as it is now carries them in a step of their own. The signalmove selftest gets its carry indented with the block it is in. * feat(editor): an indicator under the lights goes in its place by Ie-117, from the top W21, W24, W20, W19, W26 Put on a signal, an indicator under its lights was put below the ones there. It now goes in its place by Ie-117 section 12.1 among them, under the last one it doesn't go above, the others (W18 and the rest) below these; the ones under it move a place down, in the same step of undo. * fix(editor): the signal card and the move of a signal keep no pointer across a refresh of the signals - The card of the selected signal went on after "To the other side" or "Turn around" with found pointing into the list of the signals standing, which their refresh had just replaced: the indicators and the gauge of the card read freed memory. It now ends that frame there. - signal_move_to read the mount of the template after the refresh, which may scan the templates again; it is taken before it. signal_place takes a copy of the template given for the same reason. - The fouling test counts its metres with an int, and the search of the middle point of the radius is a while loop (no floating loop counter). * fix(editor): the dimension line to the danger point counts its metres with an int (Sonar S2193) The line drawn by the track from a signal to the switch or fouling point ahead stepped a double by 1 m. It now counts the whole metres with an int from the same first one: the points are the same, since adding 1 to a whole double and adding a whole int to it give the same values. --------- Co-authored-by: maj00r * feat(editor): ride the camera along the tracks, and a minimap with stations by their W4 (#317) * feat(editor): the camera rides along the tracks, over the joints and switches and over to the tracks alongside Y puts the camera onto the track under the cursor (or the nearest one), looking along it 3 m over the rails. W/S drive it ahead and back the way the camera looks, Shift and Ctrl faster (20, 60, 250 m/s); A/D take it over to the track alongside, a click to any track; E/Q and the wheel raise and lower it; the mouse looks around as when flying. At a switch entered from its blades it goes straight on, Z picks the turnout for the camera alone: no switch is thrown, no track learns of the ride. The bar over the view shows the track, the km, the speed, the height and the switch ahead. Y or Esc ends it. Self-test commands ride, ridewalk, ridejump, rideahead, rideprobe and rideleave. * feat(editor): a minimap of the tracks with the camera on them, and the stations found by the names of their W4 View / Minimap and stations (W4), Ctrl+M: a window with the rail tracks seen from above, the camera as a triangle the way it looks, the track ridden along in orange and the stops of passenger trains as dots with the names of their stations. It follows the camera, or is dragged and zoomed apart from it; a click takes the camera there, riding along the track onto the track there. Above it the stations the PassengerStopPoint memory cells and events name, searched by a part of the name with or without the polish letters; a click (or Enter for the first found) flies the camera over to the stop looking along the track, riding it rides on from there, each click to the next W4 of the station. Self-test commands minimap, stations, station and minimapclick. * fix(editor): the ride and the minimap after the review, with fewer words on the screen - Ctrl+S, Ctrl+Z and the other shortcuts reach the editor while riding; Esc closes an open popup first - no key stays held when a window takes the keyboard, the place is kept within a path that got shorter, a release of the mouse goes where its press went - the minimap keeps under the vertex limit of a draw list, Enter in the search goes round the stops of the station, the marked station stays marked - the bar of the ride is one line: the track, km, speed and height; the switch ahead under it, the keys only while standing - the minimap in the Map menu, opening over the view, with short texts; the context menu of a track rides along it * feat(editor): the ride drives with the right button held, as the camera flies, and the editor works on along it - W/S, A/D and Q/E drive the ride only with the right button held; without it they're the editor's keys again (Q/W/E the gizmo) - the left button and Esc go to the tools while riding: tracks and objects are laid and selected from where the ride took the camera; Y leaves, a flight of the camera to a framing leaves too - after the review: the help names Ctrl+W/Ctrl+Down as the much faster drive, the stops of the minimap stay within the vertex limit, the search field lets the keys go after Enter * fix(editor): the tools keep their wheel and the menu of a track its click while riding, a pan or the view from above ends the ride --------- Co-authored-by: maj00r * feat(editor): signals placed by the editor get a name plate drawn by python (#316) * feat: Elf emergency brake position in the master controller (eu07/maszyna#413) The Elf's master controller (EIMCtrlType 2) gets an optional emergency brake position below its position 0, turned on by the new .fiz key EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it). With it the old positions move up by one (MCPN 5, neutral at 4): the emergency position brakes fully at once and vents the brake pipe, like the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a too small MCPN to 5 and logs it. The Elf code with hard-coded positions (CheckEIMIC, the MED full braking, the AI) takes the shift into account. SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe): - every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5, DirChangeMaxPos=4 where present; - the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09), sounds shifted one index up, new sound0 with 26284_elf_nastawnik_nagle_*.wav. Issue: (eu07/maszyna#413) * fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position The emergency position of the master controller vented the brake pipe from every vehicle whose controller stood there, and "MainCtrl" reached the coupled vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed by one notch (the full braking of one was the emergency brake of the other, neutral of one a power position of the other). The pipe is now vented only from the vehicle driven from (IsCabMaster()), and the position goes to the coupled vehicles in the positions without the key (MainCtrlPosForCoupled(), the emergency one as the full braking), each adding its own shift on receiving it (MainCtrlPosFromCoupled()). The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same shift, so the reverser keeps working at the new neutral. * feat(editor): the signals the editor places get a plate with their name, drawn by python A signal placed with the signal tool used to get the plate texture of textures/tabl named like it, or none at all. Now, unless a texture is picked, its plate is made by python/local/signal_plate.py: "make:signal_plate?name=", a light plate with a dark edge, four screws and the name in black, the way the plates of textures/tabl look. Renaming the signal in its properties renames a drawn plate with it; a picked texture stays. The templates put the plate after a folder, "tabl/(p6)", so material_data::assign() takes the folder off a skin which names a texture made by a script. * fix(editor): a drawn signal plate keeps following a cleared name, and isn't made for a name it can't carry Clearing the name of a signal in its properties made its plate the drawn plate of no name, which then never followed the name again. A drawn plate now follows any rename to a name, and keeps the last one while the name is cleared. A name with '|', '&' or '?', or one longer than 64 characters, gets no plate (0_nothing) instead of a broken one: '|' splits the skin, '&' and '?' the query of the script, and a very long name made a path too long for the file system when the skin was looked for on the disk. * fix(editor): a signal plate keeps its last name through a name it can't carry, and a plate named by hand stays Renaming a signal to a name its plate can't carry turned the drawn plate into 0_nothing, and it stopped following the name for good. Such a name now leaves the plate with the last usable one, like a cleared name does, and the plate follows again once a usable name is typed. A drawn plate whose name was given by hand, different from the name of the signal, is no longer replaced on a rename: only the drawn plate of the signal's own name follows it. * feat(editor): the drawn signal plates come in three looks, plain, toned and aged The plate drawn by python/local/signal_plate.py looked too clean. It now takes a look in its query, "make:signal_plate?look=toned&name=Tm12": plain is the bright plate it was, toned a greyish field with a little grain and dust towards the bottom and the sides, a thinner edge, smaller screws and graphite letters, aged a darker, grainier and dustier one. Toned is drawn when no look is given. The signal tool picks the look under the plate, kept in the settings of the editor. A rename of the signal in its properties keeps the look of its plate. * perf(editor): the grain and the dust of a drawn signal plate are made on whole images The toned and aged plates shaded their field a pixel at a time in python, about 34 ms a plate with the interpreter held, so a station of a hundred signals in view kept the python queue, and the screens of the cabs, waiting for seconds. The dust is now made once per look, and the grain from random bytes of the name, both put on the field with ImageChops: about 2 ms a plate. The mean colour of the plates stays the same; only the grain falls differently. * fix(editor): the station signalling draws the plates of its signals as their schematic names them The plates the station signalling places and renames say what its schematic shows (Tm3, F1, ToA, a block signal without the stem), and a template swapped in for a signal without a plate draws that text too rather than the small letters of the name. A signal left for removal gets a plate of no text again, not one saying "_old". No plate, 0_nothing, or the texture named like the signal, what the editor gave before the plates were drawn, become the drawn plate when the signal is renamed, in the properties panel as by the station signalling, in the look set in the editor. * fix(editor): a plate of a scenery named like the end of the name of its signal stays through a rename in the properties A texture pzs_a was given by its scenery as a, its real plate: a rename in the properties panel keeps it. Only the station signalling, which looked its plates up that way, takes such a one for its own. * feat(editor): the drawn signal plates are 256 pixels across, sharp up close The edge, the screws and the blur are drawn bigger by as much as the plate is, and the grain is as coarse as before, so the three looks stay as they were. The smallest letters tried grow with the plate too. * feat(editor): a drawn signal plate takes a speed index and the m of shunting signals, typed in the signal tool signal_plate.py draws the speed index after the name, one digit up at its right or two as a fraction across the height of the letters (index=4, index=12 for 1/2), and with m=1 an "m" on a strip of its own under the name, as Ie-1 marks a semaphore giving shunting signals and as the textures/tabl a-12m plates show it. The signal tool has a field for the index and a box for the m under the look of the plate; the hint of the plate names them (B 1/2 m). The style of a drawn plate, its look with the index and the m, stays with it through a rename, in the properties panel and by the station signalling, which sets neither. The signal selftest takes index= and m=. * fix(editor): the speed index of a plate takes only digits as they are typed The decimal field let in signs and dots, which stayed shown while the index held only the digits, and filled the two places before a second digit could go in. * fix(sonar): the remarks on the drawn signal plates, to pass the quality gate The new code of the plates was 5.2% technical debt against the 5% of the gate. Fixed the small remarks; the big functions stay as they are: - the speed index field and the plate looks are std::arrays, the index is copied without snprintf, the combo of the looks has a function of its own - ranges algorithms, a string_view for signal_plate_drawn, emplace_back - signal_plate.py: dict literals, a cache of fonts not named like FONTS, no unused local, the name and the m drawn by methods of their own; the plates drawn are byte for byte the same as before --------- Co-authored-by: jerrrrycho Co-authored-by: maj00r * feat(editor): the switch drives with no switch listed and marked, and a switch deleted takes its drives and ballast along - the switch tool lists the drives set to a switch the scenery hasn't got, a click flies to the drive and selects it; the view and the photo mark them red, and the editor tells how many there are once the scenery is open - drives not described for the editor are told by their switch events naming the first parameter: single ones, those of the double switches (thrown as a..d or _a.._d), gates and derailers; the sleepers or ballast throwing a switch on their own events, with no (p1)+ or (p1)-, aren't drives - such a drive may set the speed or carry the ballast of the switch: it's kept as it is, not replaced, turned over or moved, and the switch panel shows it by its file - a switch deleted takes each drive throwing it, also one kept beside a described drive, and the ballast and sleepers named by it, in the same undo step; those of a double switch go with the last of its switches - the selftest commands straydrives and drivewhose * fix(editor): the ballast of a single switch goes with it beside a switch named with a letter more, and a switch of a doubled name keeps its drive - a bed named by a deleted single switch is checked against that name alone, not a..d - deleting one of two tracks of the same name looks for the other before taking away the drive and the ballast - the refusal of a drive not described tells its file without the folder * fix(editor): the tutorial and the hints tell of the kilometrage, and the first lesson takes O either way The kilometrage (X) was in no hint, no shortcut list and no lesson, though the hectometre posts and the block signals are numbered after it. The row of the track tools now reads L T G N U I X B P V J, the turntable with it, and F1 lists I / X / B. The lesson of the signals and the posts says what X does and where the posts take their numbers from, the km of the line or the km typed in their panel for the place clicked, and it opens with the kilometrage tool too. The first lesson asked to switch to the view from above, which a scenery made in the wizard opens in already: O either way does it now. * fix(editor): master's road lifting texts translated, and the panning by the wheel told of in 3D too The merge of master left the status and the label of the lifting of the road points in English: both go through the translations now. Master pans the 3D view by the wheel as well, so the lesson, the hint row and its line say it works in both views. , dropped from the road tool before, came back in the merge and is gone again. * fix(editor): the tools of a plain line in sight, the km of a line set once, a lesson of a whole line and of the ride along a track What a layman building a line with signals and posts couldn't find: - The Signals, Kilometrage and Posts tools are in the main row of Tracks, after the tools of laying; the stations, their signals, the line block, the turntable, the trainset and the checks stay behind More. - "Objects" was where the hectometre posts are: the tool is Posts now (Słupki), its hints say the line the posts go along. - The km of a line could be typed in three places that didn't lead to each other. The panel of the posts and the one of a station, where the line has no km set, say the typed km is theirs alone and have Set the km of the line (X), opening the Kilometrage tool; that tool says first that one known point serves the posts, the stations and the block signals. - The hint of the Signals tool says to pick a signal in the list, then click beside a track; with no templates the panel says so in plain words. - A new lesson, A whole line, step by step: the tracks and switches, the km, the station, its signals, the line block, the posts and the drive, with a button to the station tool, and opened with the station tools. - The first lesson shows the ride of the camera along a track (Y, then W S A D and Z) and has it as a step to try. - lang/editor_pl.po: "Restore the terrain" and "Drag an end" were there twice, the second copies are gone. Checked: MSVC build, unit tests 459/459; editor run on a small scenery, screenshots of the toolbar, the new lesson, the first lesson with the ride ticked after Y, the panels of the posts, the kilometrage and the signals. The station panel with no km of the line wasn't seen, the scenery had no station. * fix(editor): the posts open expanded from the trainset, and the Polish of the whole-line lesson reads right B or the Posts button pressed while the trainset tab is shown opens the hectometre posts with their panel expanded. The Tracks area tooltip names the kilometrage and the posts. The station step names the shunting signals, the station button says Narzędzie Stacja, and the ride rows and the lesson list read smoother in Polish. * fix(editor): a bent model is lengthened along the tracks joined to its own, laid along another track after the bending, and set by fewer settings The ends of a bent model have handles in the view: dragged, the model goes on along the tracks joined there, at a switch the way it's dragged to. Its length, a drag of the whole model and a drag of an end all follow the joined tracks; before, they went on straight past the end of the track under the model. The panel of a bent model picks its track: another one picked, the model stays where it stands, a platform turns its edge to the new track and keeps its length. On top stay the track, the length, the offset and the height, bent or repeated, and the platform edge; the reference point, the position along, turned, mirrored, the cant and the gauge widening went under More settings. The buttons of the model's own length and of the whole track are gone: the length field and the handles do it. The links of a model to its tracks are counted anew when its pieces change, undo and redo included. * fix(editor): the bends of straights laid from the end of a curve begin with a straight, not a compound curve In the mode of straights the curve of a plain track's free end no longer goes on into the curve of the first bend as a compound curve. The line comes out of the end's curve by a transition onto a straight, and each bend gets a curve of its own. Only a curve traced in the mode of a curve goes on from the curve of the end, as it already did at a switch. * fix(editor): the bent model keeps its links and its line to what it reaches, and drags without rebuilding at each track - the links of a bent model are matched anew whenever any of its pieces change, not only the first - the line is lengthened by the plan lengths of the joined tracks and built once a round; a drag reuses the line made at its start while it doesn't grow - the tracks of one name are told apart in the track lists, and a deleted track leaves them - the tracks at the ends the copies no longer reach are left out of the line after an edit or a drag * fix(editor): a click on a bent model's handles changes nothing, and the track picked stays picked - the line is trimmed on a drag's release only when the drag changed the model, and an edit that trimming undoes makes no undo step - the track picked for the bending is kept by the track, not its place in the list, when the list is gathered anew * fix(editor): a double slip with a drive not described for the editor isn't laid anew Laying a double slip anew took away the drives of its switches, the ones not described for the editor too, though they may set the speed or carry the ballast of the slip and are kept as they are everywhere else. The switches laid anew get other names, so such a drive left in place would be set to no switch either: the slip is left as it is, with the reason why. * fix(editor): a slip laid anew or of another template refused for any drive of it not described for the editor The check looked at the one drive a switch is found by, which is the described one when the editor kept a drive of Rainsted beside it; laying a slip again of another template took such drives away unasked. Both ways now look at every drive throwing the switches of the slip, and refuse with a reason that says the slip isn't laid anew. * fix(lang): a stray line taken out of editor_pl.po A single "r" between two entries, left by an edit of the switch texts: msgfmt refuses the file with it. * feat(launcher): the range of the aerial photos of a new real scenery given on the map, changed later in the editor (#328) * feat(launcher): the new real scenery gets the range of its aerial photos on the map, changed later in the editor The wizard of a new scenery asked only for the centre; the editor then downloaded the photos around the camera wherever it went, and a scenery had no range of them until one was drawn in the orthophoto settings. The realistic scenery is made in three steps: the name, the place (a click on the map or the place typed, degrees or PUWG 1992), and the range of the aerial photos: a square of 1, 2, 5 or 10 km around the centre, or an area of the user's, its corners clicked on the map. The range is drawn on the map with its size and the number of the tiles, and it's written to the scenery as the download area (//$z), so the editor downloads the photos and the terrain model inside it only. What a beginner gets wrong is told before the scenery is made: the button stays off with the reason under it (no name, the name taken, no centre, the centre outside Poland, an area being drawn or crossing itself), and a warning comes with the centre outside the area, a large area and a centre clicked on the map of the whole country (the map zooms to the place after the first click). In the editor the download area says in plain words what it does, a square around the camera replaces it in one click, and with the camera outside it a note at the bottom of the view says there are no photos there, with the way to the range. * fix(launcher): the range of the photos asked for after the centre, the drawing given up as with Cancel, the square named by its sides The review of the range of the aerial photos found: - with My own area chosen before the centre, the clicks meant for the centre went to the corners of the area: step 3 waits for the centre; - switching to Fictional while drawing dropped the area there was before, and an unfinished one of three corners counted as done: it's given up as with Cancel now, also with Esc; Enter ends it, Backspace takes the last corner back, as in the editor; - the error of a place mistyped stayed after a click on the map; - the largest square was told to be large or not by the rounding: the warning comes from 50 sq km on; - "2 km" read as a radius: the squares say "2 x 2 km", the tooltip how far each edge is; - a place typed with an area of the user's fitted the map to the area, not to the place. In the editor the note of the camera outside the range says the terrain model isn't there either, its button says it opens the settings, it stands above the strip of the profile and the keys of the tools, and it can be closed until the camera is back inside. The squares around the camera want the place of the scenery on the map, and replace an area there is, or start one of 10 x 10 km, only with a yes. * fix(editor): one note of the empty scenery in the middle of the view, the warnings of an area told once it's drawn A new scenery opened in the editor showed two notes of the same over each other in the middle of the view: the panel of the track tools ("The scenery has no tracks yet") and the line of the terrain ("This scenery is still empty"). The line gives way to the panel now. In the wizard the centre outside the area and the crossing edges were told while the area was still being drawn; they're told once it's done. * fix(editor): the note of the camera outside the range of the photos hidden while the camera rides a track Its lines at the bottom of the view are where the camera riding a track writes the next switch and its keys. --------- Co-authored-by: maj00r --------- Co-authored-by: maj00r Co-authored-by: Hirek193 Co-authored-by: jerrrrycho --- application/editormode.cpp | 16 +- application/editormode.h | 39 +++- application/editormodelineside.cpp | 4 +- application/editormodeselftestswitch.cpp | 19 ++ application/editormodeswitchdrive.cpp | 261 +++++++++++++++++++++-- application/editormodeswitchplace.cpp | 7 + application/editormodeswitchtemplate.cpp | 3 + application/editormodeswitchtool.cpp | 1 + application/editormodetrack.cpp | 18 +- editor/editorIncludeInfo.cpp | 65 ++++++ editor/editorIncludeInfo.hpp | 7 + lang/editor_pl.po | 30 +++ 12 files changed, 442 insertions(+), 28 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index ab150cb7b..bb87aa5cb 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -1412,6 +1412,15 @@ bool editor_mode::update() ui()->set_status(text, false); WriteLog("Editor: " + text, logtype::generic); } + // the drives left without their switches are told once, as the scenery is opened + if (auto const stray{stray_drives().size()}; stray > 0) + { + auto const text{format(STR_P("%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view", + "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view", static_cast(stray)), + stray)}; + ui()->set_notice(text); + WriteLog("Editor: " + text, logtype::generic); + } } } // after the tool has told its own status @@ -1652,6 +1661,7 @@ bool editor_mode::update() draw_build_overlay(); steps.step("laying drawn"); draw_blade_tips(); + draw_stray_drives(); draw_track_intent(); draw_tape(); steps.step("track drawn"); @@ -3309,7 +3319,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) return; } scene::Layers.removed(Instance, false == included.removed); - m_drives_standing.reset(); + drives_changed(); ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } @@ -3346,7 +3356,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } - m_drives_standing.reset(); + drives_changed(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -3391,7 +3401,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - m_drives_standing.reset(); + drives_changed(); std::string file; std::vector values; if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && diff --git a/application/editormode.h b/application/editormode.h index 81347c950..148edb25a 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -2635,8 +2635,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri struct switch_drive { standing_template standing; - int family{-1}; - int index{0}; + int family{-1}; // -1: a drive not described for the editor, e.g. of Rainsted; it can be replaced, not turned over or moved + int index{-1}; }; std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches @@ -2656,10 +2656,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri void switch_drives_committed(std::vector const &Tracks); // the drives of the switches deleted go with them, in the step of the undo history the deletion made last void drives_deleted(std::vector const &Switches); + // the file of a drive not described for the editor throwing one of the switches, empty when there's none; also one the editor + // kept beside a drive described for it + std::string undescribed_drive(std::vector const &Switches); // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved std::size_t drives_to_blade_tips(); bool m_drives_checked{false}; + // the file of each variant of the drives scanned: its family and its index in the family + std::map, std::less<>> drive_variants() const; + // the switches a template of a drive throws, by what follows its first parameter in their names: "" for a variant described for the + // editor, and for any other template whose switch events throw the track named by its first parameter, as the drives of Rainsted do; + // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not + // described for the editor have no family (-1) + std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); + std::map, std::less<>> m_drive_templates; // read once for each file + // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events + // throw nothing + struct stray_drive + { + scene::instance_handle instance{0}; + std::vector switches; // the names of the switches it throws, as its include gives them + std::string name; // of the switches missing from them + std::string file; + glm::dvec3 location{0.0}; + }; + // all the drives standing in the scenery, read from the files once while no include comes or goes + struct drives_named + { + std::vector drives; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_named; + // the include of a drive or a template changed: what's kept of the drives standing is read again + void drives_changed(); + // the drives whose switch isn't in the scenery, checked against the tracks each time + std::vector stray_drives(bool Wait = false); + void render_stray_drives(); + void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; // places them in the active layer or the given one, as one step of the undo. returns: how many were placed std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index 1c2fc9e9c..8f4f5209c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -253,7 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) { - m_drives_standing.reset(); + drives_changed(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -341,7 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { - m_drives_standing.reset(); + drives_changed(); EditorSnapshot snap; for (auto const instance : Instances) { diff --git a/application/editormodeselftestswitch.cpp b/application/editormodeselftestswitch.cpp index 891ca6d68..b9c502d17 100644 --- a/application/editormodeselftestswitch.cpp +++ b/application/editormodeselftestswitch.cpp @@ -549,6 +549,25 @@ editor_mode::selftest_result editor_mode::selftest_switch(std::string const &com WriteLog("SELFTEST drives " + name + ": chosen " + (m_switch.drive >= 0 ? m_switch.drives[m_switch.drive].name : std::string{"none"}) + ", side " + std::to_string(m_switch.drive_side) + ", standing" + files + ", steps " + std::to_string(m_history.size())); return selftest_result::handled; } + if (command == "straydrives") + { + auto const stray{stray_drives(true)}; + std::string names; + for (auto const &drive : stray) + names += " " + drive.name + "(" + drive.file + ")"; + WriteLog(format("SELFTEST straydrives: %zu", stray.size()) + names); + return selftest_result::handled; + } + if (command == "drivewhose") + { + // the drive the editor tells for the switch: its file and family, -1 for one not described + std::string name; + words >> name; + auto *track{simulation::Paths.find(name)}; + auto const found{track != nullptr ? find_switch_drive(*track) : std::nullopt}; + WriteLog("SELFTEST drivewhose " + name + ": " + (found.has_value() ? found->standing.file + " family " + std::to_string(found->family) : std::string{"none"})); + return selftest_result::handled; + } if (command == "driveflip") { std::string name; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 3e0a67854..931350af1 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editormodeshared.h" +#include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" @@ -25,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "imgui/imgui.h" #include +#include #include #include #include @@ -44,6 +46,21 @@ std::string drive_file(std::string Text) return Text; } +// the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as +// they're written +TTrack *track_named(std::string const &Name) +{ + auto *track{simulation::Paths.find(Name)}; + return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); +} + +// a template by the name of its file, with no folder: told to the user, who picks the drives by their names +std::string file_name(std::string const &File) +{ + auto const slash{File.find_last_of('/')}; + return slash != std::string::npos ? File.substr(slash + 1) : File; +} + int drive_side(std::string const &Side) { if (Side == "left") @@ -168,7 +185,8 @@ void editor_mode::switch_drives_committed(std::vector const &Tracks) drives = switch_drives_standing(); auto const found{drives->find(drive_file(track->name()))}; auto const spot{editor_track::drive_spot_of(*track)}; - if (found == drives->end() || false == spot.has_value()) + // a drive not described for the editor has no parameters known to set it with, nor a height above the rail; it stays put + if (found == drives->end() || found->second.family < 0 || false == spot.has_value()) continue; auto const &drive{found->second.standing}; auto const &included{scene::Layers.instance(drive.instance)}; @@ -221,7 +239,15 @@ bool editor_mode::place_switch_drive(TTrack &Switch) item.track = Switch.name(); item.tilt = spot->tilt; if (auto const present{find_switch_drive(Switch)}) + { + // one not described for the editor is kept: it may set the speed over the switch or carry its ballast too + if (present->family < 0) + { + tool.status = format(STR_C("Switch %s keeps its drive %s, which isn't described for the editor"), Switch.name().c_str(), file_name(present->standing.file).c_str()); + return false; + } return replace_switch_drive(Switch, tool.drive, (present->index & 1) != (driveright ? 1 : 0)); + } std::string error; if (place_templates({item}, error) == 0) { @@ -255,22 +281,147 @@ std::map const &editor_mode::switch_driv return included.removed || included.dead; })) return kept->by_switch; + auto const variants{drive_variants()}; + kept.emplace(); + kept->frame = ImGui::GetFrameCount(); + kept->revision = tool.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + auto const variant{variants.find(standing.file)}; + auto const [family, index]{variant != variants.end() ? variant->second : std::pair{-1, -1}}; + // the drive of a double switch of Rainsted stands for each of its switches, a..d + for (auto const &suffix : drive_switches(standing.file, variants)) + { + // a drive described for the editor goes before one of Rainsted set to the same switch, which the editor kept beside it + auto const [entry, fresh]{kept->by_switch.try_emplace(drive_file(standing.values[0] + suffix), switch_drive{standing, family, index})}; + if (false == fresh && entry->second.family < 0 && family >= 0) + entry->second = switch_drive{standing, family, index}; + } + } + return kept->by_switch; +} + +std::vector const &editor_mode::drive_switches(std::string const &File, std::map, std::less<>> const &Variants) +{ + static std::vector const single{std::string{}}; + if (Variants.contains(File)) + return single; + auto const [found, fresh]{m_drive_templates.try_emplace(File)}; + if (fresh) + editor_includes::switched_tracks(File, found->second); + return found->second; +} + +std::map, std::less<>> editor_mode::drive_variants() const +{ + auto const &tool{m_switch}; std::map, std::less<>> variants; for (int family = 0; family < static_cast(tool.drives.size()); ++family) for (int index = 0; index < 4; ++index) if (false == tool.drives[family].files[index].empty()) variants[drive_file(tool.drives[family].files[index])] = {family, index}; - kept.emplace(); - kept->frame = ImGui::GetFrameCount(); - kept->revision = tool.drives_revision; - kept->instances = instances; - for (auto &standing : standing_templates([&](std::string const &File) { return variants.contains(File); })) + return variants; +} + +void editor_mode::drives_changed() +{ + m_drives_standing.reset(); + m_drives_named.reset(); +} + +std::vector editor_mode::stray_drives(bool const Wait) +{ + scan_switch_drives(Wait); + auto const instances{static_cast(scene::Layers.instance_count())}; + auto &kept{m_drives_named}; + if (false == kept.has_value() || kept->revision != m_switch.drives_revision || kept->instances != instances) { - auto const &[family, index]{variants[standing.file]}; - auto name{drive_file(standing.values[0])}; - kept->by_switch.try_emplace(std::move(name), switch_drive{std::move(standing), family, index}); + auto const variants{drive_variants()}; + kept.emplace(); + kept->revision = m_switch.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + stray_drive drive{standing.instance, {}, {}, standing.file, standing.location}; + for (auto const &suffix : drive_switches(standing.file, variants)) + drive.switches.push_back(standing.values[0] + suffix); + kept->drives.push_back(std::move(drive)); + } + } + // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its + // switches gone, while one stands it still throws it + std::vector stray; + for (auto const &drive : kept->drives) + { + auto const &included{scene::Layers.instance(drive.instance)}; + // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts + if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { + auto const *track{track_named(Name)}; + return track != nullptr && false == track->m_editorremoved; + })) + continue; + std::string missing; + for (auto const &name : drive.switches) + missing += (missing.empty() ? "" : ", ") + name; + stray.push_back(drive); + stray.back().name = std::move(missing); + } + return stray; +} + +void editor_mode::render_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + ImGui::PushID("straydrives"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.55f, 0.25f, 1.0f)); + auto const open{ImGui::TreeNode("##straydrives", STR_P("%zu drive with no switch", "%zu drives with no switch", static_cast(stray.size())), stray.size())}; + ImGui::PopStyleColor(); + item_tooltip("Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name"); + if (open) + { + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + auto const label{format("%s (%s, %.0f m)##%d", drive.name.c_str(), file_name(drive.file).c_str(), glm::length(drive.location - camera), static_cast(drive.instance))}; + if (ImGui::Selectable(label.c_str(), m_instance == drive.instance)) + { + select_include(drive.instance); + fly_to(drive.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 25.0); + } + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list +void editor_mode::draw_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + // the ones far off would only crowd the view of the whole line + auto constexpr range{3000.0}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + ImVec2 at; + if (glm::length(drive.location - camera) > range || false == projection.project(drive.location, at)) + continue; + auto const selected{m_instance == drive.instance}; + drawlist->AddCircleFilled(at, 8.0f, IM_COL32(0, 0, 0, 170)); + drawlist->AddCircle(at, 7.0f, selected ? overlay_color::selected : overlay_color::invalid, 0, 3.0f); + auto const text{format(STR_C("%s: no switch of this name"), drive.name.c_str())}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const corner{at.x + 12.0f, at.y - 0.5f * size.y}; + drawlist->AddRectFilled({corner.x - 3.0f, corner.y - 1.0f}, {corner.x + size.x + 3.0f, corner.y + size.y + 1.0f}, IM_COL32(0, 0, 0, 160), 3.0f); + drawlist->AddText(corner, selected ? overlay_color::selected : overlay_color::invalid, text.c_str()); } - return kept->by_switch; } void editor_mode::apply_switch_drive_choice(TTrack &Switch) @@ -280,7 +431,10 @@ void editor_mode::apply_switch_drive_choice(TTrack &Switch) place_switch_drive(Switch); return; } - if (auto const found{find_switch_drive(Switch)}; found.has_value() && remove_templates({found->standing.instance}) > 0) + auto const found{find_switch_drive(Switch)}; + if (found.has_value() && found->family < 0) + m_switch.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found->standing.file).c_str())); + else if (found.has_value() && remove_templates({found->standing.instance}) > 0) m_switch.status = format(STR_C("Switch %s without a drive now"), Switch.name().c_str()); } @@ -299,7 +453,15 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return false; } auto const &found{present->standing}; + // a drive not described for the editor, as one of a double switch, may set the speed over the switch or carry its ballast too: it's kept as it is + if (present->family < 0) + { + tool.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found.file).c_str())); + return false; + } auto const family{Family >= 0 ? Family : present->family}; + if (family >= static_cast(tool.drives.size())) + return false; auto const index{Flip ? present->index ^ 1 : present->index}; template_item item; item.file = tool.drives[family].files[index]; @@ -334,19 +496,82 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return true; } +std::string editor_mode::undescribed_drive(std::vector const &Switches) +{ + // the drives described for the editor read first: before they are, every drive would pass for one not described + scan_switch_drives(true); + std::vector names; + for (auto const *track : Switches) + if (track != nullptr) + names.push_back(drive_file(track->name())); + auto const variants{drive_variants()}; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == variants.contains(File) && false == drive_switches(File, variants).empty(); })) + { + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return std::find(names.begin(), names.end(), drive_file(standing.values[0] + Suffix)) != names.end(); })) + return file_name(standing.file); + } + return {}; +} + void editor_mode::drives_deleted(std::vector const &Switches) { if (m_history.empty()) return; + // the names of the switches deleted, as the game finds them; they're retired already + std::vector deleted; for (auto const *track : Switches) + if (track != nullptr && track->eType == tt_Switch) + deleted.push_back(drive_file(track->name())); + if (deleted.empty()) + return; + auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; + // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, + // still has the drive and the ballast, so it's looked for too + auto const stands = [](std::string const &Name) { + if (auto const *track{track_named(Name)}; track != nullptr) + return false == track->m_editorremoved; + auto const name{drive_file(Name)}; + auto const &tracks{simulation::Paths.sequence()}; + return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); + }; + auto const take_away = [&](scene::instance_handle const Instance) { + if (false == scene::Layers.removable(Instance)) + return; + scene::Layers.removed(Instance, true); + m_history.back().instances.push_back(Instance); + }; + auto const variants{drive_variants()}; + // each drive throwing a switch deleted, also one the editor kept beside a drive described for it; the drive of a double switch throws + // the others too, so it goes with the last of them + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) { - if (track == nullptr || track->eType != tt_Switch) + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return named(standing.values[0] + Suffix); }) && + std::none_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return stands(standing.values[0] + Suffix); })) + take_away(standing.instance); + } + // the sleepers and the ballast laid by a switch, named by it as its drive is: of a double switch by the name its switches have in + // common, a..d or _a.._d, so they go with the last of them + static std::array const parts{"", "a", "b", "c", "d", "_a", "_b", "_c", "_d"}; + std::map> beds; + for (auto const &standing : standing_templates([](std::string const &) { return true; })) + { + auto const &name{standing.values[0]}; + // named by a single switch, it's this switch's alone; a switch named a beside it may be another single one + if (named(name)) + { + if (stands(name)) + continue; + } + else if (std::none_of(parts.begin(), parts.end(), [&](char const *Part) { return named(name + Part); }) || + std::any_of(parts.begin(), parts.end(), [&](char const *Part) { return stands(name + Part); })) continue; - auto const found{find_switch_drive(*track)}; - if (false == found.has_value() || false == scene::Layers.removable(found->standing.instance) || scene::Layers.instance(found->standing.instance).removed) - continue; - scene::Layers.removed(found->standing.instance, true); - m_history.back().instances.push_back(found->standing.instance); + auto const [bed, fresh]{beds.try_emplace(standing.file)}; + if (fresh) + bed->second = drive_switches(standing.file, variants).empty() && editor_includes::switch_bed(standing.file); + if (bed->second) + take_away(standing.instance); } } @@ -359,7 +584,7 @@ std::size_t editor_mode::drives_to_blade_tips() { if (track == nullptr || track->m_editorremoved || track->eType != tt_Switch) continue; - if (auto const found{find_switch_drive(*track)}; found.has_value() && scene::Layers.removable(found->standing.instance)) + if (auto const found{find_switch_drive(*track)}; found.has_value() && found->family >= 0 && scene::Layers.removable(found->standing.instance)) { switches.push_back(track); before.emplace_back(found->standing.instance, scene::Layers.directive(found->standing.instance)); diff --git a/application/editormodeswitchplace.cpp b/application/editormodeswitchplace.cpp index b35ef8c48..82028a943 100644 --- a/application/editormodeswitchplace.cpp +++ b/application/editormodeswitchplace.cpp @@ -1609,6 +1609,13 @@ bool editor_mode::replace_double_slip(TTrack &Part, editor_track::switch_templat return false; } } + // a drive not described for the editor may set the speed or carry the ballast of the slip too: the editor can neither take it + // away nor move it to the switches laid anew, which get other names, so the slip is left as it is + if (auto const drive{undescribed_drive({switches.begin(), switches.end()})}; false == drive.empty()) + { + state.status = refused(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); + return false; + } struct end { TTrack *track; diff --git a/application/editormodeswitchtemplate.cpp b/application/editormodeswitchtemplate.cpp index e6a8496bd..6edef6a65 100644 --- a/application/editormodeswitchtemplate.cpp +++ b/application/editormodeswitchtemplate.cpp @@ -286,6 +286,9 @@ bool editor_mode::change_slip_template(TTrack &Part, int const Index) for (auto const *part : parts) if (false == part->Dynamics.empty()) return fail(STR_C("The slip can't be laid again while vehicles stand on it")); + // its drives go with it and the new one gets its own: a drive not described for the editor can't be told apart from them + if (auto const drive{slip.has_value() ? undescribed_drive(slip->switches) : std::string{}}; false == drive.empty()) + return fail(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); // a single slip laid again joins the pair of the tracks it joined: the point given by them auto const &ends{slip.has_value() ? slip->ends : std::array{}}; auto const pair{slip.has_value() && record.type == "Rkp" ? 0.5 * (ends[0] + ends[3]) : glm::dvec3{0.0}}; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index a37c98f70..878e18aa3 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -282,6 +282,7 @@ void editor_mode::render_switch_ui() ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", tool.status.c_str()); ImGui::PopTextWrapPos(); } + render_stray_drives(); if (ImGui::Button(STR_C("Template editor..."))) m_switch_designer.open = true; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 91bf9c027..6e0fe60c7 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1171,22 +1171,34 @@ void editor_mode::render_turnout_ui() { auto const family{drive->family}; auto const variant{drive->index}; + // a drive not described for the editor is shown by its file + auto const described{family >= 0 && family < static_cast(m_switch.drives.size())}; + auto const &file{drive->standing.file}; + auto const shown{described ? m_switch.drives[family].name : format("%s (%s)", file.substr(file.find_last_of('/') + 1).c_str(), STR_C("not described"))}; if (begin_fields("##standingdrive", 0.3f)) { field_row("Drive##standing"); - if (ImGui::BeginCombo("##standing", m_switch.drives[family].name.c_str())) + if (false == described) + ImGui::TextUnformatted(shown.c_str()); + else if (ImGui::BeginCombo("##standing", shown.c_str())) { for (int i = 0; i < static_cast(m_switch.drives.size()); ++i) if (ImGui::Selectable(m_switch.drives[i].name.c_str(), family == i) && i != family) replace_switch_drive(Switch, i, false); ImGui::EndCombo(); } - if (ImGui::IsItemHovered()) + if (described && ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", STR_C("Puts another drive in place of the drive of this switch, on the same side"), format(STR_C("Drive: events %s+ and %s- switch it, also in the map"), Switch.name().c_str(), Switch.name().c_str()).c_str()); ImGui::EndTable(); } int side{((variant >> 1) == (variant & 1)) ? 0 : 1}; - if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, + if (false == described) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted")); + ImGui::PopTextWrapPos(); + } + else if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, {1, STR_C("other side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}})) flip_switch_drive(Switch); } diff --git a/editor/editorIncludeInfo.cpp b/editor/editorIncludeInfo.cpp index ca532f1ce..450cde5a2 100644 --- a/editor/editorIncludeInfo.cpp +++ b/editor/editorIncludeInfo.cpp @@ -548,6 +548,71 @@ bool event_names(std::string const &File, std::vector &Names) return true; } +bool switched_tracks(std::string const &File, std::vector &Suffixes) +{ + Suffixes.clear(); + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + // event switch + auto const tokens{tokenize(text.content)}; + std::string const first{"(p1)"}; + // a drive has the events thrown by the keys and the map, (p1)+ and (p1)-, or moves a model, lights its lamps or throws a double switch at + // once; the sleepers or the ballast of a switch may throw it on their own events too, with nothing else, but they don't drive it + bool driven{false}; + for (std::size_t idx = 0; idx + 2 < tokens.size() && false == driven; ++idx) + { + if (tokens[idx] != "event") + { + continue; + } + auto const &name{tokens[idx + 1]}; + auto const &kind{tokens[idx + 2]}; + driven = (name.size() > first.size() && name.compare(0, first.size(), first) == 0 && (name.back() == '+' || name.back() == '-')) || (kind != "switch" && kind != "trackvel"); + } + if (false == driven) + { + return true; + } + for (std::size_t idx = 0; idx + 4 < tokens.size(); ++idx) + { + if (tokens[idx] != "event" || tokens[idx + 2] != "switch" || tokens[idx + 4].compare(0, first.size(), first) != 0) + { + continue; + } + auto suffix{tokens[idx + 4].substr(first.size())}; + if (std::find(Suffixes.begin(), Suffixes.end(), suffix) == Suffixes.end()) + { + Suffixes.push_back(std::move(suffix)); + } + } + return true; +} + +bool switch_bed(std::string const &File) +{ + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + auto const tokens{tokenize(text.content)}; + for (std::size_t idx = 0; idx < tokens.size(); ++idx) + { + // node track ... + if (tokens[idx] == "include" || (tokens[idx] == "node" && idx + 4 < tokens.size() && tokens[idx + 4] == "track") || + (tokens[idx] == "event" && idx + 2 < tokens.size() && tokens[idx + 2] != "switch" && tokens[idx + 2] != "trackvel")) + { + return false; + } + } + return true; +} + bool signal_speeds(std::string const &File, std::vector &Speeds) { Speeds.clear(); diff --git a/editor/editorIncludeInfo.hpp b/editor/editorIncludeInfo.hpp index 7a2da9dfa..96b84b44a 100644 --- a/editor/editorIncludeInfo.hpp +++ b/editor/editorIncludeInfo.hpp @@ -90,6 +90,13 @@ int parameter_count(std::string const &File); bool signal_speeds(std::string const &File, std::vector &Speeds); // the names of the events the template defines, as they're written after "event", lower case. returns: false if the file can't be read bool event_names(std::string const &File, std::vector &Names); +// the tracks the switch events of the template throw, named by its first parameter: what follows (p1) in their names, lower case, "" +// for the track named (p1) itself, "a" for (p1)a of a double switch; none for the sleepers or the ballast of a switch, whose events only +// throw it or set its speed, with no (p1)+ or (p1)-. returns: false if the file can't be read +bool switched_tracks(std::string const &File, std::vector &Suffixes); +// true if the template can be the sleepers or the ballast of a switch: it puts no track, includes nothing and has no events but those +// throwing a switch or setting its speed. false if the file can't be read +bool switch_bed(std::string const &File); // the aspects of a block signal of the template: 4 where its events give S3, the green light flashing with the next signal at S5, // the warning two signals ahead, else 3. returns: 0 if the file can't be read int block_aspects(std::string const &File); diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4a5bc4759..b765a98d6 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14023,6 +14023,36 @@ msgstr "PPM wciśnięty, W / S" msgid "RMB held, A / D" msgstr "PPM wciśnięty, A / D" +msgid "%zu drive with no switch" +msgid_plural "%zu drives with no switch" +msgstr[0] "%zu napęd bez zwrotnicy" +msgstr[1] "%zu napędy bez zwrotnicy" +msgstr[2] "%zu napędów bez zwrotnicy" + +msgid "Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name" +msgstr "Napędy ustawione na zwrotnicę, której w scenerii nie ma: zostały po zwrotnicy usuniętej lub przemianowanej ręcznie albo we wcześniejszym edytorze, ich eventy niczego nie przestawiają.\nKliknięcie przenosi do napędu i go zaznacza, Delete go usuwa; można też nadać jakiejś zwrotnicy jego nazwę" + +msgid "%s: no switch of this name" +msgstr "%s: brak zwrotnicy o tej nazwie" + +msgid "%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view" +msgid_plural "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view" +msgstr[0] "%zu napęd nie ma zwrotnicy o swojej nazwie: jest na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[1] "%zu napędy nie mają zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[2] "%zu napędów nie ma zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" + +msgid "The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is" +msgstr "Napęd %s nie ma opisu dla edytora: może też ustawiać prędkość albo nieść podsypkę zwrotnicy, więc zostaje bez zmian" + +msgid "The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew" +msgstr "Rozjazd krzyżowy ma napęd %s bez opisu dla edytora, który może też ustawiać prędkość albo nieść jego podsypkę: nie zostanie ułożony od nowa" + +msgid "Switch %s keeps its drive %s, which isn't described for the editor" +msgstr "Zwrotnica %s zostaje przy swoim napędzie %s, który nie ma opisu dla edytora" + +msgid "A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted" +msgstr "Napęd bez opisu dla edytora, np. rozjazdu krzyżowego, który może też ustawiać prędkość albo nieść podsypkę zwrotnicy: edytor go nie zmienia, zostaje na miejscu, gdy zwrotnica się przesuwa, i znika razem z ostatnią zwrotnicą, którą przestawia" + # the wizard of a new scenery: the range of the aerial photos, given on the map and changed in the editor msgid "A fictional scenery needs no place on the map" From 201cae07e15509dd255caf892a75a603a45649f7 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:53:42 +0100 Subject: [PATCH 46/58] fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), (...) Stack (addr2line -f -C -e ): to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r --- CMakeLists.txt | 1 + EU07.cpp | 46 +++++- application/application.cpp | 42 +++++- application/application.h | 1 + tests/unit/test_crashsignals.cpp | 89 ++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 4 + utilities/Logs.cpp | 3 + utilities/crashsignals.cpp | 234 +++++++++++++++++++++++++++++++ utilities/crashsignals.h | 25 ++++ 10 files changed, 444 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_crashsignals.cpp create mode 100644 utilities/crashsignals.cpp create mode 100644 utilities/crashsignals.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d5c0ad33..e563e587f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -545,6 +545,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" diff --git a/EU07.cpp b/EU07.cpp index 1c2c36aab..fa6bb15f2 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,9 +22,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -78,8 +82,12 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ExceptionPointers = ExceptionInfo; dumpInfo.ClientPointers = FALSE; - // Wybrana kombinacja flag - MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + // a small dump by default: the stacks with the memory they point to, the threads with their process and thread + // blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data + // (Global among them). all the memory of the simulator, as large as the memory it took, only with + // "crashdump.full yes" in eu07.ini + auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs}; + MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); // in test mode nobody is there to close the box, and the run would wait for it until killed @@ -172,9 +180,15 @@ int main(int argc, char *argv[]) SetUnhandledExceptionFilter(CrashHandler); #endif #endif + // on Linux, where no dump is written, the stack of a crash in the log and on the standard error + crash_signals::install(VERSION_INFO); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); + // a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it + // from a closing; how the simulator ends after a start that worked stays as it was + int exitcode{0}; + // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { @@ -221,34 +235,54 @@ int main(int argc, char *argv[]) } else { + // below 0 when the start failed (see eu07_application::init()) + int initresult{0}; try { - auto result{Application.init(argc, argv)}; - if (result == 0) + initresult = Application.init(argc, argv); + if (initresult == 0) { - result = Application.run(); + Application.run(); Application.exit(); } } + // an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the + // log and ends with an error code catch (std::bad_alloc const &Error) { ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what())); + exitcode = 1; } #ifdef _WIN32 catch (std::runtime_error const &Error) { + ErrorLog("Critical error: " + std::string(Error.what())); std::string msg = "Simulator crash occured :(\n"; msg += Error.what(); MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); + exitcode = 1; + } +#else + // elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on + // Windows it is left to CrashHandler, whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } #ifndef _WIN32 fflush(stdout); fflush(stderr); #endif - std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults + std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults } diff --git a/application/application.cpp b/application/application.cpp index 12bc9020a..d11ed8bbd 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -171,6 +174,28 @@ void char_callback(GLFWwindow *window, unsigned int c) Application.on_char(c); } +namespace +{ + +// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no +// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context, +// is told once. glfw may call this from any thread that uses it +void glfw_error_callback(int const Code, char const *Description) +{ + auto message{std::format("GLFW error 0x{:08X}: {}", static_cast(Code), Description != nullptr ? Description : "(no description)")}; + + static std::mutex reportedmutex; + static std::set reported; + { + std::scoped_lock lock(reportedmutex); + if (false == reported.insert(message).second) + return; + } + ErrorLog(message); +} + +} // namespace + // public: void eu07_application::queue_screenshot() @@ -253,7 +278,8 @@ int eu07_application::run_crashgui() return 0; } } - return -1; + // the player closed the window: the simulator closes with it, as it always has, but that is no failed start + return 1; } #if WITH_DISCORD_RPC void eu07_application::DiscordRPCService() @@ -436,7 +462,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { - ErrorLog("Failed to run crash gui!"); + // above 0 the player closed the window, which is no error + if (result < 0) + ErrorLog("Failed to run crash gui!"); + else + WriteLog("Crash report window closed, closing"); return result; } } @@ -503,6 +533,11 @@ int eu07_application::init(int Argc, char *Argv[]) if (!init_network()) return -1; + // glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the + // platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key + // codes of its launchers), every frame + glfwSetErrorCallback(nullptr); + return result; } @@ -1391,6 +1426,9 @@ int eu07_application::init_locale() int eu07_application::init_glfw() { + // set before glfwInit(), so a failure of the start itself is told too + glfwSetErrorCallback(glfw_error_callback); + { int glfw_major, glfw_minor, glfw_rev; glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); diff --git a/application/application.h b/application/application.h index 850b66e1e..881d4f073 100644 --- a/application/application.h +++ b/application/application.h @@ -33,6 +33,7 @@ public: // constructors eu07_application() = default; // methods + // 0 when the simulator started, below 0 when its start failed, above 0 when the player closed it before it started int init( int Argc, char *Argv[] ); int diff --git a/tests/unit/test_crashsignals.cpp b/tests/unit/test_crashsignals.cpp new file mode 100644 index 000000000..4c4dd1e86 --- /dev/null +++ b/tests/unit/test_crashsignals.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/crashsignals.h" + +// the stack of a crash on Linux (utilities/crashsignals.h): written to the log and to the standard error, after which +// the signal ends the process as it always did. the crash happens in a child process, which the test watches +#if defined(__linux__) + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +std::string read_all(int const File) { + std::string text; + std::array buffer{}; + for (auto count{::read(File, buffer.data(), buffer.size())}; count > 0; count = ::read(File, buffer.data(), buffer.size())) + text.append(buffer.data(), static_cast(count)); + return text; +} + +std::string read_file(std::string const &Path) { + std::ifstream file{Path, std::ios::binary}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +// the child: the report goes to the pipe in place of the standard error, no core dump is left behind +[[noreturn]] void crash_in_child(std::array const &Pipe, std::string const &Log) { + // a child stuck before the crash (a lock some other thread held at the fork) ends anyway, and the test with it + alarm(10); + dup2(Pipe[1], STDERR_FILENO); + close(Pipe[0]); + close(Pipe[1]); + rlimit const nocore{0, 0}; + setrlimit(RLIMIT_CORE, &nocore); + + crash_signals::install("test version 1.2"); + crash_signals::set_log_path(Log); + raise(SIGSEGV); + _exit(0); // not reached: the signal ends the child +} + +} // namespace + +TEST_CASE("crash signals: a crash writes its stack to the log and to the standard error, and still ends by its signal") { + test::scratch_folder const folder{"crash_signals"}; + auto const log{folder.write("log.txt", "the last line of the log\n")}; + + std::array pipe_ends{}; + REQUIRE(pipe(pipe_ends.data()) == 0); + auto const child{fork()}; + REQUIRE(child >= 0); + if (child == 0) + crash_in_child(pipe_ends, log); + + close(pipe_ends[1]); + auto const errors{read_all(pipe_ends[0])}; + close(pipe_ends[0]); + int status{0}; + REQUIRE(waitpid(child, &status, 0) == child); + + CAPTURE(errors); + // the process ends as it would without the handler + CHECK(WIFSIGNALED(status)); + CHECK(WTERMSIG(status) == SIGSEGV); + // the report on the standard error, which the starter shows + CHECK(errors.find("Crash: signal 11 (SIGSEGV) at address 0x") != std::string::npos); + CHECK(errors.find("Version: test version 1.2") != std::string::npos); + CHECK(errors.find("Stack (addr2line") != std::string::npos); + // with the frames of the program that crashed + CHECK(errors.find("eu07_unit_tests") != std::string::npos); + // and the same at the end of the log, after what it held + auto const logtext{read_file(log)}; + CAPTURE(logtext); + CHECK(logtext.starts_with("the last line of the log\n")); + CHECK(logtext.find("Crash: signal 11 (SIGSEGV)") != std::string::npos); + CHECK(logtext.find("eu07_unit_tests") != std::string::npos); +} + +#endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 864338442..abfa6d5e7 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1294,6 +1294,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "crashdump.full") + { + ParseOne(Parser, CrashDumpFull); + return true; + } + if (token == "showsystemconsole") { ParseOne(Parser, ShowSystemConsole); @@ -1753,6 +1759,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); + export_as_text( Output, "crashdump.full", CrashDumpFull ); export_as_text( Output, "showsystemconsole", ShowSystemConsole ); export_as_text( Output, "logs.filter", DisabledLogTypes ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index c4a9a7267..c20adc05e 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -113,6 +113,10 @@ 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 }; + // the dump written when the simulator crashes (Windows): a small one by default, with the stacks, the threads, the + // modules, the memory the stacks point to and the modules' data. "crashdump.full yes" writes all the memory of the + // simulator instead, as large as the memory it took + bool CrashDumpFull{ false }; // 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; diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index e0949aba6..f4032d808 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include @@ -115,6 +116,8 @@ void LogService() { std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); + // the stack of a crash on Linux goes to the end of this file + crash_signals::set_log_path(filename); } output << msg << "\n"; output.flush(); diff --git a/utilities/crashsignals.cpp b/utilities/crashsignals.cpp new file mode 100644 index 000000000..fa62e8955 --- /dev/null +++ b/utilities/crashsignals.cpp @@ -0,0 +1,234 @@ +/* +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/crashsignals.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// the handler may only call what is safe in a signal: no allocation, no locks, no streams. so what it needs is +// kept in fixed buffers, filled in beforehand, and written with write() + +constexpr std::array crash_signal_list{SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT}; +// a handler that hangs (a crash inside the allocator or the loader, which backtrace() may need) ends this long after +constexpr unsigned int crash_report_timeout_seconds{5}; + +// a text of fixed size, filled outside the handler and read in it +template struct fixed_text { + std::array text{}; + std::atomic ready{false}; + + void set(std::string_view const Text) { + ready = false; + auto const length{std::min(Text.size(), text.size() - 1)}; + std::copy_n(Text.data(), length, text.data()); + text[length] = '\0'; + ready = true; + } + char const *get() const { return ready ? text.data() : nullptr; } +}; + +fixed_text<1024> &log_path() { + static fixed_text<1024> path; + return path; +} + +fixed_text<256> &version_text() { + static fixed_text<256> version; + return version; +} + +// the stack the handler runs on, so an overflow of the main thread's own stack is reported too +std::array &alternate_stack() { + static std::array stack{}; + return stack; +} + +void write_all(int const File, std::string_view Text) { + while (false == Text.empty()) { + auto const written{::write(File, Text.data(), Text.size())}; + if (written <= 0) + return; + Text.remove_prefix(static_cast(written)); + } +} + +void write_hex(int const File, std::uintptr_t const Value) { + constexpr std::size_t digits{sizeof(Value) * 2}; + constexpr std::string_view hexdigits{"0123456789abcdef"}; + std::array text{'0', 'x'}; + for (std::size_t digit = 0; digit < digits; ++digit) + text[2 + digit] = hexdigits[(Value >> (4 * (digits - 1 - digit))) & 0xF]; + write_all(File, {text.data(), text.size()}); +} + +void write_decimal(int const File, int const Value) { + std::array text{}; + auto position{text.size()}; + auto rest{static_cast(Value < 0 ? -Value : Value)}; + do { + text[--position] = static_cast('0' + rest % 10); + rest /= 10; + } while (rest != 0 && position > 1); + if (Value < 0) + text[--position] = '-'; + write_all(File, {text.data() + position, text.size() - position}); +} + +std::string_view signal_name(int const Signal) { + switch (Signal) { + case SIGSEGV: + return "SIGSEGV"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGABRT: + return "SIGABRT"; + default: + return "?"; + } +} + +// the signal being reported, for a report that hangs +std::atomic &crash_signal() { + static std::atomic signal{0}; + return signal; +} + +// a report that hangs is given up: the process ends by the signal of the crash, as it would have without the handler +void handle_report_timeout(int) { + auto const crashsignal{crash_signal().load()}; + raise(crashsignal); + // it is blocked while its own handler runs, which this one interrupted + sigset_t unblocked; + sigemptyset(&unblocked); + sigaddset(&unblocked, crashsignal); + sigprocmask(SIG_UNBLOCK, &unblocked, nullptr); +} + +struct crash_stack { + std::array frames{}; + int count{0}; +}; + +void write_report(int const File, int const Signal, siginfo_t const *Info, crash_stack const &Stack) { + write_all(File, "\nCrash: signal "); + write_decimal(File, Signal); + write_all(File, " ("); + write_all(File, signal_name(Signal)); + write_all(File, ")"); + // the address of the fault; an abort has none + if (Signal != SIGABRT && Info != nullptr) { + write_all(File, " at address "); + write_hex(File, reinterpret_cast(Info->si_addr)); + } + write_all(File, "\n"); + if (auto const *version{version_text().get()}) { + write_all(File, "Version: "); + write_all(File, version); + write_all(File, "\n"); + } + write_all(File, "Stack (addr2line -f -C -e ):\n"); + backtrace_symbols_fd(Stack.frames.data(), Stack.count, File); +} + +void handle_crash_signal(int const Signal, siginfo_t *Info, void *) { + crash_signal() = Signal; + struct sigaction timeout{}; + timeout.sa_handler = handle_report_timeout; + sigemptyset(&timeout.sa_mask); + sigaction(SIGALRM, &timeout, nullptr); + alarm(crash_report_timeout_seconds); + + crash_stack stack; + stack.count = backtrace(stack.frames.data(), static_cast(stack.frames.size())); + + if (auto const *path{log_path().get()}) { + if (auto const log{::open(path, O_WRONLY | O_APPEND | O_CLOEXEC)}; log >= 0) { + write_report(log, Signal, Info, stack); + ::close(log); + } + } + write_report(STDERR_FILENO, Signal, Info, stack); + + // the handler was taken off as it was called (SA_RESETHAND): the signal does what it always did + raise(Signal); +} + +} // namespace + +namespace crash_signals { + +void install(std::string_view const Version) { + static std::atomic installed{false}; + if (installed.exchange(true)) + return; + + version_text().set(Version); + + // backtrace() loads what it needs on its first call, which allocates: done here, not in the handler + std::array warmup{}; + backtrace(warmup.data(), static_cast(warmup.size())); + + stack_t alternate{}; + alternate.ss_sp = alternate_stack().data(); + alternate.ss_size = alternate_stack().size(); + sigaltstack(&alternate, nullptr); + + struct sigaction action{}; + action.sa_sigaction = handle_crash_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESETHAND; + // another crash signal of the same thread waits until the report is written, rather than starting a second one in + // its middle (a fault that comes while it is blocked still ends the process). a crash of another thread at the + // same moment may still write its report alongside + sigemptyset(&action.sa_mask); + for (auto const crashsignal : crash_signal_list) + sigaddset(&action.sa_mask, crashsignal); + for (auto const crashsignal : crash_signal_list) + sigaction(crashsignal, &action, nullptr); +} + +void set_log_path(std::string_view const Path) { + // whole, so the report finds the file wherever the simulator stands then + std::error_code error; + auto const path{std::filesystem::absolute(std::filesystem::path{Path}, error)}; + log_path().set(error ? std::string{Path} : path.string()); +} + +} // namespace crash_signals + +#else + +namespace crash_signals { + +void install(std::string_view) {} +void set_log_path(std::string_view) {} + +} // namespace crash_signals + +#endif diff --git a/utilities/crashsignals.h b/utilities/crashsignals.h new file mode 100644 index 000000000..feb526869 --- /dev/null +++ b/utilities/crashsignals.h @@ -0,0 +1,25 @@ +/* +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 + +// the stack of a crash on Linux, where no dump is written: a signal of a fault (SIGSEGV, SIGBUS, SIGFPE, SIGILL) or +// SIGABRT writes the stack of the thread that took it to the log and to the standard error, which the starter shows, +// and then ends the simulator as the signal always did (a core dump where the system makes one). the addresses are +// read with addr2line on the eu07 file of the same version, which carries its symbols. elsewhere it does nothing +namespace crash_signals { + +// sets the handlers up, once. Version goes into the report, to tell which eu07 file the addresses belong to +void install(std::string_view Version); +// the log file the report is added to, once the log has opened it +void set_log_path(std::string_view Path); + +} // namespace crash_signals From 7524cfbcc2d3aa0e34d66ac298c994f9ce2c85b3 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:54:20 +0100 Subject: [PATCH 47/58] feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r --- tests/unit/test_track_uneven.cpp | 28 +++++++++++++++++++--------- tools/track_uneven_grade.py | 6 +++--- track_uneven_doc.md | 14 ++++++++------ world/Segment.cpp | 10 ++++++---- world/TrackUneven.h | 21 ++++++++++++--------- 5 files changed, 48 insertions(+), 31 deletions(-) diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp index b55de1644..a97791a32 100644 --- a/tests/unit/test_track_uneven.cpp +++ b/tests/unit/test_track_uneven.cpp @@ -63,7 +63,8 @@ TEST_CASE("uneven track: the cab keeps what the ride on the track doesn't stand TEST_CASE("uneven track: measures as the Id-14 limits for its value") { // appendix 1, class C at 80 km/h: 18 mm vertically, 17 mm sideways, 16 mm of twist on 5 m, gauge +10/-8 mm, 20 mm of cross level, J = 5.3 - auto const amplitude{track_uneven::stray_per_mm * 18.0 * 1000.0}; // mm + auto const amplitude{track_uneven::stray_up_per_mm * 18.0 * 1000.0}; // mm + auto const sideways{track_uneven::stray_side_per_mm * 18.0 * 1000.0}; // mm double const gauge{1.435}; double const step{0.5}; int const steps{4000}; @@ -76,6 +77,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") double level{0.0}; double j{0.0}; double away{0.0}; + double aside{0.0}; for (int line = 0; line < lines; ++line) { auto const heading{glm::pi() * (line + 0.37) / lines}; @@ -85,6 +87,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") std::array, 2> up; std::array, 2> side; std::vector middle; + std::vector across_middle; for (int i = 0; i < steps; ++i) { auto const point{start + along * (i * step)}; @@ -93,9 +96,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") auto const sign{rail == 0 ? 1.0 : -1.0}; auto const stray{track_uneven::field(point + across * (sign * 0.5 * gauge))}; up[rail].push_back((stray.y - sign * 0.5 * track_uneven::level(point, across)) * amplitude); - side[rail].push_back(glm::dot(stray, across) * amplitude); + side[rail].push_back(glm::dot(stray, across) * sideways); } - middle.push_back(track_uneven::field(point).y * amplitude); + auto const centre{track_uneven::field(point)}; + middle.push_back(centre.y * amplitude); + across_middle.push_back(glm::dot(centre, across) * sideways); } std::vector verticals; std::vector horizontals; @@ -120,6 +125,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") wander += peak(gauges) / lines; level += peak(levels) / lines; away += peak(middle) / lines; + aside += peak(across_middle) / lines; j += (deviation(verticals) + deviation(horizontals) + deviation(twists) + 0.5 * deviation(gauges)) / 3.5 / lines; } CHECK(vertical == doctest::Approx(18.0).epsilon(0.1)); @@ -128,7 +134,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") CHECK(wander == doctest::Approx(10.0).epsilon(0.2)); CHECK(level == doctest::Approx(20.0).epsilon(0.1)); CHECK(j == doctest::Approx(5.3).epsilon(0.2)); - CHECK(away < 40.0); // the long waves go past the 15 mm off the survey marks of appendix 1a + // the long waves go past the 15 mm off the survey marks of appendix 1a: most of the height of a track spectrum is in them, the 10 m chord + // hardly sees them + CHECK(away < 60.0); + // and sideways: about 4.5 cm, which a platform edge or the panels of a level crossing laid on the design are off the rails by + CHECK(aside < 50.0); } TEST_CASE("uneven track: a place strays the same every time") @@ -136,11 +146,11 @@ TEST_CASE("uneven track: a place strays the same every time") // no random numbers: changing these changes how every uneven track in every scenery looks glm::dvec3 const place{1234.5, 0.0, -678.9}; auto const stray{track_uneven::field(place)}; - CHECK(stray.x == doctest::Approx(0.309777548158).epsilon(1e-9)); - CHECK(stray.y == doctest::Approx(0.311350299745).epsilon(1e-9)); - CHECK(stray.z == doctest::Approx(-0.328429734019).epsilon(1e-9)); - CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.53 * -0.178598957983).epsilon(1e-9)); - CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.53 * -0.868291889902).epsilon(1e-9)); + CHECK(stray.x == doctest::Approx(0.158385385505).epsilon(1e-9)); + CHECK(stray.y == doctest::Approx(0.356190053667).epsilon(1e-9)); + CHECK(stray.z == doctest::Approx(0.200372098150).epsilon(1e-9)); + CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.35 * -0.178598957983).epsilon(1e-9)); + CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.35 * -0.868291889902).epsilon(1e-9)); } TEST_CASE("uneven track: tracks laid towards each other meet at one cant") diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index 81df2ce2a..ba60be900 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -38,10 +38,10 @@ CURVE_STEP = 1.0 / 2500.0 # a difference of curvature that counts as a change, RISE = 0.0273 * 4.5 # how fast pressure lifts a pantograph, m/s, by TDynamicObject::Update GAP_MOST = 0.006 # the gap to the wire allowed; at 0.01 m the voltage goes and the main breaker trips OVERSPEED = 1.1 # a driver can go this much over the speed of the track -# as up_waves and the dip of the joints in world/TrackUneven.h -STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0 +# as up_waves, stray_up_per_mm and the dip of the joints in world/TrackUneven.h +STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00229, 0.4, 3.0 GOLDEN = math.pi * (3.0 - math.sqrt(5.0)) -UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))] +UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0), (.0761, .1058, .1393, .176, .2175, .2651, .3215, .3887)))] TOKEN = re.compile(r"//[^\n]*|\S+") NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$") diff --git a/track_uneven_doc.md b/track_uneven_doc.md index e4822b971..1899abdc3 100644 --- a/track_uneven_doc.md +++ b/track_uneven_doc.md @@ -46,15 +46,17 @@ A track with `uneven 18` measures as follows (`tests/unit/test_track_uneven.cpp` | parameter | result | Id-14 | |--------------------------|--------|-----------| | vertical irregularities | 18 mm | 18 mm | -| horizontal irregularities | 19 mm | 17 mm | +| horizontal irregularities | 17 mm | 17 mm | | twist on a 5 m base | 15 mm | 16 mm | | gauge | ±10 mm | +10/-8 mm | -| cross level | 20 mm | 20 mm | -| J index | 6.1 | 5.3 | +| cross level | 21 mm | 20 mm | +| J index | 5.7 | 5.3 | + +Id-14 only gives the scale of the value: how a track at that value measures. What the waves look like follows the track spectra of the literature, see "How it works". ## How it works -Unevenness is a displacement field that depends on the position on the map, made of waves 5-42 m long. Vertically there are fewer short waves, so the rails come near the peak value more often, and there are also waves of 47-83 m: they hardly count on the 10 m chord, the body rises and falls on them, and a pantograph keeps up with them. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. +Unevenness is a displacement field that depends on the position on the map, made of waves 7-90 m long sideways and 8-110 m long vertically, about the bands D1-D3 of EN 13848. Their heights follow the shape of the track spectra of the US FRA and of ORE B176 (the German spectrum): a power spectral density of `Wc² / (W² (W² + Wc²))`, `Wc = 0.8245 rad/m`, so the longer a wave, the higher it is. Most of the height is in the long waves: they hardly count on the 10 m chord, the body rises and falls on them slowly, and the cab hardly feels them. At `uneven 18` a track goes up to about 5 cm up or down and about 4.5 cm sideways off its design over the long waves, and the short ones of 7-10 m, the ones the cab shakes on, are a few millimetres. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. Each component joins separately: @@ -67,7 +69,7 @@ The ends of joined paths meet in the middle between them, with one vector across The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the body and the cab shake follow the unevenness. The slope of the ballast takes up the difference, and its foot stays as designed, on the ground. -Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres. +Models from includes (e.g. switch drives and timbers), platform edges, level crossing panels, the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres, sideways up to about 4.5 cm at `uneven 18`. On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before, as far as it has something to put in their place. It goes by the track under the vehicle, and on a switch by the path set and what its joined tracks allow. Dips at the joints and cross level replace nothing, as they don't shake the cab all the way along or sideways. On tracks with no unevenness everything works as before. @@ -83,7 +85,7 @@ On a track with unevenness the track itself shakes the cab, in place of two of t This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration. -A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. +A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 1150, for example 9.6 mm at 120 km/h, 16 mm at 70 km/h and 29 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. The physics takes the curve radius and the grade from the design, so unevenness doesn't change them. It adds only the cross level towards derailment, about 0.06 m/s² at `uneven 18` against a threshold of about 3.2 m/s². diff --git a/world/Segment.cpp b/world/Segment.cpp index d1c5f2c89..4fc928d47 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -433,8 +433,10 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; + glm::dvec3 result { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); return result; } @@ -469,7 +471,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; } @@ -507,7 +509,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist From 6c94f9743b4df9164d6444f1e9813296125e9760 Mon Sep 17 00:00:00 2001 From: pol102 Date: Fri, 20 Nov 2026 03:55:34 +0100 Subject: [PATCH 48/58] feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude --- application/editormode.cpp | 135 ++++++++++++++++++++++++++++++++++++ application/editormode.h | 6 ++ editor/editorOrthophoto.cpp | 81 ++++++++++++++++++++-- editor/editorOrthophoto.hpp | 10 +++ editor/editorSettings.cpp | 15 ++++ editor/editorSettings.hpp | 9 +++ lang/editor_pl.po | 36 ++++++++++ utilities/Globals.h | 6 ++ vehicle/Camera.cpp | 28 +++++++- 9 files changed, 317 insertions(+), 9 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index bb87aa5cb..2da0dd104 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "application/editormode.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" @@ -4258,6 +4259,11 @@ void editor_mode::render_view_menu() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + if (ImGui::BeginMenu(STR_C("Camera speed"))) + { + render_camera_settings(); + ImGui::EndMenu(); + } ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); @@ -6989,6 +6995,8 @@ void editor_mode::enter() simulation::Blackbox.close(); // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen ui_layer::draw_cursor(m_draw_cursor); + apply_camera_settings(); + Global.EditorCameraOn = true; if (simulation::Region != nullptr) { @@ -7090,6 +7098,7 @@ void editor_mode::exit() track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there ui_layer::draw_cursor(false); + Global.EditorCameraOn = false; Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -7489,6 +7498,22 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in lay_switch_mode(); break; + case GLFW_KEY_GRAVE_ACCENT: + // ~ (left of 1): the orthophoto shown or hidden; with Ctrl what the camera sees downloaded before anything else + if (false == is_press(Action) || ImGui::GetIO().WantTextInput) + break; + if (Mods & GLFW_MOD_CONTROL) + { + orthophoto_hurry(); + break; + } + if (false == anyModifier) + { + m_orthophoto.enabled(false == m_orthophoto.enabled()); + ui()->set_status(m_orthophoto.enabled() ? STR("Orthophoto on (~)") : STR("Orthophoto off (~)")); + } + break; + case GLFW_KEY_BACKSPACE: // the switch being clicked off the view: the last point taken back if (m_switch_designer.open && m_switch_designer.picking) @@ -8094,3 +8119,113 @@ void editor_mode::render_top_tracks_choice(bool const Combo) if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); } + +void editor_mode::apply_camera_settings() +{ + auto const &camera{EditorSettings.camera()}; + Global.EditorCameraSpeed = camera.speed; + Global.EditorCameraFast = camera.fast; + Global.EditorCameraZoomed = camera.zoomed; +} + +void editor_mode::render_camera_settings() +{ + auto &camera{EditorSettings.camera()}; + auto changed{false}; + auto release{false}; + ImGui::PushItemWidth(180.0f * Global.ui_scale); + auto speed{static_cast(camera.speed)}; + if (ImGui::SliderFloat(STR_C("Speed of the camera"), &speed, 0.05f, 10.0f, "x %.2f", ImGuiSliderFlags_Logarithmic)) + { + camera.speed = speed; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was")); + auto fast{static_cast(camera.fast)}; + if (ImGui::SliderFloat(STR_C("Ctrl speeds it up"), &fast, 1.0f, 30.0f, "x %.1f", ImGuiSliderFlags_Logarithmic)) + { + camera.fast = fast; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was")); + ImGui::PopItemWidth(); + if (ImGui::Checkbox(STR_C("In the top view as fast as the view is zoomed"), &camera.zoomed)) + changed = release = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("As it was"))) + { + camera = {}; + changed = release = true; + } + if (changed) + apply_camera_settings(); + if (release) + EditorSettings.save(); +} + +void editor_mode::orthophoto_hurry() +{ + if (false == m_orthophoto.enabled()) + m_orthophoto.enabled(true); + // what the camera sees of the ground: rays through a grid over the screen to the level of the ground under the camera, or as far + // as the reach of the orthophoto along it where they don't come down to it (the sky) + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + auto const camera{GfxRenderer->Camera_Position()}; + // the level of the ground under the camera: the terrain, else the scenery; with neither the rays go as far as the reach + std::optional level; + // only a level below the camera: one above it (in a tunnel, or flown under the terrain) would put the hits behind it + if (double ground{0.0}; m_streamer.active() && m_streamer.height_at(camera.x, camera.z, ground) && ground < camera.y) + level = ground; + else if (std::vector found; Global.EditorOrtho == false) + { + auto const heights{ground_heights({camera}, true, &found)}; + if (false == found.empty() && found.front() != 0 && heights.front() < camera.y) + level = heights.front(); + } + double constexpr reach{2500.0}; + glm::dvec2 low{camera.x, camera.z}; + glm::dvec2 high{camera.x, camera.z}; + for (int j = 0; j <= 6; ++j) + for (int i = 0; i <= 6; ++i) + { + glm::vec2 const ndc{static_cast(i) / 3.0f - 1.0f, static_cast(j) / 3.0f - 1.0f}; + auto const point = [&inverse, &ndc](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + if (Global.EditorOrtho) + { + // the view straight down: the corners of the screen are where it reaches on the ground + auto const corner{camera + point(0.0f)}; // the view matrix is camera-relative + low = glm::min(low, glm::dvec2{corner.x, corner.z}); + high = glm::max(high, glm::dvec2{corner.x, corner.z}); + continue; + } + auto direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + continue; + direction = glm::normalize(direction); + glm::dvec2 flat{direction.x, direction.z}; + auto distance{reach}; + if (level && direction.y < -1e-6) + distance = std::min(reach, (camera.y - *level) / -direction.y * glm::length(flat)); + if (glm::length(flat) < 1e-6) + continue; + flat = glm::normalize(flat) * distance; + glm::dvec2 const hit{camera.x + flat.x, camera.z + flat.y}; + low = glm::min(low, hit); + high = glm::max(high, hit); + } + auto const count{m_orthophoto.hurry(low, high, camera)}; + ui()->set_status(count > 0 ? format(STR_C("Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)"), count) + : std::string{STR("Orthophoto: the view is all shown already (Ctrl+~)")}); +} diff --git a/application/editormode.h b/application/editormode.h index 148edb25a..dcf5e0e3d 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -871,6 +871,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); + // View > Camera speed: the speed of the free camera, the Ctrl multiplier, in the top view as fast as it's zoomed; kept in the + // settings of the editor and handed to the camera + void render_camera_settings(); + void apply_camera_settings(); + // ~ (Ctrl): the orthophoto of what the camera sees downloaded before the rest, the ones which failed tried again at once + void orthophoto_hurry(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor void render_environment_window(); bool m_environment_open{false}; diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index f663dd012..926983444 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -1032,6 +1032,20 @@ editor_orthophoto::statistics editor_orthophoto::stats() const return out; } +int editor_orthophoto::first_level(tile const &Tile, int const Level) +{ + // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow + // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk + if (Level > standard_pixels && Tile.level < standard_pixels) + return standard_pixels; + return Level; +} + +bool editor_orthophoto::outside_area(tile_key const &Key) const +{ + return false == m_area.empty() && 0 == m_area_tiles.count(Key); +} + int editor_orthophoto::level_for(int Distance, bool Hires) { // coarser imagery further away keeps the memory use of large radii in check @@ -1630,7 +1644,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) { tile_key const key{centre.first + dx, centre.second + dy}; // outside the download area: nothing asked for, nothing shown - if (false == m_area.empty() && 0 == m_area_tiles.count(key)) + if (outside_area(key)) { if (auto const found{m_tiles.find(key)}; found != m_tiles.end()) { @@ -1642,11 +1656,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; - int level = level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires); - // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow - // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk - if (level > standard_pixels && t.level < standard_pixels) - level = standard_pixels; + int const level = first_level(t, level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires)); if (t.empty || (t.level == level && t.alpha == m_alpha) || (t.requested == level && t.requested_alpha == m_alpha) || now < t.retry_at) continue; schedule(key, t, level, m_alpha); @@ -1713,7 +1723,8 @@ void editor_orthophoto::worker() continue; long long const dx = it->key.first - m_focus.first; long long const dy = it->key.second - m_focus.second; - long long const d = dx * dx + dy * dy; + // the tiles hurried (Ctrl+~) before all the others, the nearest of them first + long long const d = dx * dx + dy * dy - (m_urgent.count(it->key) > 0 ? (1LL << 40) : 0LL); if (d < bestdistance) { bestdistance = d; @@ -1730,6 +1741,7 @@ void editor_orthophoto::worker() { current = *best; m_queue.erase(best); + m_urgent.erase(current.key); m_running.insert(current.key); if (current.level >= hires_pixels) ++m_running_hires; @@ -1957,3 +1969,58 @@ void editor_orthophoto::draw(glm::mat4 const &ViewProjection, glm::dvec3 const & drawlist->PopTextureID(); } } + +bool editor_orthophoto::hurry_tile(tile_key const &Key, int const Distance) +{ + // as update() does: nothing asked for outside the download area, nor outside the area the service covers, where the requests + // can't be answered + if (outside_area(Key)) + return false; + auto &t{m_tiles[Key]}; + if (false == in_service_area(Key.first, Key.second)) + t.empty = true; + if (t.empty) + return false; + auto const level{first_level(t, level_for(Distance, m_config.hires))}; + t.retry_at = 0.0; + if (t.level == level && t.alpha == m_alpha) + return false; // already shown as it should be + if (false == (t.requested == level && t.requested_alpha == m_alpha)) + schedule(Key, t, level, m_alpha); + return true; +} + +std::size_t editor_orthophoto::hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera) +{ + if (false == m_enabled) + return 0; + // the tile of the camera as it is now: it isn't followed while the layer is off + m_camera_tile = camera_tile(Camera); + { + std::lock_guard lock(m_mutex); + m_focus = m_camera_tile; + } + auto const a{camera_tile(glm::dvec3{Min.x, 0.0, Min.y})}; + auto const b{camera_tile(glm::dvec3{Max.x, 0.0, Max.y})}; + tile_key const first{std::min(a.first, b.first), std::min(a.second, b.second)}; + tile_key const last{std::max(a.first, b.first), std::max(a.second, b.second)}; + auto const centre{m_camera_tile}; + int const radius = m_config.radius; + std::vector keys; + for (int y = first.second; y <= last.second; ++y) + for (int x = first.first; x <= last.first; ++x) + { + tile_key const key{x, y}; + auto const distance{std::max(std::abs(x - centre.first), std::abs(y - centre.second))}; + if (distance <= radius && hurry_tile(key, distance)) + keys.push_back(key); + } + auto const count{keys.size()}; + { + std::lock_guard lock(m_mutex); + m_urgent.clear(); + m_urgent.insert(keys.begin(), keys.end()); + } + m_wakeup.notify_all(); + return count; +} diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index d6fd43f8d..450dca9b7 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -102,6 +102,9 @@ class editor_orthophoto editor_orthophoto(editor_orthophoto const &) = delete; editor_orthophoto &operator=(editor_orthophoto const &) = delete; + // the tiles over a rectangle of the world (x, z; what the camera sees), within the reach around the camera, asked for before anything + // else, the ones which failed tried again at once. returns: how many were put at the front of the queue + std::size_t hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera); bool enabled() const { return m_enabled; } // disabling drops the queue and returns the gpu memory of the resident tiles void enabled(bool State); @@ -245,6 +248,12 @@ class editor_orthophoto }; static int level_for(int Distance, bool Hires); + // the level a tile is asked for at first: a tile showing nothing yet takes the standard image before the 4K one + static int first_level(tile const &Tile, int Level); + // the tile is outside the download area set, which then has no imagery asked for it + bool outside_area(tile_key const &Key) const; + // a tile of the view hurried: put at the front of the queue unless it's shown as it should be. true: counted among the hurried + bool hurry_tile(tile_key const &Key, int Distance); tile_key camera_tile(glm::dvec3 const &Camera) const; glm::dvec2 tile_corner(tile_key const &Key) const; // world (x,z) of the north-west corner void schedule(tile_key const &Key, tile &Tile, int Level, std::uint8_t Alpha); @@ -300,6 +309,7 @@ class editor_orthophoto bool m_prefetch_paused{false}; source m_prefetch_source; std::uint32_t m_prefetch_generation{0}; + std::set m_urgent; // asked for by hurry(): workers take these first; guarded by m_mutex std::atomic m_stop{false}; std::atomic m_generation{1}; diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index c7e162c46..dd475b183 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -198,6 +198,18 @@ bool editorSettings::load() layer.terms = fields[5]; m_wms_layers.push_back(layer); } + else if (key == "camera_speed") + { + parse(value, m_camera.speed); + m_camera.speed = std::clamp(m_camera.speed, 0.05, 10.0); + } + else if (key == "camera_fast") + { + parse(value, m_camera.fast); + m_camera.fast = std::clamp(m_camera.fast, 1.0, 30.0); + } + else if (key == "camera_zoomed") + m_camera.zoomed = (value == "1"); else if (key.rfind(origin_prefix, 0) == 0) { // northing;easting @@ -269,6 +281,9 @@ bool editorSettings::save() stream << "laying_heights " << (m_heights == lay_heights::points ? "points" : m_heights == lay_heights::level ? "level" : "fitted") << "\n"; for (auto const &layer : m_wms_layers) stream << "wms_layer " << (layer.visible ? 1 : 0) << ";" << layer.opacity << ";" << encoded(layer.url) << ";" << encoded(layer.layers) << ";" << encoded(layer.title) << ";" << encoded(layer.terms) << "\n"; + stream << "camera_speed " << m_camera.speed << "\n"; + stream << "camera_fast " << m_camera.fast << "\n"; + stream << "camera_zoomed " << (m_camera.zoomed ? 1 : 0) << "\n"; stream << std::fixed << std::setprecision(3); for (auto const &origin : m_orthophoto_origins) stream << origin.first << " " << origin.second.first << ";" << origin.second.second << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index 548f12b61..5223fca51 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -119,10 +119,19 @@ public: }; lay_heights heights() const { return m_heights; } void heights(lay_heights Heights) { m_heights = Heights; } + // the free camera: its speed, how many times faster Ctrl makes it, and in the top view as fast as the view is zoomed + struct camera_settings + { + double speed{1.0}; + double fast{30.0}; + bool zoomed{false}; // off as the editor was before: "As it was" means it + }; + camera_settings &camera() { return m_camera; } private: movement_scheme m_movement{movement_scheme::wsad}; orthophoto_settings m_orthophoto; + camera_settings m_camera; std::map> m_orthophoto_origins; std::vector m_wms_layers; double m_platform_edge{1.725}; diff --git a/lang/editor_pl.po b/lang/editor_pl.po index b765a98d6..6484fdd75 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14266,3 +14266,39 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" + +msgid "Camera speed" +msgstr "Prędkość kamery" + +msgid "Speed of the camera" +msgstr "Prędkość kamery" + +msgid "How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was" +msgstr "Jak szybko strzałki albo WSAD przesuwają kamerę, z Shiftem trochę szybciej; 1 = jak dotąd" + +msgid "Ctrl speeds it up" +msgstr "Przyspieszenie z Ctrl" + +msgid "How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was" +msgstr "Ile razy szybciej jedzie kamera z wciśniętym Ctrl, także Ctrl+Shift; 30 = jak dotąd" + +msgid "In the top view as fast as the view is zoomed" +msgstr "W widoku z góry prędkość zależna od powiększenia" + +msgid "Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom" +msgstr "Przybliżona mapa jedzie wolno, oddalona szybko: po ekranie zawsze w tym samym tempie" + +msgid "As it was" +msgstr "Przywróć domyślne" + +msgid "Orthophoto on (~)" +msgstr "Ortofoto włączone (~)" + +msgid "Orthophoto off (~)" +msgstr "Ortofoto wyłączone (~)" + +msgid "Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)" +msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" + +msgid "Orthophoto: the view is all shown already (Ctrl+~)" +msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" diff --git a/utilities/Globals.h b/utilities/Globals.h index c20adc05e..cdbab2c74 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -199,6 +199,12 @@ struct global_settings { bool EditorOrtho{ false }; float EditorOrthoExtent{ 150.f }; int EditorOrthoTracks{ 0 }; // the railway in the top view of the editor: 0 whole, 1 without the ballast, 2 the rails alone + // the free camera of the editor: its speed set in the View menu, the Ctrl multiplier of it, and in the top view whether it goes as far + // as the view reaches, so the map moves across the screen as fast zoomed in as out + bool EditorCameraOn{ false }; // the editor is on: its camera goes by the settings below + double EditorCameraSpeed{ 1.0 }; + double EditorCameraFast{ 30.0 }; + bool EditorCameraZoomed{ false }; GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury GLint iMaxCabTextureSize{ 4096 }; // largest allowed texture in vehicle cab int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 55d4691d1..fe1a85c9a 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -62,6 +62,30 @@ TCamera::OnCommand( command_data const &Command ) { // threshold position on stick between walk lerp and walk/run lerp auto const stickthreshold = 2.0 / 3.0; + // the free camera of the editor as fast as its View menu sets it, Ctrl by the multiplier set there, in the top view by how far it reaches + auto editorscale { 1.0 }; + auto editorfast { -1.0 }; + if( Global.EditorCameraOn && m_owner == nullptr ) { + editorscale = Global.EditorCameraSpeed; + if( Global.EditorOrtho && Global.EditorCameraZoomed ) { + editorscale *= std::clamp( static_cast( Global.EditorOrthoExtent ) / 150.0, 0.02, 200.0 ); + } + editorfast = Global.EditorCameraFast; + } + // how many times faster the fast command of a move makes it: the editor's own, or the free fly's (Default) and the cab's (Cab) + auto const fastness = [&]( bool const Fast, double const Editor, double const Default, double const Cab ) { + if( false == Fast ) { + return 1.0; + } + if( editorfast > 0.0 ) { + return Editor; + } + if( false == FreeFlyModeFlag ) { + return 1.0; + } + return m_owner == nullptr ? Default : Cab; + }; + bool iscameracommand { true }; switch( Command.command ) { @@ -82,7 +106,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::movehorizontalfast ? m_owner == nullptr ? 30.0 : 5.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::movehorizontalfast, editorfast, 30.0, 5.0 ); // left-right m_moverate.x = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -101,7 +125,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::moveverticalfast ? m_owner == nullptr ? 10.0 : 3.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::moveverticalfast, std::max( 1.0, editorfast / 3.0 ), 10.0, 3.0 ); // up-down m_moverate.y = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; From c5d14e93ac9947a88730b2e490e367c6dc5116b0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:39:40 +0100 Subject: [PATCH 49/58] fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number again ee3af0bf (#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416: ee3af0bf moved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r --- application/scenarioloaderuilayer.cpp | 2 +- tests/unit/test_utilities.cpp | 52 +++++++++++++++++++++++---- utilities/utilities.cpp | 4 +-- utilities/utilities.h | 7 +++- 4 files changed, 54 insertions(+), 11 deletions(-) diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 207a1756e..87366757f 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -88,7 +88,7 @@ std::vector scenarioloader_ui::get_random_trivia() json triviaData = json::parse(fileContent); // select random - int i = Random(0, static_cast(triviaData.size()) - 1); + int i = RandomInt(0, static_cast(triviaData.size()) - 1); std::string triviaStr = triviaData[i]["text"]; std::string background = triviaData[i]["background"]; if (triviaData[i].contains("scenery")) diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index d26472248..3bcb565a8 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -8,6 +8,9 @@ #include "utilities/Globals.h" #include "utilities/utilities.h" +#include +#include + // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their // oddities included. the ones which look like mistakes are listed in COVERAGE.md. the helpers which read from a // parser (LoadPoint, the sets, the map) are in test_parser.cpp @@ -115,16 +118,31 @@ TEST_CASE("utilities: clearing a flag needs all of its bits set") { TEST_CASE("utilities: random whole numbers are within the bounds, both included, given in any order") { std::set seen; for (auto draw{0}; draw < 200; ++draw) { - auto const value{Random(3, 7)}; + auto const value{RandomInt(3, 7)}; CHECK(value >= 3); CHECK(value <= 7); seen.insert(value); - auto const swapped{Random(7, 3)}; + auto const swapped{RandomInt(7, 3)}; CHECK(swapped >= 3); CHECK(swapped <= 7); } CHECK(seen.size() == 5); - CHECK(Random(5, 5) == 5); + CHECK(RandomInt(5, 5) == 5); +} + +TEST_CASE("utilities: whole-number bounds still give a real number in between") { + // the wind, the wheel flats, the truck hunting and the tachometer draw with whole-number bounds + static_assert(std::is_same_v); + auto fractions{0}; + for (auto draw{0}; draw < 50; ++draw) { + auto const value{Random(0, 4)}; + CHECK(value >= 0.0); + CHECK(value <= 4.0); + if (value != std::floor(value)) { + ++fractions; + } + } + CHECK(fractions > 0); } TEST_CASE("utilities: random numbers are within the bounds given in any order") { @@ -157,17 +175,37 @@ TEST_CASE("utilities: random numbers are within the bounds given in any order") } TEST_CASE("utilities: the same seed gives the same random numbers") { - std::vector first; + std::vector first; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - first.push_back(Random(0, 1000000)); + first.push_back(Random(0.0, 1000000.0)); } - std::vector second; + std::vector second; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - second.push_back(Random(0, 1000000)); + second.push_back(Random(0.0, 1000000.0)); } CHECK(first == second); + std::vector localfirst; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localfirst.push_back(RandomInt(0, 1000000)); + } + std::vector localsecond; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localsecond.push_back(RandomInt(0, 1000000)); + } + CHECK(localfirst == localsecond); +} + +TEST_CASE("utilities: the whole numbers are drawn from the local engine, not from that of the run's seed") { + // the trivia of the loading screen is drawn before a network client gets the seed of the session + Global.random_engine.seed(5); + auto const first{Random()}; + Global.random_engine.seed(5); + RandomInt(0, 9); + CHECK(Random() == first); } TEST_CASE("utilities: the local random numbers have an engine of their own") { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index d704fe9b7..a88b692c1 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -150,11 +150,11 @@ double Random(double min, double max) return dist(Global.random_engine); } -int Random(int min, int max) +int RandomInt(int min, int max) { if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB) std::uniform_int_distribution dist(min, max); - return dist(Global.random_engine); + return dist(Global.local_random_engine); } std::uint64_t true_random_seed() diff --git a/utilities/utilities.h b/utilities/utilities.h index 8c4181475..d2b3e5a6f 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -64,7 +64,12 @@ inline long Round(double const f) } double Random(double a, double b); -int Random(int min, int max); +// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number +// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the +// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it +// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would +// put that engine out of step with the other machines of a network session +int RandomInt(int min, int max); /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. From c556c4c8fdc51982b91bef6432f48c68febc78ab Mon Sep 17 00:00:00 2001 From: pol102 Date: Sat, 21 Nov 2026 10:39:53 +0100 Subject: [PATCH 50/58] fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 --- application/editormode.cpp | 3 ++ editor/editorOrthophoto.cpp | 68 ++++++++++++++++++++++++++------ editor/editorOrthophoto.hpp | 12 ++++++ editor/editorTerrainStreamer.cpp | 39 ++++++++++++++++++ editor/editorTerrainStreamer.hpp | 9 +++++ 5 files changed, 118 insertions(+), 13 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index 2da0dd104..c9b50c3f0 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -601,6 +601,9 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); }); Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // with the heightmap terrain, a new tile waits while a chunk under it is still to come; where none is nor will be, or the walk of + // the chunks doesn't reach, it lies on the other ground or on the NMT guess as before. A scenery without it as before + Layer.coming_source([](glm::dvec2 const &Min, glm::dvec2 const &Max) { return EditorTerrain.active() && EditorTerrain.ground_coming(Min, Max); }); // the imagery often comes before the terrain made from the model: it lies where the terrain will be Layer.guess_source([this](double const X, double const Z, double &Height) { if (nmt_ground(X, Z, Height)) diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index 926983444..ac198746c 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -937,23 +937,47 @@ void editor_orthophoto::ground_arrived() { if (!m_height) return; - for (auto &entry : m_tiles) + for (auto &[key, t] : m_tiles) { - auto &t{entry.second}; - if (!t.grounded || !t.guessed) - continue; - // the middle and the corners: a chunk of the terrain is much larger than a tile, it covers some of these when it comes. A tile - // lying flat, with nothing to go by, also goes onto the model once it's in - glm::dvec2 const corner = tile_corner(entry.first); - for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) - if (double y; m_height(corner.x - u * tile_size, corner.y - v * tile_size, y) || (t.heights.empty() && m_guess && m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y))) - { - t.grounded = false; - break; - } + if (t.grounded && ground_came(key, t)) + t.grounded = false; } } +bool editor_orthophoto::waits_for_ground(tile_key const &Key) const +{ + // a tile laid out already stays, sampled again when its ground comes (ground_came) + if (!m_coming || m_tiles.contains(Key)) + return false; + glm::dvec2 const corner = tile_corner(Key); + return m_coming(corner - glm::dvec2{tile_size}, corner); +} + +bool editor_orthophoto::ground_came(tile_key const &Key, tile const &Tile) const +{ + glm::dvec2 const corner = tile_corner(Key); + // a tile lying flat, with nothing to go by, also goes onto the model once it's in: the middle and the corners + if (Tile.guessed && Tile.heights.empty() && m_guess) + for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) + if (double y; m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y)) + return true; + // the points the ground didn't answer, every second one of the grid (16 m) and the edges: a chunk of the terrain is about as + // large as a tile and comes over a part of it, often a band along a side; partly answered tiles count too, not only the guessed + static_assert(ground_grid % 2 == 0, "the edges of the grid are among its even points"); + int constexpr samples{ground_grid + 1}; + double constexpr step{tile_size / ground_grid}; + for (auto const index : Tile.unanswered) + { + int const i{index % samples}; + int const j{index / samples}; + if (i % 2 != 0 || j % 2 != 0) + continue; + if (double y; m_height(corner.x - i * step, corner.y - j * step, y)) + return true; + } + return false; +} + void editor_orthophoto::detach_scene() { for (auto &entry : m_tiles) @@ -1247,6 +1271,7 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) Tile.scene_dirty = true; Tile.heights.clear(); Tile.surface.clear(); + Tile.unanswered.clear(); glm::dvec2 const corner = tile_corner(Key); glm::dvec2 const min(corner.x - tile_size, corner.y - tile_size); @@ -1318,6 +1343,21 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) } } + // the points the ground didn't answer: the ground coming there later (the terrain loaded after the imagery, which comes from the + // disk cache at once) has the tile sampled again, rather than left at the heights filled in or guessed now + Tile.unanswered.clear(); + auto const columns{static_cast(samples)}; + for (std::size_t index = 0; index < heights.size(); ++index) + { + if (heights[index] != no_height) + continue; + // in the scene the heights come from the triangles, and a steep spot (a wall, a quarry face) gives none: where the heightmap + // terrain answers the point, its ground is there already, and ground_came() would find it again on every chunk that comes + if (double y; surface && m_height && m_height(corner.x - static_cast(index % columns) * step, corner.y - static_cast(index / columns) * step, y)) + continue; + Tile.unanswered.push_back(static_cast(index)); + } + // holes (places without ground) take the average of their neighbours, spreading inwards std::size_t missing = std::count(heights.begin(), heights.end(), no_height); if (missing == heights.size()) @@ -1653,6 +1693,8 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) } continue; } + if (waits_for_ground(key)) + continue; tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index 450dca9b7..4811c99c1 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -120,6 +120,10 @@ class editor_orthophoto // the heights the ground will have where there's none yet, as of the terrain model on its way: a tile laid out before its // ground comes lies there, or level with the tiles beside, rather than at the height of the layer far below or above void guess_source(height_query Query) { m_guess = std::move(Query); } + // true while the ground under an XZ rectangle (Min/Max are x,z) is still to come. A new tile there waits for it, rather than + // being laid out at the height of the layer; elsewhere it lies on whatever ground there is, or on the guess, as without it + using coming_query = std::function; + void coming_source(coming_query Query) { m_coming = std::move(Query); } // the area the imagery is downloaded in, a polygon of PUWG 1992 (easting, northing): its tiles go to the disk cache in the // background, the products the settings ask for, and no tile outside it is asked for around the camera. Empty: no area, the // tiles around the camera as before @@ -239,6 +243,9 @@ class editor_orthophoto float height_max{0.0f}; std::vector surface; // upward facing ground triangles clipped to the tile (3 vertices each) bool guessed{false}; // no ground under it when sampled: the heights guessed, from the terrain model or the tiles beside + // the points of the grid of the heights the ground didn't answer when sampled (rows north->south, as heights): filled from + // the points beside or guessed, and sampled again once the ground comes under one of them + std::vector unanswered; // scene geometry scene::basic_section *section{nullptr}; // section holding the shape (nullptr = not in the scene) scene::basic_cell *cell{nullptr}; // set instead of the section's shape list when the shape is translucent @@ -262,6 +269,10 @@ class editor_orthophoto void release_tile(tile &Tile); texture_slot acquire_slot(); void sample_ground(tile_key const &Key, tile &Tile); + // the ground has come under a point of the tile which had none when it was sampled + bool ground_came(tile_key const &Key, tile const &Tile) const; + // a new tile isn't asked for yet: the ground under it is still to come + bool waits_for_ground(tile_key const &Key) const; // the height of the ground sampled under a tile beside Own at the point, the tiles with guessed heights left out bool sampled_height(tile_key const &Own, double const X, double const Z, float &Height) const; void build_shape(tile_key const &Key, tile &Tile); @@ -281,6 +292,7 @@ class editor_orthophoto ground_query m_ground; height_query m_height; height_query m_guess; + coming_query m_coming; scene::basic_region *m_region{nullptr}; // region the scene geometry was put into std::multimap m_free_chunks; // geometry chunks by capacity, reused between tiles // the scene opacity is baked into the textures, which means reading the tiles again; applied once the value settles diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a681b1a9e..9c00017de 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include terrain_streamer EditorTerrain; @@ -907,6 +908,44 @@ bool terrain_streamer::owns(gfx::geometry_handle const &Geometry) const return false; } +bool terrain_streamer::in_walk(chunk_key const &Key) const +{ + // the circle update() walks around the camera and around where it's heading + auto const within = [this, &Key](chunk_key const &Centre) { + auto const dx{Key.first - Centre.first}; + auto const dz{Key.second - Centre.second}; + return std::abs(dx) <= m_walkradius && std::abs(dz) <= m_walkradius && dx * dx + dz * dz <= (m_walkradius + 1) * (m_walkradius + 1); + }; + return within(m_walkhere) || within(m_walkthere); +} + +bool terrain_streamer::chunk_coming(chunk_key const &Key) const +{ + if (m_chunks.contains(Key) || m_removed.contains(Key)) + return false; + if (m_loading.contains(Key)) + return true; + // a chunk the walk doesn't reach at this distance isn't loaded, so it isn't waited for: it's taken in when the camera comes near + if (false == in_walk(Key)) + return false; + // still to come while its pack isn't read yet, or it's in its pack; not there where the pack is read without it + auto const pack{m_packs.find(heightmap::pack_of(Key))}; + if (pack == m_packs.end() || pack->second.status == pack_state::state::unknown || pack->second.status == pack_state::state::loading) + return true; + return pack->second.status == pack_state::state::ready && pack->second.file->has(Key); +} + +bool terrain_streamer::ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const first{heightmap::chunk_at(Low.x, Low.y)}; + auto const last{heightmap::chunk_at(High.x, High.y)}; + for (auto z{std::min(first.second, last.second)}; z <= std::max(first.second, last.second); ++z) + for (auto x{std::min(first.first, last.first)}; x <= std::max(first.first, last.first); ++x) + if (chunk_coming(chunk_key{x, z})) + return true; + return false; +} + bool terrain_streamer::exists(chunk_key const &Key) const { if (m_chunks.count(Key) > 0) diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index cf8407ac1..760335a75 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -81,6 +81,10 @@ class terrain_streamer std::string stats() const; // chunks in the pack files and in memory, less the removed ones; the files known so far bool exists(chunk_key const &Key) const; + // true while a chunk over an XZ rectangle (Low/High are x,z) is still to come at this distance of the camera: being loaded, or + // within the walk around the camera and in its pack or with its pack not read yet. False where all of them are in memory, where + // none is nor will be, and where the walk doesn't reach + bool ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const; // editing; the chunks changed are written to the files by save() heightmap::manifest const &manifest() const { return m_manifest; } @@ -235,6 +239,11 @@ class terrain_streamer scene::basic_cell *cell{nullptr}; }; + // within the circle of chunks the last walk of update() asked for + bool in_walk(chunk_key const &Key) const; + // the chunk is still to come at this distance of the camera (see ground_coming) + bool chunk_coming(chunk_key const &Key) const; + void start_workers(); void stop_workers(); void worker(); From 988c0af5895a01edca87a0faa474003b903e9e2e Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:40:07 +0100 Subject: [PATCH 51/58] fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r --- application/editormode.cpp | 4 +- application/editormode.h | 3 + editor/editorGeoMap.cpp | 8 +- editor/editorGeoMap.hpp | 2 + editor/editorHttp.cpp | 261 ++++++++++++++++++++++++-------- editor/editorOrthophoto.cpp | 14 +- editor/editorOrthophoto.hpp | 5 +- tests/unit/CMakeLists.txt | 2 + tests/unit/test_editor_http.cpp | 138 +++++++++++++++++ 9 files changed, 363 insertions(+), 74 deletions(-) create mode 100644 tests/unit/test_editor_http.cpp diff --git a/application/editormode.cpp b/application/editormode.cpp index c9b50c3f0..a40c6e081 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -618,6 +618,8 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) editor_mode::~editor_mode() { editor_track::observe(nullptr); + // the capabilities of a WMS service being read are given up rather than waited for to their timeouts + m_wms_adding.closing = true; } std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const @@ -4101,7 +4103,7 @@ void editor_mode::render_wms_adding() adding.info.reset(); adding.ticked.clear(); adding.service = url; - adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + adding.reading = std::async(std::launch::async, [url, closing = &adding.closing]() { return editor_orthophoto::describe(url, [closing]() { return closing->load(); }); }); } if (adding.reading.valid()) { diff --git a/application/editormode.h b/application/editormode.h index dcf5e0e3d..d25840e18 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -915,6 +916,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri { std::array url{}; std::array filter{}; + // the reading is given up: the editor goes. before the reading, so it outlives the future waiting for the reading to end + std::atomic closing{false}; std::future reading; std::optional info; std::string service; // the address the capabilities were read of diff --git a/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index ab7f74b24..68b153559 100644 --- a/editor/editorGeoMap.cpp +++ b/editor/editorGeoMap.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorGeoMap.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorHttp.hpp" #include "editor/editorOrthophoto.hpp" #include "utilities/translation.h" @@ -164,6 +165,8 @@ bool parse_place(std::string const &Text, glm::dvec2 &Point) editor_map::~editor_map() { + // the download running is broken off rather than waited for to its end or its timeout + m_closing = true; if (m_request.valid()) m_request.wait(); release(); @@ -328,12 +331,13 @@ void editor_map::request(glm::vec2 const &Size) char bbox[160]; std::snprintf(bbox, sizeof(bbox), "%.1f,%.1f,%.1f,%.1f", low.x, low.y, high.x, high.y); auto const url{kMapService + "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=osm&STYLES=&SRS=EPSG:2180&BBOX=" + bbox + "&WIDTH=" + std::to_string(width) + "&HEIGHT=" + std::to_string(height) + "&FORMAT=image/png"}; - m_request = std::async(std::launch::async, [url, low, high]() { + m_request = std::async(std::launch::async, [url, low, high, closing = &m_closing]() { image result; result.low = low; result.high = high; std::vector data; - if (false == editor_http_get(url, data, result.error)) + thread_local editor_http::client client; + if (false == client.get(url, data, result.error, [closing]() { return closing->load(); })) return result; int w{0}, h{0}, components{0}; // the texture loader turns the stb flip on for the whole process only once it loads its first texture: this thread diff --git a/editor/editorGeoMap.hpp b/editor/editorGeoMap.hpp index 5c160095b..a1dd07124 100644 --- a/editor/editorGeoMap.hpp +++ b/editor/editorGeoMap.hpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -86,6 +87,7 @@ class editor_map glm::vec2 m_pressed{0.f}; bool m_dragging{false}; std::future m_request; + std::atomic m_closing{false}; // the download of the map is given up: the map goes std::uint64_t m_texture{0}; glm::dvec2 m_image_low{0.0}; glm::dvec2 m_image_high{0.0}; diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 81a195aeb..cbda581f0 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -45,15 +45,209 @@ struct client::platform #if defined(_WIN32) +namespace +{ + +DWORD constexpr kStopCheck{50}; // ms between the looks at whether the transfer is to be given up + +// what the callback of WinHTTP hands over to the thread waiting for it +struct transfer_state +{ + HANDLE done{::CreateEventW(nullptr, FALSE, FALSE, nullptr)}; // the operation begun finished or failed + HANDLE closed{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; // the request is called back no more + DWORD error{ERROR_SUCCESS}; // of the operation that failed + DWORD size{0}; // bytes available or read + + transfer_state() = default; + transfer_state(transfer_state const &) = delete; + transfer_state &operator=(transfer_state const &) = delete; + ~transfer_state() + { + if (done != nullptr) + ::CloseHandle(done); + if (closed != nullptr) + ::CloseHandle(closed); + } +}; + +void CALLBACK on_status(HINTERNET, DWORD_PTR const Context, DWORD const Status, LPVOID const Info, DWORD const Length) +{ + auto *state{reinterpret_cast(Context)}; + if (state == nullptr) + return; + switch (Status) + { + case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: + case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: + break; + case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: + state->size = *static_cast(Info); + break; + case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: + state->size = Length; + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + state->error = static_cast(Info)->dwError; + break; + case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: + ::SetEvent(state->closed); + return; + default: + return; + } + ::SetEvent(state->done); +} + +// one GET on a connection of its own. the steps of WinHTTP are asynchronous and waited for while the stop is looked at, so a +// transfer is given up at once also while a service keeps the connection waiting: the closing of the editor doesn't wait for +// the timeouts of a service that doesn't answer +class transfer +{ + public: + transfer(stop_check const &Stop, std::string &Error) : + m_stop(Stop), + m_error(Error) + { + } + ~transfer() + { + close(); + } + transfer(transfer const &) = delete; + transfer &operator=(transfer const &) = delete; + + bool open(HINTERNET const Session, std::wstring const &Host, INTERNET_PORT const Port, std::wstring const &Path, bool const Secure) + { + if (m_state.done == nullptr || m_state.closed == nullptr) + return failed(::GetLastError()); + m_connection = ::WinHttpConnect(Session, Host.c_str(), Port, 0); + if (m_connection == nullptr) + return failed(::GetLastError()); + m_request = ::WinHttpOpenRequest(m_connection, L"GET", Path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, Secure ? WINHTTP_FLAG_SECURE : 0); + if (m_request == nullptr) + return failed(::GetLastError()); + auto context{reinterpret_cast(&m_state)}; + if (false == ::WinHttpSetOption(m_request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context))) + return failed(::GetLastError()); + if (::WinHttpSetStatusCallback(m_request, on_status, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, 0) == WINHTTP_INVALID_STATUS_CALLBACK) + return failed(::GetLastError()); + m_called_back = true; + return true; + } + + bool send() + { + return step([this]() { return ::WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast(&m_state)); }); + } + + bool receive() + { + return step([this]() { return ::WinHttpReceiveResponse(m_request, nullptr); }); + } + + DWORD status() const + { + DWORD status{0}; + DWORD size{sizeof(status)}; + ::WinHttpQueryHeaders(m_request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + return status; + } + + // the whole body of the response + bool read_all(std::vector &Out) + { + while (true) + { + if (m_stop()) + { + m_error = "cancelled"; + return false; + } + if (false == step([this]() { return ::WinHttpQueryDataAvailable(m_request, nullptr); })) + return false; + auto const available{m_state.size}; + if (available == 0) + return true; + if (Out.size() + available > kLargest) + { + m_error = kTooLarge; + Out.clear(); + return false; + } + auto const offset{Out.size()}; + Out.resize(offset + available); + auto const read{step([this, &Out, offset, available]() { return ::WinHttpReadData(m_request, Out.data() + offset, available, nullptr); })}; + Out.resize(offset + (read ? m_state.size : 0)); + if (false == read) + return false; + } + } + + void close() + { + if (m_request != nullptr) + { + ::WinHttpCloseHandle(m_request); + m_request = nullptr; + // the closing is the last callback: after it the state, and the buffer of a read broken off, are no longer written to + if (m_called_back) + ::WaitForSingleObject(m_state.closed, INFINITE); + m_called_back = false; + } + if (m_connection != nullptr) + { + ::WinHttpCloseHandle(m_connection); + m_connection = nullptr; + } + } + + private: + bool failed(DWORD const Code) + { + m_error = "WinHTTP error " + std::to_string(Code); + return false; + } + + // begins an operation and waits for it: false when it failed, or a stop was asked for meanwhile + template bool step(Begin const &Operation) + { + m_state.error = ERROR_SUCCESS; + if (false == Operation()) + return failed(::GetLastError()); + while (::WaitForSingleObject(m_state.done, kStopCheck) != WAIT_OBJECT_0) + { + if (m_stop()) + { + // closed at once: the operation broken off doesn't write into the buffer any more once this returns + close(); + m_error = "cancelled"; + return false; + } + } + if (m_state.error != ERROR_SUCCESS) + return failed(m_state.error); + return true; + } + + stop_check const &m_stop; + std::string &m_error; + transfer_state m_state; + HINTERNET m_connection{nullptr}; + HINTERNET m_request{nullptr}; + bool m_called_back{false}; // the closing of the request is called back +}; + +} // namespace + client::client() : m_platform(std::make_unique()) { wchar_t const *agent = L"MaSzyna-editor"; #ifdef WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); #endif if (m_platform->session == nullptr) // automatic proxy needs windows 8.1+ - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (m_platform->session != nullptr) ::WinHttpSetTimeouts(m_platform->session, 10000, 10000, 15000, 20000); } @@ -94,64 +288,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st std::wstring const host(parts.lpszHostName, parts.dwHostNameLength); std::wstring const path = std::wstring(parts.lpszUrlPath, parts.dwUrlPathLength) + std::wstring(parts.lpszExtraInfo, parts.dwExtraInfoLength); - HINTERNET connection = ::WinHttpConnect(m_platform->session, host.c_str(), parts.nPort, 0); - HINTERNET request = connection ? ::WinHttpOpenRequest(connection, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) - : nullptr; - auto const close = [&]() { - if (request != nullptr) - ::WinHttpCloseHandle(request); - if (connection != nullptr) - ::WinHttpCloseHandle(connection); - }; - - if (request == nullptr || !::WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || !::WinHttpReceiveResponse(request, nullptr)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); + transfer request{Stop, Error}; + if (false == request.open(m_platform->session, host, parts.nPort, path, parts.nScheme == INTERNET_SCHEME_HTTPS) || false == request.send() || false == request.receive()) return false; - } - - DWORD status{0}; - DWORD statussize{sizeof(status)}; - ::WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statussize, WINHTTP_NO_HEADER_INDEX); - - for (;;) - { - if (Stop()) - { - Error = "cancelled"; - close(); - return false; - } - DWORD available{0}; - if (!::WinHttpQueryDataAvailable(request, &available)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - if (available == 0) - break; - if (Out.size() + available > kLargest) - { - Error = kTooLarge; - close(); - Out.clear(); - return false; - } - std::size_t const offset = Out.size(); - Out.resize(offset + available); - DWORD received{0}; - if (!::WinHttpReadData(request, Out.data() + offset, available, &received)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - Out.resize(offset + received); - } - close(); + auto const status{request.status()}; + if (false == request.read_all(Out)) + return false; + request.close(); if (status != 200) { diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index ac198746c..d3254a2c1 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -63,12 +63,6 @@ double steady_seconds() } // namespace -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error) -{ - thread_local http_client client; - return client.get(Url, Out, Error, []() { return false; }); -} - namespace { @@ -688,7 +682,7 @@ std::string xml_element(std::string const &Xml, std::string const &Tag, std::siz } // namespace -editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service) +editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service, std::function const &Stop) { service_info info; auto url{Service}; @@ -700,8 +694,10 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S // a few tries, the services drop connections and time out now and then std::vector data; auto read{false}; - for (int attempt = 0; attempt < 3 && false == read; ++attempt) - read = editor_http_get(url, data, info.error); + stop_check const stopping{Stop ? Stop : stop_check{[]() { return false; }}}; + thread_local http_client client; + for (int attempt = 0; attempt < 3 && false == read && false == stopping(); ++attempt) + read = client.get(url, data, info.error, stopping); if (false == read) return info; info.error.clear(); diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index 4811c99c1..b56052e7e 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -28,8 +28,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" // material_handle #include "rendering/geometrybank.h" // gfx::geometry_handle -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error); - namespace scene { class basic_region; @@ -183,7 +181,8 @@ class editor_orthophoto bool puwg{false}; std::string error; }; - static service_info describe(std::string const &Service); + // Stop: true to give the reading up + static service_info describe(std::string const &Service, std::function const &Stop = {}); static std::string cache_directory(); private: diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c1ad98f35..cca503a01 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -32,6 +32,8 @@ add_executable(${UNIT_TESTS_NAME} # and the fouling points of the switches, widened in the curves as the gauge is "${CMAKE_SOURCE_DIR}/editor/editorGauge.cpp" "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" + # and the http client the editor fetches its aids with + "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp new file mode 100644 index 000000000..ffdfe9959 --- /dev/null +++ b/tests/unit/test_editor_http.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorHttp.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// a service on this machine. with no reply it takes the connection and the request and never answers, as geoportal.gov.pl +// does now and then +class local_server { + public: + explicit local_server(std::string Reply = {}) : + m_reply(std::move(Reply)) { + m_acceptor.open(asio::ip::tcp::v4()); + m_acceptor.bind({asio::ip::address_v4::loopback(), 0}); + m_acceptor.listen(); + m_port = m_acceptor.local_endpoint().port(); + m_thread = std::jthread{[this]() { serve(); }}; + } + ~local_server() { + m_done = true; + // a connection of its own wakes the server waiting for one + asio::ip::tcp::socket wake{m_context}; + asio::error_code ignored; + wake.connect({asio::ip::address_v4::loopback(), m_port}, ignored); + wake.close(ignored); + m_thread.join(); + } + local_server(local_server const &) = delete; + local_server &operator=(local_server const &) = delete; + + std::string url() const { + return std::format("http://127.0.0.1:{}/wcs?REQUEST=GetCapabilities", m_port); + } + + private: + void serve() { + while (false == m_done) { + asio::ip::tcp::socket socket{m_context}; + asio::error_code error; + m_acceptor.accept(socket, error); + if (error) + return; + if (false == m_reply.empty()) { + answer(socket); + continue; + } + // the request is left without an answer, the connection open, until the server goes + while (false == m_done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + // the reply once the whole request is read, then the connection closed + void answer(asio::ip::tcp::socket &Socket) const { + asio::error_code error; + asio::streambuf request; + asio::read_until(Socket, request, "\r\n\r\n", error); + if (!error) + asio::write(Socket, asio::buffer(m_reply), error); + Socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); + } + + std::string const m_reply; + asio::io_context m_context; + asio::ip::tcp::acceptor m_acceptor{m_context}; + unsigned short m_port{0}; + std::atomic m_done{false}; + std::jthread m_thread; +}; + +// the requests to the local server would go to a proxy named in the environment, which can't reach it +bool proxied() { + for (char const *variable : {"http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"}) { + if (char const *value{std::getenv(variable)}; value != nullptr && *value != '\0') + return true; + } + return false; +} + +} // namespace + +TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { + if (false == editor_http::available() || proxied()) + return; // a build with no http client, or a proxy in the way + local_server server; + auto const start{std::chrono::steady_clock::now()}; + auto const elapsed = [start]() { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); }; + editor_http::client client; + std::vector data; + std::string error; + // the stop comes while the client waits for the answer, long before any of its timeouts + auto const got{client.get(server.url(), data, error, [&elapsed]() { return elapsed() > 0.3; })}; + CHECK_FALSE(got); + CHECK_FALSE(error.empty()); + // the receive timeout is 20 s; the transfer ends within a moment of the stop (libcurl looks at it about once a second) + CHECK(elapsed() < 5.0); +} + +TEST_CASE("editor http: the whole body of a response is read") { + if (false == editor_http::available() || proxied()) + return; + std::string body(100000, '\0'); + for (std::size_t i = 0; i < body.size(); ++i) + body[i] = static_cast('a' + i % 26); + local_server server{std::format("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK(client.get(server.url(), data, error, []() { return false; })); + CHECK(error.empty()); + CHECK(std::string(data.begin(), data.end()) == body); +} + +TEST_CASE("editor http: the body of an error is kept with the status in the error") { + if (false == editor_http::available() || proxied()) + return; + // the terrain model service tells a place outside of its coverage in the body of an error + std::string const body{"outside requested coverage"}; + local_server server{std::format("HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get(server.url(), data, error, []() { return false; })); + CHECK(error == "HTTP 400"); + CHECK(std::string(data.begin(), data.end()) == body); +} From abdb814469dec0e5483aa262af42c37238517424 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:53:11 +0100 Subject: [PATCH 52/58] revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r --- simulation/simulationenvironment.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..4e8c0e5f7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -26,11 +26,12 @@ namespace { float turbidity_of( float const Overcast ) { + if( Overcast <= 0.10 ) { return 3.f; } if( Overcast <= 0.20 ) { return 4.f; } - if( Overcast <= 0.40 ) { return 5.f; } - if( Overcast <= 0.60 ) { return 6.f; } - if( Overcast <= 0.70 ) { return 7.f; } - if( Overcast <= 0.80 ) { return 8.f; } + if( Overcast <= 0.60 ) { return 5.f; } + if( Overcast <= 0.70 ) { return 6.f; } + if( Overcast <= 0.80 ) { return 7.f; } + if( Overcast <= 0.90 ) { return 8.f; } return 9.f; } From 65d3c020ebe85867183c67ad9c0ceedf704f0b40 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:26:20 +0100 Subject: [PATCH 53/58] fix(render): the free camera blurs with its own movement, the grass racing under it no longer strobes in rings (#441) The motion blur took the movement of the vehicle the camera sits in and nothing else, so in freefly (and the debug camera) the world got no blur from the camera at all. Low over grass the texture under the camera then moved tens of pixels a frame and strobed: rings around the camera, at the distances its pattern repeats, stronger with shift and ctrl, gone above about 20 m, worst on a 165 Hz screen. * the camera with no vehicle of its own blurs the world with its movement since the frame before, as a vehicle does with get_future_movement(); a jump of 50 m or more (a camera preset) is no movement * that movement is held to half a metre a frame: the blur takes the scene where the camera will be, and a camera faster than that passes the ground at the bottom of the screen within a frame, where its motion turned over into a bright band. with the shutter of the blur it still smears metres * the blur shader skips samples off the picture instead of reading its edge row again and again --- rendering/opengl33renderer.cpp | 25 +++++++++++++++++++++++++ rendering/opengl33renderer.h | 2 ++ shaders/postfx_motionblur.frag | 4 ++++ 3 files changed, 31 insertions(+) diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 3a3008a44..5215a7b9f 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -988,6 +988,31 @@ void opengl33_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const *vehicle = Global.pCamera.m_owner; glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); future = glm::translate(mv, -glm::vec3(vehicle->get_future_movement())) * glm::inverse(mv); + m_freecameraposition.reset(); + } + else if (vp.main) + { + // the free camera (freefly, debug camera) blurs the world with its own movement, as a vehicle does with its: + // without it the ground racing under a low camera strobes in rings at the distances its texture repeats. + // the movement of the frame before stands for the one to come; a jump (a camera preset) is no movement + auto const position{Global.pCamera.Pos}; + if (m_freecameraposition) + { + auto movement{glm::vec3(position - *m_freecameraposition)}; + auto const length{glm::length(movement)}; + if (length < 50.f) + { + // the blur takes the scene where the camera will be: a fast camera (shift, ctrl) moves past the ground + // at the bottom of the screen within a frame, it ends up behind it there and its motion turns over + // into a bright band. half a metre a frame still blurs metres with the shutter of the motion blur + auto const maxmovement{0.5f}; + if (length > maxmovement) + movement *= maxmovement / length; + glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); + future = glm::translate(mv, -movement) * glm::inverse(mv); + } + } + m_freecameraposition = position; } Update_Lights( simulation::Lights ); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 4322cc2db..3e97683ae 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -469,6 +469,8 @@ class opengl33_renderer : public gfx_renderer { GLuint64 m_gllasttime = 0; double m_precipitationrotation; + // where the camera with no vehicle of its own was at the frame before, for the motion blur of its movement + std::optional m_freecameraposition; glm::mat4 perspective_projection_raw(float fovy, float aspect, float znear, float zfar); glm::mat4 perspective_projection(const viewport_proj_config &c, float n, float f, glm::mat4 &frustum); diff --git a/shaders/postfx_motionblur.frag b/shaders/postfx_motionblur.frag index 146179ac9..d2b23fd03 100644 --- a/shaders/postfx_motionblur.frag +++ b/shaders/postfx_motionblur.frag @@ -32,6 +32,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) From 7c12b83ba470a83a391e61b4e654f2af29daa535 Mon Sep 17 00:00:00 2001 From: pawelw Date: Sun, 22 Nov 2026 12:27:18 +0100 Subject: [PATCH 54/58] fix(ai): an uphill start keeps the power on until the train brake is off (#396) * fix(ai): an uphill start keeps the power on until the train brake is off The uphill start of #265 ended as soon as the power held the train (or the head of the train moved back 0.5 km/h). From then on the brake still on in the wagons made Ready false, the power went off, the train rolled back, was braked again and the start began anew; only the cylinders falling below 0.8 bar let the train get away. - Once the power holds the train, the start goes on while the train brake is released: Ready holds, the power stays on, bounded to 1.5 x the grade force. It ends when the consist is released (the same test as Ready, without the hold) or after 60 s. - A start is given up for rolling back on the mass-weighted speed of the consist, not on the speed of the locomotive, which runs back into the slack of the train held by its brake. - A train slipping back uphill is not released by the rule for a train to go on. * fix(ai): an uphill start begins only with the whole train at a stand * fix(ai): an uphill start applies the train brake further while it doesn't hold the train without the locomotive brake * fix(ai): the speed and the tractive force of an uphill start in the direction of travel also from cab 2 * fix(ai): an uphill start tops up the train brake a full application time a step, at most to full service, and keeps the power between 1.1 and 1.5 times the grade force while the brake releases * fix(ai): an uphill start no longer takes a notch back in the release phase: the notch below doesn't hold the train * refactor(ai): the train brake top-up of an uphill start in uphill_start::brake_top_up(), with unit tests --- CMakeLists.txt | 1 + tests/unit/test_uphill_start.cpp | 103 +++++++++++++++++++++ vehicle/Driver.cpp | 150 ++++++++++++++++++++++++------- vehicle/Driver.h | 12 +++ vehicle/uphillstart.cpp | 36 ++++++++ vehicle/uphillstart.h | 41 +++++++++ 6 files changed, 312 insertions(+), 31 deletions(-) create mode 100644 tests/unit/test_uphill_start.cpp create mode 100644 vehicle/uphillstart.cpp create mode 100644 vehicle/uphillstart.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e563e587f..69dc5fbab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -557,6 +557,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/brakingcurve.cpp" "vehicle/handover.cpp" +"vehicle/uphillstart.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp new file mode 100644 index 000000000..d450af68b --- /dev/null +++ b/tests/unit/test_uphill_start.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/uphillstart.h" + +// starting uphill, the train brake is applied further, a step at a time, until the brake of the unpowered vehicles +// holds the train without the locomotive brake (eu07/maszyna#396). the numbers are those of an ST43 with 37 empty +// wagons on 12.5 per mille: 1040 t, 128.6 kN of grade force, the wagons on G with about 22 s to apply + +using uphill_start::brake_top_up; +using uphill_start::top_up; +using uphill_start::top_up_action; + +namespace { + +double const grade{128600.0}; // [N] +double const application{22.0}; // [s] + +// the train standing with the brake handle at Position, held there long enough for the cylinders to fill, while +// each step adds Gain of brake force (as a multiple of the grade force) to the Start it had. runs the top-up until it +// lets the locomotive brake off, and returns the handle position it stopped at and the number of steps +struct outcome { + double position; + int steps; +}; +outcome run_top_up(double Start, double Gain, double Position = 1.25) { + top_up state; + auto force{Start * grade}; + auto steps{0}; + for (auto guard{0}; guard < 100; ++guard) { + auto const action{brake_top_up(state, force, grade, Position, application, application)}; + if (action == top_up_action::none) { + break; + } + REQUIRE(action == top_up_action::step); + Position += 0.25; + force += Gain * grade; + ++steps; + } + return {Position, steps}; +} + +} // namespace + +TEST_CASE("uphill start: a brake that holds the train isn't applied further") { + top_up state; + CHECK(brake_top_up(state, 1.1 * grade, grade, 1.25, application, application) == top_up_action::none); + CHECK(state.last_force < 0.0); +} + +TEST_CASE("uphill start: each step waits the full application time of the brake") { + top_up state; + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, 0.5 * application, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, application, application) == top_up_action::step); + // the handle has just moved + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, 0.0, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, application - 0.1, application) == top_up_action::wait); +} + +TEST_CASE("uphill start: a light application is topped up until the brake holds the train") { + // before Nowy Zagorz on linia_107_objazdy: 0.64 bar in the wagons, 128 kN against 129 kN + auto const result{run_top_up(0.995, 0.15)}; + CHECK(result.steps == 1); + CHECK(result.position == doctest::Approx(1.5)); +} + +TEST_CASE("uphill start: a brake that doesn't get stronger ends the top-up after one more step") { + // all the wagon brakes cut out: no step adds anything + auto const result{run_top_up(0.0, 0.0)}; + CHECK(result.steps == 1); + CHECK(result.position < uphill_start::top_up_position); +} + +TEST_CASE("uphill start: a brake that gets stronger by too little ends the top-up") { + // a step adds 1% of the grade force, below the 2% that counts + auto const result{run_top_up(0.3, 0.01)}; + CHECK(result.steps == 1); + SUBCASE("and one that gets stronger by enough goes on") { + auto const going{run_top_up(0.3, 0.05)}; + CHECK(going.steps > 1); + } +} + +TEST_CASE("uphill start: the top-up goes no further than full service") { + // every step adds enough to go on, but never enough to hold the train + auto const result{run_top_up(0.0, 0.03)}; + CHECK(result.position == doctest::Approx(uphill_start::top_up_position)); + CHECK(result.steps == 11); + top_up state; + CHECK(brake_top_up(state, 0.0, grade, uphill_start::top_up_position, application, application) == top_up_action::none); +} + +TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { + top_up state; + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.25, application, application) == top_up_action::step); + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.5, application, application) == top_up_action::none); + CHECK(state.done); + // the brake gets stronger later all the same: the start has gone on without the top-up + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::none); + // a new start begins with a new top-up + state = {}; + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 0d80e105f..2deac6621 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3751,7 +3751,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart ) { + if( bUphillStart && ( false == bUphillRelease ) ) { // starting uphill the train brake holds the train until the power does break; } @@ -6549,24 +6549,35 @@ TController::determine_consist_state() { ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - // starting uphill the power is applied against the train brake on purpose, until the power holds the train - auto const heldforstart { bUphillStart }; - if (Ready) { + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + auto const wasready { Ready }; + if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - vehicle->Vel < 1.0 ? + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - // ready all the same only at a standstill with the power going on against the brake on purpose; - // in motion a braking force left anywhere in the train (a hand brake) stops it as before - Ready = heldforstart && ( vehicle->Vel < 1.0 ); + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); } + } + if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken @@ -6583,7 +6594,8 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -6679,6 +6691,10 @@ TController::determine_consist_state() { && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony Ready = true; //żeby uznać za odhamowany } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8717,6 +8733,12 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -8773,15 +8795,19 @@ void TController::control_uphill_start() { && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; false == uphill ) { - bUphillStart = false; + end_uphill_start(); return; } if( false == bUphillStart ) { if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; fUphillStartTime = ElapsedTime; } else { @@ -8790,31 +8816,86 @@ void TController::control_uphill_start() { } if( AccDesired <= EU07_AI_NOACCELERATION ) { // no longer to start: the standing rules take over - bUphillStart = false; + end_uphill_start(); return; } - if( velocity < -0.5 ) { - // rolling back all the same: the rules for a train slipping back take over and apply the brakes - bUphillStart = false; + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - auto tractiveforce { 0.0 }; + fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame - tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - auto const holdingforce { fMass * -fAccGravity }; - if( ( velocity > 1.0 ) - || ( tractiveforce > 1.1 * holdingforce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillStart = false; + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; } void TController::increase_tractive_force() { @@ -8888,10 +8969,17 @@ void TController::control_braking_force() { if( TestFlag( iDrivigFlags, movePress ) ) { return; } auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) ) { + && false == TestFlag(iDrivigFlags, movePress) + && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -8946,7 +9034,7 @@ void TController::control_braking_force() { else { // a stara wersja w miarę dobrze działa na składy wagonowe if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + || slippingbackuphill) && // also brake if uphill and slipping back (fBrakeTime < 0.0 // the size of the brake demand decides whether to skip the reaction time, so the brake-only part // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0794799dc..62b326696 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "utilities/translation.h" #include "application/driverhints.h" +#include "vehicle/uphillstart.h" #include "vehicle/blackbox.h" auto const EU07_AI_ACCELERATION = 0.05; @@ -27,6 +28,7 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back +auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; enum TOrders @@ -337,6 +339,8 @@ private: bool uphill_stop_hold() const; bool uphill_brake_committed( double const Velocity ) const; void control_uphill_start(); + void end_uphill_start(); + bool uphill_brake_top_up(); std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -441,6 +445,14 @@ private: int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does double fUphillStartTime = 0.0; // when the uphill start began + bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released + bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off + uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further + double fUphillReleaseTime = 0.0; // when the release began + double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] + double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp new file mode 100644 index 000000000..dd1895b11 --- /dev/null +++ b/vehicle/uphillstart.cpp @@ -0,0 +1,36 @@ +/* +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/uphillstart.h" + +namespace uphill_start { + +top_up_action brake_top_up( + top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, + double const Applicationtime) { + + if (State.done || (Brakeforce >= holding_force * Holdingforce) || (Brakeposition >= top_up_position)) { + return top_up_action::none; + } + // each step is given the full application time of the train brake, for the cylinders along the train to fill + if (Heldtime < Applicationtime) { + return top_up_action::wait; + } + if ((State.last_force >= 0.0) && (Brakeforce - State.last_force < top_up_gain * Holdingforce)) { + // the last step added next to nothing: the brake of this train can't hold it (brakes cut out, a load setting + // too low), and the start goes on without + State.done = true; + return top_up_action::none; + } + State.last_force = Brakeforce; + return top_up_action::step; +} + +} // namespace uphill_start diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h new file mode 100644 index 000000000..108662cbe --- /dev/null +++ b/vehicle/uphillstart.h @@ -0,0 +1,41 @@ +/* +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 + +// starting uphill (TController::control_uphill_start()), the AI's driver lets the locomotive brake off only once +// the brake of the rest of the train holds the train on its own: a train stopped on a light application stands on +// the locomotive brake too, and rolls back as soon as it is off. until then the train brake is applied further, a +// step at a time +namespace uphill_start { + +auto const holding_force{1.1}; // a force that holds a train uphill, as a multiple of the grade force +auto const top_up_position{4.0}; // full service: the furthest the train brake is applied to hold the train +// a step that adds less brake force than this, as a multiple of the grade force, is the last one +auto const top_up_gain{0.02}; + +// what has been done to apply the train brake further, in one start +struct top_up { + double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] + bool done{false}; // a step added next to nothing: no more of them in this start +}; + +enum class top_up_action { + none, // the brake holds the train, or can't be made to: the start goes on + wait, // the cylinders are still filling after the last step + step // apply the train brake one step further +}; + +// Brakeforce: the brake force of the unpowered vehicles [N]; Holdingforce: the grade force on the train [N]; +// Brakeposition: the train brake handle, as BrakeCtrlPosition; Heldtime: how long the handle has been where it +// is [s]; Applicationtime: the time the train brake takes to apply, for the cylinders along the train to fill [s] +top_up_action brake_top_up( + top_up &State, double Brakeforce, double Holdingforce, double Brakeposition, double Heldtime, double Applicationtime); + +} // namespace uphill_start From e0b2bdfb7f56faf2166e16d030ecef007be07a81 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:07:52 +0100 Subject: [PATCH 55/58] fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges (#444) * fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges Prepared from cold, the AI filled the brake pipe at once with the locomotive brake off: the distributors released while the auxiliary reservoirs were still empty, so the train had no air to brake with, and on a gradient it rolled as it released. The train counted as ready as soon as it was released. A train placed cold with its pipe below the lock of the FV4a driver's brake valve (2.75 bar) wasn't unlocked until the order to go, and went on what its reservoirs got meanwhile (TMS77185 in linia_107_objazdy: 40 minutes at 1.2-1.9 bar, the last wagon at 4.3 bar at the start). - Standing, PrepareEngine() applies the locomotive brake first, then fills the pipe. Where the locomotive brake alone doesn't hold the train (1.1 x the grade force), the train brake goes to the first service position instead, so the reservoirs charge with the train held. Multiple units with the electro-pneumatic brake are released as before. - Standing to charge, the AI unlocks the pipe as it does to go (the releaser, or the unlock button). A handle which has to be moved to unlock is left where the light application holds the train. - A train is ready only once the pipe and the auxiliary reservoir of every vehicle with a working brake are within 0.5 bar of the working pressure (4.5 of 5.0: the last wagon of a long train stays at about 4.6-4.7 from what leaks along the pipe), with the pipe fed at the head of the train. Brakes cut out don't count. - The locomotive brake comes off only once the train is charged, also against DecBrakeEIM(), which for a vehicle without the integrated handle releases it too; an uphill start begins only then. - A human driver gets the same wait as a hint: "Wait for the train brakes to charge" (driver_hint::waitbrakecharge), and the hint to release the brakes waits with it once the train brake is off (brake_charge::release_waits()). The train brake may still come off: released, it fills the pipe. - A charge that rises by less than 0.02 bar in 60 s lets the train go all the same, with a line in the log. The time counts only while there is air to charge with (the engine prepared, the main reservoir above what the pipe charges to, the pipe fed at the head): a train with its compressor not running yet or a locked pipe is waited out. Once let go, a train stays so until it is to stand again: otherwise the pipe refilling behind the release held it at a crawl (et22-1075 with 36 wagons, baltyk_interregio). - The check applies to the pneumatic brake only, to the first start of a train that hasn't run (above 1 km/h) since it was placed, and to a start with the pipe below 2.5 bar (near empty, after an emergency application). A start after an ordinary stop, a service stop (3.0-3.5 bar), a change of direction or a shunting move isn't held: waiting there only delayed the train, and the scenery set the routes of the others later. - The release of the train brake in PrepareEngine() had a stray semicolon after its condition; the condition applies again in motion. - Unit tests for the charge check (brake_charge::charged(), locomotive_brake_holds(), release_waits()). Run on all 174 shipped sceneries (20 minutes each, against master): no train stuck that moved on master, 466 timetable departures compared, 459 within 15 s, mean -1.2 s. Waits for the charge: median 4 s, 90% 39 s, longest 106 s (a heavy freight train charged from 2.2 bar). * test(ai): the brake charge test counts its looks in whole numbers, not in a floating-point time SonarCloud took the loop of the test of a train with nothing to charge with yet for a bug (cpp:S2193, a counter of type double). The same 120 looks, 5 s apart. * fix(ai): the light application that holds a charging train stays on, and an empty pipe is no charge Runs of a cold train on a gradient (P33000 at Lupkow in linia_107_objazdy, 13-16 per mille, with an SM42 and 32 wagons, 1556 t) showed three faults of the charged-brakes start: - The locomotive brake was taken to hold the train with the force of its brake blocks alone, 1031 kN for an ST43: several times what its wheels pass on to the rails. It is limited to a quarter of the locomotive's weight (brake_charge::adhesion), so a light locomotive with a heavy train gets the light application of the train brake. - That application was taken off again as soon as the order to go came, by the rule that puts the handle back to running with the main reservoir below 5 bar, and by DecBrake(). The train then stood on the locomotive brake that doesn't hold it, and moved as its wagons let go (to 0.3 km/h). It stays on until the train is charged (brake_charge::holds_application()). - With the train brake applied the train counted as charged to what the head of the pipe has, which is nothing with the pipe empty: charged at 0.02 bar the moment the brake was applied. The pipe at the head counts no lower than a full service application leaves (brake_charge::reference()). The SM42 with the 32 wagons now stands still while it charges and starts without rolling back, 2 min 30 s after it was prepared (4 min 40 s before, with a start that rolled back at 0.3 km/h). An ST43 with 33 wagons and a 754 with 8 coaches there are as before, their locomotive brake holds them. In eight of the sceneries run before (l053_poranek, calkowo_v2_cementa, calkowo_v2_ctl-wegiela, calkowo_v2_osoba_jar_poranek, calkowo_retro_zima, linia61_towarowy2, l053-sluzba-brutto-posp, baltyk_interregio) the 60 timetable departures compared are the same, within 15 s, mean 0.0 s. Unit tests for the two new decisions. * fix(ai): the locomotive brake counted of the occupied vehicle alone locomotive_brake_force() added the brake of every powered vehicle of the train. The locomotive brake handle acts on the occupied vehicle only (LocalBrakePosA is set on mvOccupied and passed to no other vehicle), so a second locomotive, in multiple control or hauled dead, made the brake count as holding a train it doesn't hold, and the train brake was released on a gradient with the leading locomotive alone holding. The estimate of one vehicle is brake_charge::locomotive_brake_force(), with a test. brakecharge.h named TController::control_brake_charge(), which doesn't exist: the logic is in determine_consist_state(). --- CMakeLists.txt | 1 + application/driverhints.cpp | 8 ++ application/driverhints_def.h | 1 + tests/unit/test_brake_charge.cpp | 169 ++++++++++++++++++++++++++++ vehicle/Driver.cpp | 183 +++++++++++++++++++++++++++++-- vehicle/Driver.h | 10 ++ vehicle/brakecharge.cpp | 65 +++++++++++ vehicle/brakecharge.h | 76 +++++++++++++ 8 files changed, 501 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_brake_charge.cpp create mode 100644 vehicle/brakecharge.cpp create mode 100644 vehicle/brakecharge.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 69dc5fbab..0d47ed907 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -558,6 +558,7 @@ set(CORE_SOURCES "vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/uphillstart.cpp" +"vehicle/brakecharge.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..3ab528f4f 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -762,6 +762,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } + case driver_hint::waitbrakecharge: { + // NOTE: this action doesn't have AI component: the ai waits through Ready and DecBrake() + hint( + Action, + [this](float const /*Parameter*/) { + return IsConsistCharged; } ); + break; + } case driver_hint::waitloadexchange: { // NOTE: this action doesn't have AI component hint( diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..b71b9b9a9 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -59,6 +59,7 @@ DRIVER_HINT_DEF(directionother, STRN("Switch reverser to opposite direction")) DRIVER_HINT_DEF(directionnone, STRN("Set reverser to neutral")) DRIVER_HINT_DEF(waitpressuretoolow, STRN("Wait for main reservoir to fill")) DRIVER_HINT_DEF(waitpantographpressuretoolow, STRN("Wait for sufficient air pressure in pantograph subsystem")) +DRIVER_HINT_DEF(waitbrakecharge, STRN("Wait for the train brakes to charge")) DRIVER_HINT_DEF(sandingon, STRN("Switch on sanding")) DRIVER_HINT_DEF(sandingoff, STRN("Switch off sanding")) DRIVER_HINT_DEF(consistdoorlockson, STRN("Switch on door locks")) diff --git a/tests/unit/test_brake_charge.cpp b/tests/unit/test_brake_charge.cpp new file mode 100644 index 000000000..238d0bef0 --- /dev/null +++ b/tests/unit/test_brake_charge.cpp @@ -0,0 +1,169 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakecharge.h" + +// a standing train starts only with its brake pipe and auxiliary reservoirs charged (TController, the consist check) + +using brake_charge::charged; +using brake_charge::state; + +TEST_CASE("brake charge: a train charged to within the margin may start") { + state s; + CHECK(charged(s, 5.0, 5.0, 0.0)); + s = {}; + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, 0.0)); + s = {}; + // the last wagon of a long train, for good below the working pressure from what leaks along the pipe + CHECK(charged(s, 4.62, 5.0, 0.0)); +} + +TEST_CASE("brake charge: a train prepared from cold waits while its pipe fills") { + state s; + // the pipe of the last wagon empty, then filling by 0.1 bar every 5 s + auto level{0.0}; + auto time{0.0}; + while (level < 5.0 - brake_charge::margin - 0.05) { + CHECK_FALSE(charged(s, level, 5.0, time)); + CHECK_FALSE(s.stalled); + level += 0.1; + time += 5.0; + } + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, time)); + CHECK(s.going); +} + +TEST_CASE("brake charge: a charge that stops rising lets the train go after the stall time") { + state s; + // a hose not connected: the last wagon stays at 3.2 bar + CHECK_FALSE(charged(s, 3.2, 5.0, 100.0)); + CHECK_FALSE(charged(s, 3.21, 5.0, 130.0)); // less than the gain that counts + CHECK_FALSE(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time - 0.1)); + CHECK(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time)); + CHECK(s.stalled); + // and stays let go + CHECK(charged(s, 3.2, 5.0, 300.0)); +} + +TEST_CASE("brake charge: a train let go stays let go while its charge rises again as it starts") { + // the train went on a stalled charge; starting, the brakes release and the pipe refills behind them + state s; + REQUIRE_FALSE(charged(s, 4.3, 5.0, 0.0)); + REQUIRE(charged(s, 4.3, 5.0, brake_charge::stall_time)); + CHECK(charged(s, 4.35, 5.0, brake_charge::stall_time + 1.0)); + CHECK(charged(s, 4.4, 5.0, brake_charge::stall_time + 2.0)); + SUBCASE("until the train is to stand again: the next start is checked anew") { + s.going = false; + CHECK_FALSE(charged(s, 4.42, 5.0, brake_charge::stall_time + 3.0)); + CHECK(charged(s, 4.6, 5.0, brake_charge::stall_time + 4.0)); + } +} + +TEST_CASE("brake charge: a train with nothing to charge with yet isn't let go for a stall") { + // prepared from cold: the pipe empty, the engine not started, no air in the main reservoir + state s; + // a look every 5 s for ten times the stall time + auto const looks{static_cast(10.0 * brake_charge::stall_time / 5.0)}; + for (auto i{0}; i < looks; ++i) { + CHECK_FALSE(charged(s, 0.0, 5.0, 5.0 * i, false)); + } + CHECK_FALSE(s.stalled); + CHECK_FALSE(s.going); + // the engine runs, the pipe fills + auto const start{10.0 * brake_charge::stall_time}; + CHECK_FALSE(charged(s, 0.0, 5.0, start, true)); + // the stall time counts from when there was air to charge with + CHECK_FALSE(charged(s, 0.0, 5.0, start + brake_charge::stall_time - 10.0, true)); + CHECK_FALSE(charged(s, 2.0, 5.0, start + brake_charge::stall_time + 10.0, true)); + CHECK(charged(s, 4.6, 5.0, start + brake_charge::stall_time + 60.0, true)); +} + +TEST_CASE("brake charge: a slow but steady charge isn't taken for a stall") { + state s; + auto time{0.0}; + auto level{2.0}; + // 0.03 bar every 50 s: above the gain within the stall time + for (auto i{0}; i < 20; ++i) { + CHECK_FALSE(charged(s, level, 5.0, time)); + level += 0.03; + time += 50.0; + } + CHECK_FALSE(s.stalled); +} + +TEST_CASE("brake charge: a lower working pressure (the reductor turned down) lowers the charge asked for") { + state s; + CHECK(charged(s, 4.35, 4.8, 0.0)); + s = {}; + CHECK_FALSE(charged(s, 4.25, 4.8, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds the train only with the margin over the grade force") { + using brake_charge::locomotive_brake_holds; + // the 752 with about 720 t: 17 kN on -2.4 per mille, 30 kN on -4.3, against about 100 kN of its brake + CHECK(locomotive_brake_holds(100000.0, 17000.0)); + CHECK(locomotive_brake_holds(100000.0, -30000.0)); + CHECK(locomotive_brake_holds(110001.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(100000.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(0.0, 1000.0)); + CHECK(locomotive_brake_holds(0.0, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds with no more than the wheels pass on to the rails") { + using brake_charge::locomotive_brake_force; + // an ST43 of 116 t: 1031 kN at the brake blocks, 0.25 of its weight on the rails + CHECK(locomotive_brake_force(1031000.0, 116000.0 * 9.81) == doctest::Approx(284490.0)); + // a weak brake stays what it is + CHECK(locomotive_brake_force(50000.0, 116000.0 * 9.81) == doctest::Approx(50000.0)); + CHECK(locomotive_brake_force(0.0, 116000.0 * 9.81) == doctest::Approx(0.0)); + CHECK(locomotive_brake_force(-1.0, 116000.0 * 9.81) == doctest::Approx(0.0)); +} + +TEST_CASE("brake charge: standing not charged, the release of the locomotive brake waits") { + using brake_charge::release_waits; + // the train brake already off: what is left on is the locomotive brake, which holds the train while it charges + CHECK(release_waits(false, true, false)); +} + +TEST_CASE("brake charge: the release doesn't wait once the train is charged, or once it moves") { + using brake_charge::release_waits; + CHECK_FALSE(release_waits(true, true, false)); + // in motion a release is braking control, not a start + CHECK_FALSE(release_waits(false, false, false)); + CHECK_FALSE(release_waits(true, false, false)); +} + +TEST_CASE("brake charge: the train brake may come off while the train charges") { + using brake_charge::release_waits; + // released, the train brake fills the pipe, which is what charges the train + CHECK_FALSE(release_waits(false, true, true)); +} + +TEST_CASE("brake charge: with the train brake applied the train charges to the head of the pipe, not to an empty one") { + using brake_charge::reference; + // released: the working pressure + CHECK(reference(4.7, 5.0, false) == doctest::Approx(5.0)); + // the first service position: what the head of the pipe has + CHECK(reference(4.65, 5.0, true) == doctest::Approx(4.65)); + // a pipe emptied, or just being filled: no lower than a full service application leaves, with the margin a train + // is charged within. an SM42 with 32 wagons at 0.02 bar counted as charged the moment its brake was applied + CHECK(reference(0.02, 5.0, true) == doctest::Approx(4.0)); + state s; + CHECK_FALSE(brake_charge::charged(s, 0.02, reference(0.02, 5.0, true), 0.0)); + // an overcharged pipe doesn't raise it + CHECK(reference(5.4, 5.0, true) == doctest::Approx(5.0)); +} + +TEST_CASE("brake charge: the light application that holds a charging train stays on when the order to go comes") { + using brake_charge::holds_application; + CHECK(holds_application(true, false, true, 1.0)); + CHECK(holds_application(true, false, true, 0.75)); + // charged, or moving: the start releases it + CHECK_FALSE(holds_application(true, true, true, 1.0)); + CHECK_FALSE(holds_application(true, false, false, 1.0)); + // a train the locomotive brake holds has no such application + CHECK_FALSE(holds_application(false, false, true, 1.0)); + // a stronger application comes off down to the first position; a released handle has nothing to hold + CHECK_FALSE(holds_application(true, false, true, 2.0)); + CHECK_FALSE(holds_application(true, false, true, 0.0)); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 2deac6621..57a8337ae 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3329,9 +3329,13 @@ bool TController::PrepareEngine() } } // set up train brake - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) { - if ( !mvOccupied->Handle->Time - || mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ); + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) + && ( ( false == mvOccupied->Handle->Time ) + || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -3760,6 +3764,13 @@ bool TController::DecBrake() { // any release now raises the pipe, and a long train releases more than the handle is moved back, too late // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it break; + } + if( brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + // the order to go came while the train still charges: released now, the wagons let go as their + // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive + // brake stays on with it + break; } if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); @@ -3769,10 +3780,16 @@ bool TController::DecBrake() { if (BrakeCtrlPosition < 0.74) /*mvOccupied->*/ BrakeLevelSet(gbh_RP); } - if( !OK ) { + // standing, the locomotive brake holds the train until its brakes are charged: off before, a train + // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off + // as well (the locomotive brake of a vehicle without the integrated handle) + auto const holdlocomotive { + ( false == IsConsistCharged ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = mvOccupied->DecLocalBrakeLevel(2); } - if( !OK ) { + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = DecBrakeEIM(); } /* @@ -6555,12 +6572,18 @@ TController::determine_consist_state() { auto released { true }; // the brakes are off, the hold of an uphill start not counted auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted auto momentum { 0.0 }; + auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) + && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + } auto const wasready { Ready }; if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać @@ -6695,6 +6718,69 @@ TController::determine_consist_state() { IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); + // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to + // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light + // application while charging) they charge to what the head of the pipe has. + // only the start the charge is in question for: the first after the train was prepared standing, or one with the + // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the + // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and + // those behind it. + // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before + if( mvOccupied->Vel > 1.0 ) { + // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its + // every start the first, waiting for each cut of wagons placed cold to charge + bBrakeChargeStart = false; + bBrakeChargeHold = false; + bHasRun = true; + } + auto const chargeable { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( chargelevel < std::numeric_limits::max() ) }; + if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { + bBrakeChargeStart = true; + } + if( chargeable && bBrakeChargeStart ) { + if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { + // to stand: the next start is checked anew + BrakeCharge.going = false; + } + auto const trainbrakeapplied { + AIControllFlag ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's + // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, + // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held + // by its brakes as it can't release them either + auto const supplied { + iEngineActive + && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) + && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + auto const wasstalled { BrakeCharge.stalled }; + IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); + if( BrakeCharge.stalled && ( false == wasstalled ) ) { + WriteLog( + "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); + } + if( false == IsConsistCharged ) { + // a human driver is told to wait as the ai does, the locomotive brake applied + cue_action( driver_hint::waitbrakecharge ); + } + } + else { + IsConsistCharged = true; + BrakeCharge = {}; + } + if( AIControllFlag + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8804,7 +8890,8 @@ void TController::control_uphill_start() { && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train + && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train + && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air bUphillStart = true; bUphillRelease = false; UphillTopUp = {}; @@ -8898,6 +8985,55 @@ void TController::end_uphill_start() { bUphillBrakeTopUp = false; } +// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe +// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, +// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake +// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train +// is charged and to start (DecBrake()) +void TController::secure_standing_train() { + + if( BrakeSystem != TBrakeSystem::Pneumatic ) { + // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive + // brake off again when the unit starts + cue_action( driver_hint::trainbrakerelease ); + return; + } + // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again + // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before + if( false == bHasRun ) { + bBrakeChargeStart = true; + } + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + cue_action( driver_hint::independentbrakeapply ); + } + if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { + // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the + // distributors keep a light application. a stronger application already there is left as it is, but not + // the emergency one or an empty pipe's, which don't charge + if( AIControllFlag + && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { + BrakeLevelSet( 1.0 ); + } + bBrakeChargeHold = true; + return; + } + bBrakeChargeHold = false; + cue_action( driver_hint::trainbrakerelease ); +} + +// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on +// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead +double TController::locomotive_brake_force() const { + + if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), + mvOccupied->TotalMassxg ); +} + void TController::increase_tractive_force() { if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać @@ -9060,7 +9196,14 @@ void TController::control_braking_force() { } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 + // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the + // waitbrakecharge hint; the ai is held back in DecBrake() + && ( AIControllFlag + || ( false == brake_charge::release_waits( + IsConsistCharged, + mvOccupied->Vel < EU07_AI_NOMOVEMENT, + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca @@ -9136,7 +9279,16 @@ void TController::control_releaser() { auto actuate { false }; auto isbrakehandleinrightposition { true }; - if( AccDesired > EU07_AI_NOACCELERATION ) { + // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's + // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only + // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. + // a handle which has to be moved to unlock is left where it holds the train with the train brake + auto const chargesstanding { + bBrakeChargeStart + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ) }; + + if( ( AccDesired > EU07_AI_NOACCELERATION ) || chargesstanding ) { // fill up brake pipe if needed if( mvOccupied->PipePress < 3.0 ) { actuate = true; @@ -9146,6 +9298,8 @@ void TController::control_releaser() { isbrakehandleinrightposition &= BrakeCtrlPosition == mvOccupied->HandleUnlock; } } + } + if( AccDesired > EU07_AI_NOACCELERATION ) { // wyluzuj lokomotywę, to szybciej ruszymy // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it @@ -9186,7 +9340,9 @@ void TController::control_releaser() { void TController::control_main_pipe() { // unlocking main pipe - if( AccDesired > -0.03 + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) && true == mvOccupied->LockPipe ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } @@ -9218,9 +9374,12 @@ void TController::control_main_pipe() { update_brake_charging(); - if( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) { + if( ( mvOccupied->Compressor < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + // the light application a charging train stands on stays, as in DecBrake() + && ( false == brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { cue_action( driver_hint::trainbrakerelease ); } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 62b326696..5ad92c348 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/uphillstart.h" +#include "vehicle/brakecharge.h" #include "vehicle/blackbox.h" auto const EU07_AI_ACCELERATION = 0.05; @@ -341,6 +342,8 @@ private: void control_uphill_start(); void end_uphill_start(); bool uphill_brake_top_up(); + void secure_standing_train(); + double locomotive_brake_force() const; std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -452,6 +455,13 @@ private: double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + bool IsConsistCharged = true; // standing, the brake pipe and the auxiliary reservoirs are charged to start (or stopped charging) + brake_charge::state BrakeCharge; // standing, how the charge of the brakes rose + // the next start waits for the brakes to charge: the first after the train was prepared standing, or one with the + // pipe near empty. cleared once the train runs + bool bBrakeChargeStart = false; + bool bHasRun = false; // the train has moved (above 1 km/h) since it was placed + bool bBrakeChargeHold = false; // charging, the train stands on a light application of the train brake as well double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) diff --git a/vehicle/brakecharge.cpp b/vehicle/brakecharge.cpp new file mode 100644 index 000000000..18668987d --- /dev/null +++ b/vehicle/brakecharge.cpp @@ -0,0 +1,65 @@ +/* +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/brakecharge.h" + +namespace brake_charge { + +bool charged(state &State, double const Level, double const Reference, double const Time, bool const Supplied) { + + if (State.going) { + return true; + } + if (Level >= Reference - margin) { + State = {}; + State.going = true; + return true; + } + if ((State.best < 0.0) || (Level > State.best + stall_gain) || (false == Supplied)) { + // still charging, or nothing to charge with yet: the time for a stall counts from when there is + State.best = Level; + State.best_time = Time; + State.stalled = false; + return false; + } + State.stalled = (Time - State.best_time >= stall_time); + State.going = State.stalled; + return State.stalled; +} + +double locomotive_brake_force(double const Blockforce, double const Weight) { + + return std::max(0.0, std::min(Blockforce, Weight * adhesion)); +} + +bool locomotive_brake_holds(double const Locomotivebrakeforce, double const Gradeforce) { + + return Locomotivebrakeforce >= holding_force * std::abs(Gradeforce); +} + +double reference(double const Headpipe, double const Working, bool const Trainbrakeapplied) { + + if (false == Trainbrakeapplied) { + return Working; + } + return std::clamp(Headpipe, Working - service_drop + margin, Working); +} + +bool holds_application(bool const Hold, bool const Charged, bool const Standing, double const Position) { + + return Hold && (false == Charged) && Standing && (Position > 0.0) && (Position <= 1.0); +} + +bool release_waits(bool const Charged, bool const Standing, bool const Trainbrakeapplied) { + + return (false == Charged) && Standing && (false == Trainbrakeapplied); +} + +} // namespace brake_charge diff --git a/vehicle/brakecharge.h b/vehicle/brakecharge.h new file mode 100644 index 000000000..f283dade9 --- /dev/null +++ b/vehicle/brakecharge.h @@ -0,0 +1,76 @@ +/* +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 + +// a standing train starts only with its brakes charged, as a driver checks before setting off: the brake pipe and the +// auxiliary reservoir of every vehicle with a working brake close to the working pressure. released alone isn't enough: +// a train prepared from cold is released at once, its pipe still filling, and has no air to brake with +// (TController::PrepareEngine(), TController::determine_consist_state()) +namespace brake_charge { + +// [bar] below the working pressure the pipe and the reservoir count as charged: 4.5 of 5.0. the last wagon of a long +// train stays at about 4.6-4.7 for good, from what leaks along the pipe +auto const margin{0.5}; +// below this the pipe counts as near empty (after an emergency application): the next start waits for the charge +// whatever came before. well below what a service application leaves: the AI stops at a station with the handle past +// the full service position, the pipe at 3.0-3.5 bar, and wagons coupled from cold come with about 3 bar. waiting there +// only delays the train, and the scenery sets the routes of the others later (calkowo_v2_osoba_jar_poranek, l053_poranek) +auto const empty_level{2.5}; // [bar] +// a charge that rises by less than this in stall_time has stopped (a leak, a hose not connected, a pipe cock shut): the +// train goes all the same, rather than stand for good +auto const stall_gain{0.02}; // [bar] +auto const stall_time{60.0}; // [s] +// standing, the locomotive brake alone has to give this multiple of the grade force to hold the train while it charges +auto const holding_force{1.1}; +// the share of a locomotive's weight its brake can hold the train with at most: what the wheels pass on to the rails, +// taken low (a wet rail). the force of the brake blocks alone is several times that +auto const adhesion{0.25}; +// [bar] how far below the working pressure the pipe is at a full service application: with the train brake applied the +// train charges to what the head of the pipe has, but a pipe below this (emptied, or just being filled) is no charge +auto const service_drop{1.5}; + +struct state { + double best{-1.0}; // the highest charge seen while it still rose [bar], -1 before the first look + double best_time{0.0}; // when it was seen [s] + bool stalled{false}; // the charge stopped rising short of charged + // the train was let go: it stays so until the driver clears this, when the train is to stand again. otherwise a + // charge rising again as the train starts (the pipe refilling behind the release) would stop it at a crawl + bool going{false}; +}; + +// Level: the lowest pressure of the brake pipes and auxiliary reservoirs among the vehicles with a working brake [bar]; +// Reference: the pressure they charge to [bar]; Time: now [s]; Supplied: there is air to charge with (the engine +// prepared, the main reservoir above the reference): without it the charge can't rise, and that isn't a stall. +// true once the train may start, and from then on +bool charged(state &State, double Level, double Reference, double Time, bool Supplied = true); + +// what the locomotive brake of a vehicle holds with at full application [N]: the force of its brake blocks (Blockforce), +// but no more than its wheels pass on to the rails, the adhesion share of its Weight [N] +double locomotive_brake_force(double Blockforce, double Weight); + +// whether the locomotive brake, Locomotivebrakeforce at full application [N], holds the standing train against its +// Gradeforce [N] on its own; when it doesn't, the train brake is applied lightly while the train charges +bool locomotive_brake_holds(double Locomotivebrakeforce, double Gradeforce); + +// the pressure the train is to be charged to [bar]: the working pressure with the train brake released; with it applied +// what the head of the pipe has (Headpipe), as the reservoirs get no more, though no less than a full service +// application leaves, or a pipe emptied by an emergency application would count as charged at once +double reference(double Headpipe, double Working, bool Trainbrakeapplied); + +// whether a light application of the train brake (Position, up to the first service position) stays on: the train +// stands on it while it charges (Hold), the locomotive brake not holding it alone +bool holds_application(bool Hold, bool Charged, bool Standing, double Position); + +// whether a release of the brakes waits for the charge: standing, a train not charged yet keeps its locomotive brake +// on. the train brake (Trainbrakeapplied) may come off all the same: released, it fills the pipe, which is what charges +// the train. the hint a human driver gets to release the brakes waits with it (driver_hint::waitbrakecharge instead) +bool release_waits(bool Charged, bool Standing, bool Trainbrakeapplied); + +} // namespace brake_charge From 767bcb4682d1ad3f121e0054927d9e97513ebbf4 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:28:02 +0100 Subject: [PATCH 56/58] fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again (#415) * fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again The colours of the sky dome were made for the full renderer, which tonemaps them and draws to an sRGB framebuffer: the sRGB matrix, the gamma put on the brightness, a lighter gradient and a band of light at the horizon (40c21bd4, b46c8c76, 8df81eb4), and the fog no longer dimmed by the diffuse level (#229). The legacy and simple renderers draw these colours as they are, and the ambient light and the fog are taken from them, so all three differed from 26.05 there. With Global.LegacyRenderer the dome is computed as in 26.05: the Adobe RGB matrix, the brightness knee at 0.85, the sky tone saturated as the colour, the plain gradient and the gamma of 0.45 by day at the end; the fog is lit by the key light at its diffuse level. The full renderer is unchanged. The turbidity under overcast is a separate fix (#410). * fix(test): a test run takes the legacy and the simple renderer flag off with the renderer From the review of #415: apply_test_mode_settings() sets the null renderer but left Global.LegacyRenderer and Global.BasicRenderer as the gfxrenderer line of eu07.ini made them. With this PR the legacy flag picks the colours of the sky dome, and their average is the light level the scenery lamps, the AI's compartment lights and Python's light_level go by. The same --test run on a machine with "gfxrenderer legacy" and on one with the default renderer computed different skies and could switch those lights at other times. A test run now always takes the sky of the full renderer, as on master. The context of a test run doesn't depend on the flag (it asks for none in particular), and its multisampling is off, so nothing else changes. --------- Co-authored-by: maj00r --- environment/skydome.cpp | 56 +++++++++++++++++++++++----- simulation/simulationenvironment.cpp | 4 +- simulation/simulationtest.cpp | 4 ++ 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/environment/skydome.cpp b/environment/skydome.cpp index 654b3a345..2a12695d9 100644 --- a/environment/skydome.cpp +++ b/environment/skydome.cpp @@ -5,6 +5,27 @@ #include "simulation/simulationenvironment.h" #include "utilities/Globals.h" +namespace { + +// XYZ to Adobe RGB, as the sky was converted up to 26.05. the legacy renderer still gets its sky this way: +// it draws the colours of the dome as they are, with no tonemapping of its own +glm::vec3 +xyz_to_adobe_rgb( glm::vec3 const &XYZ ) { + + // M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html + std::array const mi{ + glm::vec3{ 2.041369f, -0.969266f, 0.0134474f }, + glm::vec3{ -0.5649464f, 1.8760108f, -0.1183897f }, + glm::vec3{ -0.3446944f, 0.041556f, 1.0154096f } }; + + return glm::vec3{ + XYZ.x * mi[ 0 ].x + XYZ.y * mi[ 1 ].x + XYZ.z * mi[ 2 ].x, + XYZ.x * mi[ 0 ].y + XYZ.y * mi[ 1 ].y + XYZ.z * mi[ 2 ].y, + XYZ.x * mi[ 0 ].z + XYZ.y * mi[ 1 ].z + XYZ.z * mi[ 2 ].z }; +} + +} // namespace + // sky gradient based on "A practical analytic model for daylight" // by A. J. Preetham Peter Shirley Brian Smits (University of Utah) @@ -185,6 +206,11 @@ void CSkyDome::RebuildColors() { float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; auto gammacorrection = glm::mix( glm::vec3( 1.0f ), glm::vec3( 0.45f ), twilightfactor ); + // the legacy renderer has no tonemapping and no srgb framebuffer, so its sky stays as 26.05 made it: + // display-encoded by day (gamma 0.45), with the brightness knee and the plain gradient, and no horizon band. + // the averages taken from these colours give it the ambient light and the fog of 26.05 too + bool const legacy { Global.LegacyRenderer }; + auto const legacygammacorrection = glm::mix( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); // get zenith luminance auto const chi = static_cast(( 4.0f / 9.0f - m_turbidity / 120.0f ) * ( M_PI - 2.0f * m_thetasun )); @@ -253,7 +279,7 @@ void CSkyDome::RebuildColors() { float const Z = (1.0f - x - y) / y * Y; colorconverter = glm::vec3( X, Y, Z ); - color = colors::XYZtoRGB( colorconverter ); + color = legacy ? xyz_to_adobe_rgb( colorconverter ) : colors::XYZtoRGB( colorconverter ); colorconverter = colors::RGBtoHSV(color); if ( m_linearexpcontrol ) { @@ -264,7 +290,12 @@ void CSkyDome::RebuildColors() { colorconverter.z = 1.0f - std::exp( -m_expfactor * colorconverter.z ); } - colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + if( false == legacy ) { + colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + } + else if( colorconverter.z > 0.85f ) { + colorconverter.z = 0.85f + ( colorconverter.z - 0.85f ) * 0.35f; + } colorconverter.y = std::clamp( colorconverter.y * Global.m_skysaturationcorrection, 0.0f, 1.0f ); // desaturate sky colour, based on overcast level @@ -281,7 +312,7 @@ void CSkyDome::RebuildColors() { // this height-based factor is reduced the farther the sun is up in the sky float const shiftfactor = std::clamp( std::lerp(heightbasedphase, sunbasedphase, sunbasedphase), 0.0f, 1.0f ); // h = 210 makes for 'typical' sky tone - glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, 0.5f, colorconverter.z ) ); + glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, legacy ? colorconverter.y : 0.5f, colorconverter.z ) ); color = colors::HSVtoRGB( colorconverter ); color = glm::mix( color, skytonecolor, shiftfactor * Global.m_skyhuecorrection ); @@ -296,14 +327,21 @@ void CSkyDome::RebuildColors() { color.x = 0.20f * color.z; color.y = 0.65f * color.z; } - // simple gradient, darkening towards the top - color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); + if( legacy ) { + // simple gradient, darkening towards the top, then the gamma correction + color *= std::clamp( 1.0f - vertex.y, 0.f, 1.f ); + color = glm::pow( glm::max( color, glm::vec3( 0.f ) ), legacygammacorrection ); + } + else { + // simple gradient, darkening towards the top + color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); - float const horizonboost = 1.5f + m_overcast; - float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation - float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); + float const horizonboost = 1.5f + m_overcast; + float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation + float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); - color *= std::lerp( 1.0, horizonboost, horizonband ); + color *= std::lerp( 1.0, horizonboost, horizonband ); + } //color *= ( 0.25f - vertex.y ); m_colours[ i ] = color; diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 4e8c0e5f7..57c1074a7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -190,7 +190,9 @@ world_environment::update() { // update the fog. setting it to match the average colour of the sky dome is cheap // but quite effective way to make the distant items blend with background better - Global.FogColor = m_skydome.GetAverageHorizonColor() * keylightcolor * + // the legacy renderer keeps the fog of 26.05, lit by the key light at its diffuse level + glm::vec3 const foglightcolor { Global.LegacyRenderer ? keylightcolor * diffuselevel : keylightcolor }; + Global.FogColor = m_skydome.GetAverageHorizonColor() * foglightcolor * std::clamp((float)Global.fLuminance, 0.f, 1.f); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index d32fd0e72..5fb80adae 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -62,6 +62,10 @@ void apply_test_mode_settings() Global.local_start_vehicle = "ghostview"; Global.GfxRenderer = "null"; Global.NvRenderer = false; + // the flags of the gfxrenderer line read from the settings go with it: the legacy one picks the colours of the sky, + // and with them the light level the lamps and the AI go by, so a test run would depend on the renderer of the ini + Global.LegacyRenderer = false; + Global.BasicRenderer = false; Global.bSoundEnabled = false; Global.python_enabled = false; Global.bInactivePause = false; From 827db5443087d7647c886530eea82e9a39164f6c Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:28:54 +0100 Subject: [PATCH 57/58] fix(python): the files a screen opens itself are found on Linux when named in another case (#449) #362 made the simulator find the data named in another case of its letters, through FileOnDisk(), the script of a screen included. What the script opens itself goes past it: Image.open(), ImageFont.truetype(), open() and the openimage() of the screens go straight to the system. The data is made on Windows, so on Linux a screen that asks for "WS_on.png" where the disk has "ws_on.png" doesn't start at all, e.g. the left screens of the EN57AL/AKM (WS_gotowosc.png), EN57AKL and EN71AKS (WN_off.png, M1M2_on.png and more). abstractscreenrenderer.py, run in __main__ before any screen, now finds those files as FileCased() does: the name given when it's on the disk, otherwise the one differing from it only in case, of the file or of its folders, a folder listed again for a name missing at most once a second. builtins.open() (which Image.open() goes through) and ImageFont.truetype() take the name so found, and openimage() looks for it. A file not there yet goes into its folder as named on the disk, so a screen writing its state for the first time doesn't make a second folder. A name with no such file is passed on as given, so a file missing fails as before. On Windows, which finds the names in any case itself, nothing is wrapped and nothing changes. No change to the game data is needed. Checked on a case-sensitive folder (a Windows folder with the case-sensitive attribute) with the scripts as they are in the data: with the file of master the EN57AL, EN57AKL and EN71AKS screens fail to start, with this one they start and render; plus the cases of the lookup (folders, ./, .., backslashes, a new file, a missing one, the module run twice, a screen's global named like the module's own). Co-authored-by: Claude Opus 5.5 --- .../python/local/abstractscreenrenderer.py | 69 ++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/staticFiles/python/local/abstractscreenrenderer.py b/staticFiles/python/local/abstractscreenrenderer.py index 3ebf20813..59341c045 100644 --- a/staticFiles/python/local/abstractscreenrenderer.py +++ b/staticFiles/python/local/abstractscreenrenderer.py @@ -1,6 +1,73 @@ from PIL import Image, ImageDraw, ImageFont from math import ceil, floor, cos, sin, radians +import builtins import os +import sys +import time + +# Linux tells the case of the letters in a file name apart, Windows doesn't, and the data is made on Windows: a screen asks for +# "WS_on.png" where the disk has "ws_on.png", or names a folder in another case. The simulator opens such files of its own through +# FileOnDisk(); the files a screen opens itself (images, fonts, text) are found here the same way. The name given when it's on the +# disk, otherwise the one differing from it only in case, of the file or of its folders. On Windows nothing changes. +_case_sensitive = not sys.platform.startswith('win') +_cased_listings = {} # folder -> (when listed, {name in lower case: name on the disk}) + +def _cased_name(folder, name): + """the name in the folder differing from the one given only in case, as on the disk; None when there's none""" + listed = _cased_listings.get(folder) + # a name missing gets the folder listed again, at most once a second, as FileCased() does + if listed is None or (name.lower() not in listed[1] and time.monotonic() - listed[0] >= 1.0): + names = {} + try: + for entry in os.listdir(folder or '.'): + names.setdefault(entry.lower(), entry) + except OSError: + pass + listed = (time.monotonic(), names) + _cased_listings[folder] = listed + return listed[1].get(name.lower()) + +def file_on_disk(path): + """the file to open: as it's named on the disk, the path given when there's none (and on Windows, which finds it itself)""" + if not _case_sensitive or not isinstance(path, str) or os.path.exists(path): + return path + text = path.replace('\\', '/') + parts = [part for part in text.split('/') if part] + cased = '/' if text.startswith('/') else '' + for index, part in enumerate(parts): + last = index == len(parts) - 1 + found = part + if part not in ('.', '..') and not os.path.exists(cased + part): + found = _cased_name(cased, part) + if found is None: + if not last: + return path + # a file not there yet goes into its folder as named on the disk: one written for the first time. The folder + # gets listed anew next time, the file being there by then + _cased_listings.pop(cased, None) + return cased + part + cased += found if last else found + '/' + return cased + +def _open_files_on_disk(): + # Image.open() opens the file through builtins.open(); the fonts are opened by FreeType, from the name. What the wrappers + # call is held here, not looked up in __main__, which the screens share and could name the same + on_disk = file_on_disk + open_given = builtins.open + truetype_given = ImageFont.truetype + + def open_on_disk(file, *args, **kwargs): + return open_given(on_disk(file), *args, **kwargs) + + def truetype_on_disk(font=None, *args, **kwargs): + return truetype_given(on_disk(font), *args, **kwargs) + + open_on_disk.file_on_disk = True + builtins.open = open_on_disk + ImageFont.truetype = truetype_on_disk + +if _case_sensitive and not getattr(builtins.open, 'file_on_disk', False): + _open_files_on_disk() # Pillow 10 removed ImageFont.getsize(), ImageDraw.textsize() and Image.ANTIALIAS, which the screen scripts use; for # Python 3.14 only a newer Pillow is available, so they are put back, on top of getbbox() / textbbox() and LANCZOS @@ -30,7 +97,7 @@ class abstractscreenrenderer(): def openimage(self, name): exts = [ ".png", ".tga", ".dds" ] for e in exts: - path = name + e + path = file_on_disk(name + e) if os.path.isfile(path): if e == ".dds": return Image.open(path).transpose(Image.FLIP_TOP_BOTTOM) From 571487612be73b69effc5433f70bbab2a55aea0d Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:44:46 +0100 Subject: [PATCH 58/58] fix(render): old assets drawn as 26.05 drew them; the headlight beam spread sideways (#481) * fix(render): old assets drawn as 26.05 drew them: metal, sun highlight, tonemapping, sun scale, diffuse colour The shader changes since 26.05.2 were made for PBR-authored assets; the assets in the game data were tuned for 26.05, and none of them is authored for the new combine. - Metal keeps its diffuse term as far as its reflection mask is low (metal_diffuse_loss = metalic * reflectivity). Assets marking metal in the specgloss with a low mask went almost black (the gold EN63A-031); a full mask is drawn as before. - The direct sun highlight is tinted by the albedo again, for dielectrics too. Old assets tuned param_specular / specgloss R with that multiply; untinted, dark glossy plastic broke into white glints along edges (Impuls fronts) and speckles on cab desks (SA132). - ACES instead of AgX: AgX with its look crushed the dark end, a night scene lost half its brightness and the ground beside the track went black. - SUN_DIFFUSE_SCALE 2.5 again (1.5 dimmed the moon at night as well). - The Diffuse colour of submodels and shapes scales the light as it is, as in 26.05, not raised to 2.2: that took a quarter off the default 0.8 of every scenery shape and more off the ~64 000 textured submodels with a darker Diffuse. Checked on screenshots of 10 vehicles by day (Ultra preset) and from cabs at night against the 26.05.2 shaders on the same executable. No game data changes. * feat(render): the headlight beam spread sideways, gfx.headlights.beamwidth (default 1.7) The projected beam texture lit the track and the ballast, and the ground beside them only with its dark edge (24-45 against 116 on the ballast close ahead, nearly 0 further on), so at night only the ballast showed. The beam is spread sideways around its middle by gfx.headlights.beamwidth: at 1.7 the ground gets most of the light of the ballast, the brightness along the track stays as it was. 1 draws the narrow beam of 26.05; range 1-4. The value reaches the shaders as HEADLIGHT_BEAM_WIDTH, written with the classic locale so that a decimal comma can't break the glsl; the shader validator compiles them with and without the spread. The key is written to the log with the other settings. * fix(render): the sunless specgloss shader combines metal as apply_lights does * fix(render): an untextured submodel takes its linearised colour as the texture again, as 26.05 did mat_colored.frag gave apply_lights() a white base, so the albedo of a Map: none submodel was its diffuse colour c, where 26.05.2 drew c^2.2 * c. A dark grey came out tens of times lighter: on the road vehicles of pctga the tyres (25-40 grey) 60-165x, the glass 23x, whole untextured cars (a4, golf, passat, ka, arosa) 1.5-3x. With the linearised colour as the texture a grey matches 26.05 in the ambient and the sun; a saturated colour is up to a third darker in the sun, as 26.05 scaled the sun by the value of the colour, not by the colour. * fix(render): the sun highlight is tinted by the texture alone, as 26.05 drew it --- ci_shadervalidator/Globals.h | 1 + ci_shadervalidator/main.cpp | 2 + gl/glsl_common.cpp | 18 +++++++++ shaders/light_common.glsl | 45 ++++++++++++++------- shaders/mat_colored.frag | 8 ++-- shaders/mat_sunlessnormalmap_specgloss.frag | 16 +++++--- shaders/tonemapping.glsl | 7 ++-- utilities/Globals.cpp | 7 ++++ utilities/Globals.h | 3 ++ 9 files changed, 81 insertions(+), 26 deletions(-) diff --git a/ci_shadervalidator/Globals.h b/ci_shadervalidator/Globals.h index e8f548dc3..943ff0adc 100644 --- a/ci_shadervalidator/Globals.h +++ b/ci_shadervalidator/Globals.h @@ -9,6 +9,7 @@ struct _global bool gfx_shadergamma; bool gfx_usegles; int iMultisampling; + float gfx_headlights_beamwidth; }; extern _global Global; diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 65ad54b2a..d11a013bf 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -48,6 +48,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_shadergamma = true; // the default of the simulator, which compiles the alpha to coverage branches of the shaders Global.iMultisampling = 2; + Global.gfx_headlights_beamwidth = 2.f; if (!check_shader(filename)) suc = false; @@ -59,6 +60,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_extraeffects = false; Global.gfx_shadergamma = false; Global.iMultisampling = 0; + Global.gfx_headlights_beamwidth = 1.f; if (!check_shader(filename)) suc = false; diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index e621fdc6b..9c3cfcb1f 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -1,6 +1,23 @@ #include "stdafx.h" #include "glsl_common.h" +#include +#include + +namespace +{ +// a float the way glsl reads it, whatever the locale of the program +std::string glsl_float(float const Value) +{ + std::ostringstream text; + text.imbue(std::locale::classic()); + text.setf(std::ios::fixed); + text.precision(3); + text << Value; + return text.str(); +} +} // namespace + std::string gl::glsl_common; void gl::glsl_common_setup() @@ -12,6 +29,7 @@ void gl::glsl_common_setup() "#define POSTFX_ENABLED " + std::to_string((int)!Global.gfx_skippipeline) + "\n" + "#define EXTRAEFFECTS_ENABLED " + std::to_string((int)Global.gfx_extraeffects) + "\n" + "#define ALPHA_TO_COVERAGE_ENABLED " + std::to_string((int)(Global.iMultisampling > 0)) + "\n" + + "#define HEADLIGHT_BEAM_WIDTH " + glsl_float(Global.gfx_headlights_beamwidth) + "\n" + "#define MAX_LIGHTS " + std::to_string(MAX_LIGHTS) + "U\n" + "#define MAX_CASCADES " + std::to_string(MAX_CASCADES) + "U\n" + "#define MAX_PARAMS " + std::to_string(MAX_PARAMS) + "U\n" + diff --git a/shaders/light_common.glsl b/shaders/light_common.glsl index 6261a090d..ddc7c39d3 100644 --- a/shaders/light_common.glsl +++ b/shaders/light_common.glsl @@ -33,7 +33,7 @@ in vec4 UserData; // lit and shaded faces of the same surface). // --------------------------------------------------------------------- const float AMBIENT_SCALE = 0.65; -const float SUN_DIFFUSE_SCALE = 1.5; +const float SUN_DIFFUSE_SCALE = 2.5; // 26.05; at 1.5 the moon left the night black around the headlights const float SUN_NDOTL_SHARPNESS = 1.25; float length2(vec3 v) @@ -242,7 +242,13 @@ vec2 calc_headlights(light_s light, vec3 fragnormal) float distance = length(light.pos - f_pos.xyz); float atten = 1.0f / (1.0f + light.linear * distance + light.quadratic * (distance * distance)); atten *= mix(1.0, 0.0, clamp((coords.z - 0.998) * 500.0, 0.0, 1.0)); - vec3 lights = textureProj(headlightmap, headlightpos).rgb * light.headlight_weights.rgb; + // gfx.headlights.beamwidth spreads the beam sideways around its middle (0.5 of the projected x), so the + // ground beside the track gets the light of the ballast; the brightness along the track stays as it was + vec4 beampos = headlightpos; +#ifdef HEADLIGHT_BEAM_WIDTH + beampos.x = 0.5 * beampos.w + (beampos.x - 0.5 * beampos.w) / HEADLIGHT_BEAM_WIDTH; +#endif + vec3 lights = textureProj(headlightmap, beampos).rgb * light.headlight_weights.rgb; float lightintensity = max(max(lights.r, lights.g), lights.b); return part * atten * lightintensity; } @@ -279,7 +285,9 @@ vec3 EnvBRDFApprox(vec3 F0, float roughness, float NoV) // param[1].x its intensity (HSV value unless a material overrides it). vec3 material_diffuse() { - vec3 diffusecolor = pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)); + // the colour as it is, as 26.05 scaled the light by it; linearised (^2.2) it took a quarter off the default + // 0.8 of every scenery shape and more off darker submodels, and the night went black + vec3 diffusecolor = max(param[0].rgb, vec3(0.0)); float value = max(param[0].r, max(param[0].g, param[0].b)); return (value > 0.0 ? diffusecolor * (param[1].x / value) : vec3(0.0)); } @@ -288,6 +296,8 @@ vec3 material_diffuse() // do magic here vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { + // the sun highlight is tinted by the texture alone, as 26.05 drew it, not by the diffuse colour too + vec3 highlight_tint = texturecolor; // Diffuse colour is applied once, to the albedo; the light terms below are not scaled by it again texturecolor *= material_diffuse(); float weathered = (param[3].w > 0.0 ? clamp(param[3].w * UserData.x, 0.0, 1.0) : 0.0); @@ -313,6 +323,10 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place. + // Assets made before the metal/rough combine mark metal in the specgloss but keep a low mask, and without + // this their metal parts went almost black; a metal with the full mask is drawn as before. + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -333,9 +347,9 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - // Metals carry no diffuse term; env reflection is gated by the env BRDF + // Metals carry no diffuse term where they reflect; env reflection is gated by the env BRDF // (F0-tinted, roughness-attenuated) so matte surfaces barely reflect. - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -375,16 +389,19 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 env_reflection = envcolor * env_spec * reflectivity * (1.0 - shadow1 * 0.5); // --- Physically-based metal/rough combine (Substance 3D Painter parity) --- - // Dielectrics: keep the full diffuse albedo; the direct sun highlight stays - // light-coloured because dielectric F0 is achromatic (~0.04) and - // must NOT be tinted by the base colour. - // Metals: drop the diffuse term entirely and tint the direct highlight - // with the albedo (metal F0 == base colour). + // Dielectrics: keep the full diffuse albedo; the direct sun highlight is tinted + // by the albedo, as 26.05 drew it. The specular strength of the + // assets (param_specular, the specgloss R) was tuned with that + // multiply; an untinted highlight on dark glossy plastic of an old + // asset turned into white glints along edges and speckles on cab + // desks. + // Metals: drop the diffuse term where the reflection mask is full (see + // metal_diffuse_loss) and tint the direct highlight with the + // albedo (metal F0 == base colour). // The highlight *strength* (specularamount) is deliberately left untouched so - // existing material tuning is preserved — only the colour/energy split that - // was previously inverted gets corrected. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // existing material tuning is preserved. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo // sun + ambient + headlight diffuse + specularcolor * spec_tint // direct sun highlight diff --git a/shaders/mat_colored.frag b/shaders/mat_colored.frag index 46de50f09..59ee3e8f8 100644 --- a/shaders/mat_colored.frag +++ b/shaders/mat_colored.frag @@ -24,8 +24,10 @@ layout(location = 1) out vec4 out_motion; void main() { - // no texture: the diffuse colour alone makes the albedo, apply_lights() applies it to the white base - vec4 tex_color = vec4(1.0, 1.0, 1.0, param[0].a); + // no texture: the diffuse colour, linearised, stands in for the texture, and apply_lights() scales it by the + // colour once more, as 26.05 did (c^2.2 * c); on a white base a dark grey of an untextured car came out + // tens of times lighter than in 26.05: tyres, bumpers and glass grey instead of near black + vec4 tex_color = vec4(pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)), param[0].a); // if (tex_color.a < opacity) // discard; @@ -33,7 +35,7 @@ void main() vec3 fragcolor = ambient; vec3 fragnormal = normalize(f_normal); float reflectivity = param[1].z; - float specularity = dot(pow(param[0].rgb, vec3(2.2)), vec3(0.5)); + float specularity = dot(tex_color.rgb, vec3(0.5)); glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); diff --git a/shaders/mat_sunlessnormalmap_specgloss.frag b/shaders/mat_sunlessnormalmap_specgloss.frag index 4e2abe1d9..eb1f9b916 100644 --- a/shaders/mat_sunlessnormalmap_specgloss.frag +++ b/shaders/mat_sunlessnormalmap_specgloss.frag @@ -37,6 +37,7 @@ uniform sampler2D specgloss; vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { // diffuse colour applied once, to the albedo (see material_diffuse() in light_common.glsl) + vec3 highlight_tint = texturecolor; texturecolor *= material_diffuse(); // Cab interior: dim ambient less than the exterior path - ambient // is the dominant indoor illumination, but it was still too bright. @@ -47,6 +48,9 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place + // (the same as apply_lights in light_common.glsl). + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -64,7 +68,7 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -95,11 +99,11 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl // Env reflection gated by env BRDF (roughness-attenuated, F0-tinted). vec3 env_reflection = envcolor * env_spec * reflectivity; - // Physically-based metal/rough combine (matches apply_lights / Substance): - // dielectric -> light-coloured highlight + full diffuse; metal -> albedo-tinted - // highlight, no diffuse term. Highlight strength left unchanged. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // Metal/rough combine, the same as apply_lights: the direct highlight is tinted by + // the albedo (as 26.05 drew it), a metal drops its diffuse term only where its + // reflection mask is full. Highlight strength left unchanged. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo + specularcolor * spec_tint diff --git a/shaders/tonemapping.glsl b/shaders/tonemapping.glsl index 863fe0fe1..701f9d5fd 100644 --- a/shaders/tonemapping.glsl +++ b/shaders/tonemapping.glsl @@ -139,14 +139,15 @@ vec3 ApplyAgX(vec3 linearColorRec709) vec4 tonemap(vec4 x) { - // Use AgX by default. Reinhard and ACES above are kept for reference. + // ACES, as 26.05 drew it. AgX and Reinhard above are kept for reference: AgX with its look crushed the dark + // end, so the night and everything in shadow went black (a night scene lost half its brightness). // Last-line-of-defense sanitize so NaN/Inf/negative HDR values do not // escape into log2()/pow() and produce black flashes or invalid output. vec3 hdr = x.rgb; hdr = mix(hdr, vec3(0.0), vec3(any(isnan(hdr)) || any(isinf(hdr)))); hdr = max(hdr, vec3(0.0)); - return FBOUT(vec4(ApplyAgX(hdr), x.a)); - //return FBOUT(vec4(ACESFilm(hdr), x.a)); + return FBOUT(vec4(ACESFilm(hdr), x.a)); + //return FBOUT(vec4(ApplyAgX(hdr), x.a)); //return FBOUT(vec4(reinhard(x.rgb), x.a)); } diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index abfa6d5e7..d5974f934 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1708,6 +1708,12 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token Parser >> gfx_shadow_rank_cutoff; gfx_shadow_rank_cutoff = std::clamp(gfx_shadow_rank_cutoff, 1, 3); } + else if (Token == "gfx.headlights.beamwidth") + { + Parser.getTokens(1); + Parser >> gfx_headlights_beamwidth; + gfx_headlights_beamwidth = std::clamp(gfx_headlights_beamwidth, 1.f, 4.f); + } else { tokenparsed = false; @@ -1978,6 +1984,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.shadergamma", gfx_shadergamma ); export_as_text( Output, "gfx.shadow.angle.min", gfx_shadow_angle_min ); export_as_text( Output, "gfx.shadow.rank.cutoff", gfx_shadow_rank_cutoff ); + export_as_text( Output, "gfx.headlights.beamwidth", gfx_headlights_beamwidth ); export_as_text( Output, "python.enabled", python_enabled ); export_as_text( Output, "python.threadedupload", python_threadedupload ); export_as_text( Output, "python.uploadmain", python_uploadmain ); diff --git a/utilities/Globals.h b/utilities/Globals.h index cdbab2c74..a754819da 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -352,6 +352,9 @@ struct global_settings { float gfx_distance_factor_max { 3.f }; float gfx_shadow_angle_min { -0.2f }; int gfx_shadow_rank_cutoff { 3 }; + // how many times wider sideways the headlight beam is spread than its texture: at 1.7 the ground beside the track gets + // most of the light of the ballast; 1 draws the narrow beam of 26.05 + float gfx_headlights_beamwidth { 1.7f }; float ui_fontsize = 13.0f; float ui_scale = 1.0f;