diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index ad2d471ec..12c5c5866 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -32,13 +32,27 @@ jobs: # running is left to finish; with a build cancelled the publish job of that run is skipped. A push # to master gets a group of its own, its commit, so the builds of master are never cancelled. + # Windows is built twice: with AVX2 (the default of ENABLE_AVX2) and without it, for CPUs older + # than Haswell (2013). Each variant has its own concurrency group, or one would cancel the other. + windows: - name: Windows x64 / MSVC + name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 concurrency: - group: ${{ github.workflow }}-windows-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -112,11 +126,13 @@ jobs: $pythonRoot = Split-Path $pythonExe Write-Host "Python root: $pythonRoot" + Write-Host "Extra CMake flags: ${{ matrix.variant.cmake_flags }}" cmake -S . -B build ` -G "Visual Studio 17 2022" ` -A x64 ` - "-DPython3_ROOT_DIR=$pythonRoot" + "-DPython3_ROOT_DIR=$pythonRoot" ` + ${{ matrix.variant.cmake_flags }} - name: Build shell: pwsh @@ -340,7 +356,7 @@ jobs: - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/bin/${{ env.CONFIG_WIN }}/ if-no-files-found: error @@ -349,7 +365,7 @@ jobs: - name: Upload Windows debug symbols uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-symbols-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/pdb/${{ env.CONFIG_WIN }}/*.pdb build/bin/${{ env.CONFIG_WIN }}/*.map @@ -362,13 +378,24 @@ jobs: # ============================================================ linux: - name: Linux x64 / GCC + name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 - # see the note above the windows job + # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: - group: ${{ github.workflow }}-linux-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -394,8 +421,13 @@ jobs: | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null sudo apt-get update + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. sudo apt-get install -y \ build-essential \ + libasound2-dev \ + libpulse-dev \ + libpipewire-0.3-dev \ libgl1-mesa-dev \ libglew-dev \ libglfw3-dev \ @@ -422,12 +454,17 @@ jobs: https://github.com/kcat/openal-soft.git \ /tmp/openal-soft + # the backends are loaded with dlopen at run time (ALSOFT_DLOPEN), so the bundled library needs none of them; + # REQUIRE makes a missing header fail the build instead of shipping a library without sound cmake \ -S /tmp/openal-soft \ -B /tmp/openal-soft/build \ -DCMAKE_BUILD_TYPE=Release \ -DALSOFT_EXAMPLES=OFF \ - -DALSOFT_UTILS=OFF + -DALSOFT_UTILS=OFF \ + -DALSOFT_REQUIRE_PIPEWIRE=ON \ + -DALSOFT_REQUIRE_PULSEAUDIO=ON \ + -DALSOFT_REQUIRE_ALSA=ON cmake \ --build /tmp/openal-soft/build \ @@ -455,6 +492,7 @@ jobs: -DWITH_ZMQ=OFF \ -DWITH_OPENVR=OFF \ -DUSE_LTO=OFF \ + ${{ matrix.variant.cmake_flags }} \ -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" @@ -520,7 +558,7 @@ jobs: - name: Upload Linux build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-linux-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_LINUX }} path: | build/bin/ if-no-files-found: error @@ -543,29 +581,47 @@ jobs: cancel-in-progress: false steps: - - name: Download Windows build + # the AVX2 build keeps the old name of the download, so the links already handed out still work + - name: Download Windows build (AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - - name: Download Linux build + - name: Download Windows build (no AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64-noavx2 + + - name: Download Linux build (AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 + - name: Download Linux build (no AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} + path: dist/maszyna-linux-x64-noavx2 + - name: Pack run: | cd dist - find maszyna-linux-x64 -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; - if [ -d maszyna-linux-x64/linuxpython64/bin ]; then - chmod +x maszyna-linux-x64/linuxpython64/bin/* - fi + # the artifacts lose the executable bit + for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; + if [ -d "$dir/linuxpython64/bin" ]; then + chmod +x "$dir"/linuxpython64/bin/* + fi + done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . ls -la - name: Publish rolling release of the branch @@ -585,14 +641,18 @@ jobs: "" \ "Download without a GitHub account:" \ "- Windows: $base/maszyna-windows-x64.zip" \ + "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ "- Linux: $base/maszyna-linux-x64.tar.gz" \ + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ dist/maszyna-windows-x64.zip \ + dist/maszyna-windows-x64-noavx2.zip \ dist/maszyna-linux-x64.tar.gz \ + dist/maszyna-linux-x64-noavx2.tar.gz \ --target "$SHA" \ --prerelease \ --latest=false \ @@ -601,4 +661,6 @@ jobs: echo "### Public download" >> "$GITHUB_STEP_SUMMARY" echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY" + echo "- Windows, no AVX2: $base/maszyna-windows-x64-noavx2.zip" >> "$GITHUB_STEP_SUMMARY" echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY" + echo "- Linux, no AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" >> "$GITHUB_STEP_SUMMARY" diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b98ae937..78abf46a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -478,6 +478,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 "") @@ -553,6 +558,7 @@ set(CORE_SOURCES "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" "vehicle/blackbox.cpp" +"utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" "vehicle/drivingaid.cpp" diff --git a/EU07.cpp b/EU07.cpp index 20f24aa5a..a76564663 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,11 +22,17 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include #include #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -107,6 +113,8 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); + // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + PhysicsLogs.stop(); finish_log(); fflush(stdout); fflush(stderr); @@ -136,10 +144,29 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } +// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred +// of them they took all the files the C library of Windows lets a process have open by default (512): the files +// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h), +// but the limit is raised to the most either system allows still, for whatever else opens many files at once +void raise_open_files_limit() +{ +#ifdef _WIN32 + _setmaxstdio(8192); +#else + rlimit limit{}; + if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max) + { + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + } +#endif +} + } // namespace int main(int argc, char *argv[]) { + raise_open_files_limit(); #ifdef WITHDUMPGEN #ifdef _WIN32 SetUnhandledExceptionFilter(CrashHandler); @@ -215,6 +242,9 @@ int main(int argc, char *argv[]) MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); } #endif + // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // otherwise, and a second stop only writes what came since + PhysicsLogs.stop(); } #ifndef _WIN32 fflush(stdout); diff --git a/application/application.cpp b/application/application.cpp index 96f578514..140475b60 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, waited for a second at most: the rest is dropped + PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) mode.reset(); @@ -1323,6 +1327,21 @@ int eu07_application::init_settings(int Argc, char *Argv[]) simulation::apply_test_mode_settings(); } + // a renderer this build doesn't have gets the full one: the starter writes the words of every build it knows + // ("vulkan" for the vulkan builds), and any word not known here used to start the legacy renderer. + // "simpleshader" and "off" of the older starters keep the legacy one they always had + auto const &renderer{Global.GfxRenderer}; + auto const known{renderer == "default" || renderer == "legacy" || renderer == "simple" || renderer == "null" || renderer == "simpleshader" || + renderer == "off" || (renderer == "experimental" && gfx_renderer_factory::get_instance()->has_backend(renderer))}; + if (false == known) + { + WriteLog("gfxrenderer \"" + renderer + "\" isn't in this build, the full renderer is used instead"); + Global.GfxRenderer = "default"; + Global.NvRenderer = false; + Global.LegacyRenderer = false; + Global.BasicRenderer = false; + } + return 0; } diff --git a/application/editormode.cpp b/application/editormode.cpp index e08e1f0e7..ab150cb7b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -1398,6 +1398,7 @@ bool editor_mode::update() Global.editor_tracks = (current_work_area() == work_area::tracks); selftest_step(); steps.step("selftest"); + thumbnails_trim(); // the drives of the switches go to the tips of their blades once, as the templates of the scenery are known if (false == m_drives_checked) { diff --git a/application/editormode.h b/application/editormode.h index bcf22592c..81347c950 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -745,13 +745,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri char filter[64]{}; float size{96.f}; // of the images, pixels std::string selected; - std::map thumbnails; // texture shown for the item of the name, 0: none + struct thumbnail + { + int texture{0}; // 0: none + int material{0}; // the material the texture is the first of, 0: a texture alone + double shown{0.0}; // when it was last asked for, ImGui time + }; + std::map thumbnails; // texture shown for the item of the name + bool refresh{false}; // all the images to be let go of and read again int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor int loadsframe{-1}; } m_textures; void render_texture_browser(); // texture of the image of the item of the browser, 0 while there's none std::uint64_t texture_thumbnail(texture_browser::item const &Item); + // the textures of the images out of sight for a while taken out of the memory: a picker of thousands of them scrolled + // through would keep them all, full size, until the memory ran out + void thumbnails_trim(); // takes a material dragged from the texture browser onto the item drawn last. returns: true if one was dropped, its name in Name static bool material_drop(std::string &Name); // the same, for a text field diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index 155210a87..e3423de5e 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -93,25 +93,53 @@ std::uint64_t editor_mode::texture_thumbnail(texture_browser::item const &Item) if (browser.loads >= 2) return 0; ++browser.loads; - texture_handle texture{null_handle}; + texture_browser::thumbnail thumbnail; if (Item.material) { - auto const material{GfxRenderer->Fetch_Material(Item.name)}; - if (auto const *data{GfxRenderer->Material(material)}; material != null_handle && data != nullptr) - texture = data->GetTexture(0); + // a material reads all its textures, the normal maps and the rest with the one shown + thumbnail.material = GfxRenderer->Fetch_Material(Item.name); + if (auto const *data{GfxRenderer->Material(thumbnail.material)}; thumbnail.material != null_handle && data != nullptr) + thumbnail.texture = data->GetTexture(0); } else - texture = GfxRenderer->Fetch_Texture(Item.name, true); - lookup = browser.thumbnails.emplace(Item.name, texture).first; + thumbnail.texture = GfxRenderer->Fetch_Texture(Item.name, true); + lookup = browser.thumbnails.emplace(Item.name, thumbnail).first; } - if (lookup->second == null_handle) + lookup->second.shown = ImGui::GetTime(); + if (lookup->second.texture == null_handle) return 0; - auto &texture{GfxRenderer->Texture(lookup->second)}; + auto &texture{GfxRenderer->Texture(lookup->second.texture)}; if (false == texture.get_is_ready()) texture.create(); return texture.get_is_ready() ? static_cast(texture.get_id()) : 0; } +void editor_mode::thumbnails_trim() +{ + // a few seconds out of sight, so scrolling back and forth doesn't read them over and over + // all of them after the browser's Refresh, here before any image is drawn: not while the panels drawn earlier in the + // frame still refer to them + auto constexpr kept{3.0}; + auto const now{ImGui::GetTime()}; + auto &browser{m_textures}; + for (auto entry{browser.thumbnails.begin()}; entry != browser.thumbnails.end();) + { + auto const &thumbnail{entry->second}; + if (false == browser.refresh && ((thumbnail.texture == null_handle && thumbnail.material == null_handle) || now - thumbnail.shown < kept)) + { + ++entry; + continue; + } + // the scene's own textures stay; shown again, the image is read anew within the few a frame + if (thumbnail.material != null_handle) + GfxRenderer->Unload_Material(thumbnail.material); + else + GfxRenderer->Unload_Texture(thumbnail.texture); + entry = browser.thumbnails.erase(entry); + } + browser.refresh = false; +} + void editor_mode::render_texture_browser() { auto &browser{m_textures}; @@ -173,7 +201,8 @@ void editor_mode::render_texture_browser() if (ImGui::Button(STR_C("Refresh"))) { browser.listed = false; - browser.thumbnails.clear(); + // the images let go of at the start of the next frame, see thumbnails_trim() + browser.refresh = true; } ImGui::SameLine(); ImGui::TextUnformatted((std::string{paths::textures} + browser.folder).c_str()); diff --git a/application/editormodetrackprops.cpp b/application/editormodetrackprops.cpp index 13a9d2a49..4542d0225 100644 --- a/application/editormodetrackprops.cpp +++ b/application/editormodetrackprops.cpp @@ -1043,8 +1043,10 @@ void editor_mode::textures_index() { if (entry->is_directory(ignored)) { - // the normal maps go with their textures, not on a track by themselves - if (lowered(entry->path().filename().string()) == "normals") + // the normal maps go with their textures, not on a track by themselves; the previews of the node bank, thousands of + // them, are images of models and not textures of anything + auto const folder{lowered(entry->path().filename().string())}; + if (folder == "normals" || (folder == "previews" && entry.depth() == 0)) entry.disable_recursion_pending(); continue; } diff --git a/audio/audio.cpp b/audio/audio.cpp index 845fba9e7..cd053f682 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -35,7 +35,8 @@ decoded_sound decode_sound( std::string const &File ) { SF_INFO si; si.format = 0; - SNDFILE *sf = sf_open(File.c_str(), SFM_READ, &si); + // the file as it's named on the disk, the name of the buffer is in lowercase + SNDFILE *sf = sf_open(FileOnDisk(File).c_str(), SFM_READ, &si); if (sf == nullptr) throw std::runtime_error("sound: sf_open failed"); @@ -216,9 +217,9 @@ openal_buffer::fetch_caption() { std::string captionfilename { name }; captionfilename.erase( captionfilename.rfind( '.' ) ); // obcięcie rozszerzenia captionfilename += "-" + Global.asLang + ".txt"; // już może być w różnych językach - if( true == FileExists( captionfilename ) ) { + if( auto const casedfilename { FileCased( captionfilename ) }; false == casedfilename.empty() ) { // wczytanie - std::ifstream inputfile( captionfilename ); + std::ifstream inputfile( casedfilename ); caption.assign( std::istreambuf_iterator( inputfile ), std::istreambuf_iterator() ); } } diff --git a/blackbox_doc.md b/blackbox_doc.md index ab330dc2e..126cea033 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -7,14 +7,42 @@ done at the same moment, every command the user gave, when the autopilot took ov the timetable and how the train kept to it at each station, and where it was told to sound the horn. From it another program (the starter, a viewer) can replay the session on the map, or set the user's driving against the AI's. -It is written along with the physics logs: `physicslog yes` in `eu07.ini`, not in an editor session. -`blackbox no` turns it off while the physics logs are kept (it is on by default). The file goes next to -them, `physicslog/_.blackbox` (the local time the recording started at). -The `.dat` logs stay as they are. +`blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no +`blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. +The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are +hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail +vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +editor session. The file goes to `physicslog/_.blackbox` (the local time the +recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. + +With the physics logs off it still gives the `.dat` log of each vehicle the user was in, as it goes: +`physicslog/.dat`, the same file name, the same columns and the same line every 0.05 s as +`physicslog yes` would write. In the name of a file, of these logs and of those of `physicslog yes`, the +characters no file name may have on Windows, `< > : " / \ | ? *` and the control characters, are `_`, on +every system: a spawned vehicle, named `:`, has its log as `_.dat`. A name +Windows keeps for a device (`con`, `nul`, `com1` and the like) gets a `_` before it. A log is the driver's, named after the vehicle that driver began in: it +begins the first time the user is with that driver, and goes on while the user looks around outside, or +moves to another cab of the unit or another vehicle of the same train. Taking a vehicle of another driver +goes on in that driver's log, begun then if it is the first time. Back with a driver, the log goes on after +the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of +the driver of its train. So the speed recorder's tape can be read from them as before, also while the +simulator runs, without a log of every vehicle. A driver who writes a log of its own, with +`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the +user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the +user drives has no log. Like those of `physicslog yes`, they are written every +two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds +of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. +The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of +those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as +long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. +Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, +and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no -new one starts when driving goes on after that. +new one starts when driving goes on after that. The `.dat` logs it gives with the physics logs off go on +then, after the gap of the time in the editor, until the simulator closes: they are files of their own. It is written as the session goes and flushed once a second, so the file can be read while the simulator still writes it, and after a crash all but the last second is there. A file without the `end` record @@ -162,14 +190,15 @@ record. ### 0x20 cab -The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 190 bytes. +The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 194 bytes (190 in the +files written before the speed of the wheels was added at the end). | type | field | |---------|------------------------------------------------------------------------| | `f64` | t | | `u32` | number of the vehicle | | `dvec3` | position | -| `f32` | speed [km/h], positive along the front of the vehicle | +| `f32` | speed of the vehicle [km/h], positive along its front | | `f32` | acceleration along the track [m/s²] | | `f32` | odometer [km] | | `u8` | driver: 0 none, 1 the user, 2 the AI (the autopilot) | @@ -221,6 +250,7 @@ The vehicle the user is in, every 0.1 s, also while the user looks around outsid | `f32` | the clutch of a diesel's gearbox, 0 open .. 1 closed | | `f32` | the filling of a diesel's hydraulic torque converter, 0..1 | | `f32` | the highest brake cylinder pressure of the vehicles of the train [bar] | +| `f32` | speed of the wheels [km/h], as the speedometer shows it: those of the powered vehicle (in a unit driven from an unpowered car, its motor car), signed as the speed of the vehicle: apart from it while the wheels slip, 0 while they are locked in a skid | The lights the train is to show follow from the movement and the two patterns after it: in a train run the head the pattern asked for, the usual one Pc 1 (both headlights and the upper one; Pc 2 is the left red marker with the right and the @@ -285,7 +315,8 @@ whose motors the cab drives (the motor car of a unit). | 0x0800'0000 | the cruise control holds a speed | The doors, their permits and steps, the departure signal and the releaser are of the vehicle the user is -in; the pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. +in. Left and right are those of the vehicle, seen from its front: from the rear cab (the cab -1) the driver's +left doors are the vehicle's right, as the simulator works them from there. The pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. The lights: 0x001 left headlight, 0x002 left red marker, 0x004 upper headlight, 0x010 right headlight, 0x020 right red marker, 0x040 rear-end signals, 0x080 left and 0x100 right auxiliary diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 12569ebd0..81a195aeb 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -16,7 +16,10 @@ http://mozilla.org/MPL/2.0/. #include #endif +#include +#include #include +#include namespace editor_http { @@ -160,6 +163,37 @@ bool client::get(std::string const &Url, std::vector &Out, std::st #elif defined(EU07_WITH_CURL) +namespace +{ +// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it +// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there +// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +std::string const &certificates_file() +{ + static std::string const file{[]() { + std::error_code error; + for (char const *variable : {"SSL_CERT_FILE", "CURL_CA_BUNDLE"}) + { + if (char const *value{std::getenv(variable)}; (value != nullptr) && (*value != '\0') && std::filesystem::is_regular_file(value, error)) + return std::string{value}; + } + for (char const *candidate : { + "/etc/ssl/certs/ca-certificates.crt", // Debian, Ubuntu, Arch, SteamOS, Gentoo, NixOS + "/etc/pki/tls/certs/ca-bundle.crt", // Fedora, RHEL + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL + "/etc/ssl/ca-bundle.pem", // openSUSE + "/etc/ssl/cert.pem", // Alpine, the BSDs, macOS + }) + { + if (std::filesystem::is_regular_file(candidate, error)) + return std::string{candidate}; + } + return std::string{}; + }()}; + return file; +} +} // namespace + client::client() : m_platform(std::make_unique()) { @@ -204,6 +238,14 @@ bool client::get(std::string const &Url, std::vector &Out, std::st ::curl_easy_reset(m_platform->curl); ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + if (auto const &certificates{certificates_file()}; false == certificates.empty()) + { + ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); +#if LIBCURL_VERSION_NUM >= 0x073400 + // an https proxy is checked with the same file + ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); +#endif + } ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); // http kept for the services the user types; nothing else, also where a redirect leads diff --git a/editor/editorPreviews.cpp b/editor/editorPreviews.cpp index 27f84a9fe..68164460c 100644 --- a/editor/editorPreviews.cpp +++ b/editor/editorPreviews.cpp @@ -298,7 +298,9 @@ void image_cache::work() m_queue.pop_front(); } int width{0}, height{0}, components{0}; - auto *pixels{stbi_load(image.path.c_str(), &width, &height, &components, 4)}; + // the file as it's named on the disk, the path stays the key of the cache + auto const file{FileCased(image.path)}; + auto *pixels{file.empty() ? nullptr : stbi_load(file.c_str(), &width, &height, &components, 4)}; if (pixels != nullptr && width > 0 && height > 0) { // scaled down by the average of the pixels which make each one, the longer side to the size of the cache diff --git a/gl/shader.cpp b/gl/shader.cpp index 31a3e6a87..c276cdef8 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -1,8 +1,10 @@ #include "stdafx.h" +#include #include #include #include +#include #include "shader.h" #include "glsl_common.h" #include "utilities/Logs.h" @@ -58,6 +60,12 @@ std::string gl::shader::read_file(const std::string &filename) const std::ifstream f; f.open(filename); + if (false == f.is_open()) + { + // with the reason the system gives: a file which is there but can't be opened (too many files open) looks + // the same as a missing one otherwise + throw shader_exception("cannot open shader: " + filename + " (" + std::generic_category().message(errno) + ")"); + } stream << f.rdbuf(); f.close(); diff --git a/global_include/interfaces/IMaterial.h b/global_include/interfaces/IMaterial.h index c6f3d1237..2d16a43b0 100644 --- a/global_include/interfaces/IMaterial.h +++ b/global_include/interfaces/IMaterial.h @@ -3,6 +3,7 @@ #include #include #include +#include #include "ITexture.h" @@ -17,6 +18,11 @@ struct IMaterial virtual std::optional GetSelfillum() const = 0; virtual int GetShadowRank() const = 0; virtual texture_handle GetTexture(int slot) const = 0; + // every texture the material draws with, those of all its variants included. materials which don't tell give none + virtual std::vector GetAllTextures() const + { + return {}; + } static IMaterial *null_material() { struct NullMaterial : public IMaterial diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 668792f28..4a5bc4759 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -12248,15 +12248,11 @@ msgstr "Wierzchołek %zu: krzywa przejściowa między łukiem przylegającego to msgid "Download area" msgstr "Obszar pobierania" -msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model, -goes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" -msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle -do pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" +msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model,\ngoes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" +msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle\ndo pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" -msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up; -a point dragged moves, Shift+click removes it" -msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje; -przeciągnięty punkt się przesuwa, Shift+klik go usuwa" +msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up;\na point dragged moves, Shift+click removes it" +msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje;\nprzeciągnięty punkt się przesuwa, Shift+klik go usuwa" msgid "%zu points" msgstr "punktów: %zu" diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 680f67c42..52bc4047e 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -137,15 +137,19 @@ TModelsManager::find_in_databank( std::string const &Name ) { } // checks whether specified file exists. returns name of the located file, or empty string. +// the file is found in any case, as the scenery made on Windows names it, but the name is given back as asked for: it's the key of +// the bank, and TModel3d::LoadFromFile() opens the file as it's named on the disk std::string TModelsManager::find_on_disk( std::string const &Name ) { std::vector extensions { { ".e3d" }, { ".t3d" } }; for( auto const &extension : extensions ) { - auto lookup = FileExists(Name + extension) ? Name : FileExists(paths::models + Name + extension) ? paths::models + Name : ""; - if( false == lookup.empty() ) { - return lookup; + if( false == FileCased( Name + extension ).empty() ) { + return Name; + } + if( false == FileCased( paths::models + Name + extension ).empty() ) { + return paths::models + Name; } } diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 44f5f6255..e3507e216 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1702,24 +1702,27 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) m_filename = name; asBinary = name + ".e3d"; + // the files as they're named on the disk, the name given is in lowercase + auto const textfile{FileCased(name + ".t3d")}; + auto const binaryfile{FileCased(asBinary)}; // Hirek: Jesli mamy ustawione priorityLoadText3D na yes to wpierw ladujemy t3d - if (Global.priorityLoadText3D && FileExists(name + ".t3d")) + if (Global.priorityLoadText3D && (false == textfile.empty())) { - WriteLog("Forced loading text model \"" + name + ".t3d\""); - LoadFromTextFile(name + ".t3d", dynamic); + WriteLog("Forced loading text model \"" + textfile + "\""); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } - else if (FileExists(asBinary)) + else if (false == binaryfile.empty()) { - LoadFromBinFile(asBinary, dynamic); + LoadFromBinFile(binaryfile, dynamic); asBinary = ""; Init(); } - else if (FileExists(name + ".t3d")) + else if (false == textfile.empty()) { - LoadFromTextFile(name + ".t3d", dynamic); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } diff --git a/model/Texture.cpp b/model/Texture.cpp index cd275c9e0..9b428202b 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -640,7 +640,7 @@ void opengl_texture::load_STBI() { int x, y, n; stbi_set_flip_vertically_on_load(1); - uint8_t *image = stbi_load((name + type).c_str(), &x, &y, &n, 4); + uint8_t *image = stbi_load(FileOnDisk(name + type).c_str(), &x, &y, &n, 4); if (!image) { data_state = resource_state::failed; @@ -818,7 +818,7 @@ DDSURFACEDESC2 opengl_texture::deserialize_ddsd(std::istream &s) void opengl_texture::load_DDS() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -938,7 +938,7 @@ opengl_texture::load_DDS() { if( true == Global.gfx_texture_streaming ) { // the data is read by a worker thread, everything else about the texture is known already request = std::make_shared(); - request->file = name + type; + request->file = FileOnDisk( name + type ); request->offset = static_cast( file.tellg() ) + offset; request->size = datasize; request->flip = flip; @@ -1000,7 +1000,7 @@ opengl_texture::load_DDS() { void opengl_texture::load_KTX() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -1061,7 +1061,7 @@ opengl_texture::load_KTX() { void opengl_texture::load_TEX() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); char head[ 5 ]; file.read( head, 4 ); @@ -1108,7 +1108,7 @@ opengl_texture::load_TEX() { void opengl_texture::load_TGA() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); // Read the header of the TGA, compare it with the known headers for compressed and uncompressed TGAs unsigned char tgaheader[ 18 ]; @@ -1886,6 +1886,52 @@ texture_manager::mark_as_needed( texture_handle const Texture, bool const Near ) } } +void +texture_manager::unload( texture_handle const Texture ) { + + if( ( Texture <= 0 ) + || ( Texture >= static_cast( m_textures.size() ) ) ) { + return; + } + auto const &record { m_textures[ Texture ] }; + auto &texture { *record.first }; + if( ( record.second != resource_timestamp() ) + || ( texture.id == 0 ) // failed to load + || ( true == texture.is_static ) + || ( true == texture.is_rendertarget ) + || ( texture.type == "make:" ) + || ( texture.type == "internalsrc:" ) ) { + return; + } + if( ( texture.data_state == resource_state::loading ) + && ( texture.request != nullptr ) ) { + // read by a worker thread: taken over first, to be dropped with the rest + texture.complete_data(); + if( texture.data_state == resource_state::failed ) { + return; + } + } + auto const created { texture.id != opengl_texture::invalid_id }; + if( ( false == created ) + && ( texture.data_state != resource_state::good ) ) { + // nothing read nor made, e.g. the textures of a material asked for without loading + return; + } + if( true == created ) { + // deleted outright: release() would read the texture back from the card with gfx.resource.move, only for it to be dropped + ::glDeleteTextures( 1, &texture.id ); + texture.id = opengl_texture::invalid_id; + texture.is_ready = false; + // the released gl name can be given to a new texture, the unit cache can't trust it + for( auto &unit : opengl_texture::units ) { + unit = -1; + } + } + texture.data = std::vector(); + texture.data_state = resource_state::none; + texture.reload_on_use = true; +} + // releases gl textures of vehicles not needed nor drawn for a while void texture_manager::release_unneeded() { diff --git a/model/Texture.h b/model/Texture.h index 313d0f6f4..20221fcea 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -181,6 +181,10 @@ public: // releases gl textures of vehicles not needed nor drawn for a while void release_unneeded(); + // takes a texture the scene has never drawn out of both the gfx card and the memory, e.g. the image of a picker scrolled + // past, or one read and not made yet; it's read again when it's used. textures the scene draws are left to the resource sweep + void + unload( texture_handle const Texture ); // debug performance string std::string info() const; diff --git a/model/material.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 5eb98222b..800f33dcf 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2570,6 +2570,11 @@ ITexture const &opengl33_renderer::Texture(texture_handle const Texture) const return m_textures.texture(Texture); } +void opengl33_renderer::Unload_Texture(texture_handle const Texture) +{ + m_textures.unload(Texture); +} + void opengl33_renderer::Update_AnimModel(TAnimModel *model) { model->RaAnimate(m_framestamp); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 807563c40..4322cc2db 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -110,6 +110,8 @@ class opengl33_renderer : public gfx_renderer { Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 71bd7d0ef..5083c6f2f 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -419,6 +419,15 @@ opengl_renderer::Render() { // add user interface setup_units( true, false, false ); ::glPushClientAttrib( GL_CLIENT_VERTEX_ARRAY_BIT ); + // the arrays the scene left enabled point into the buffer of whatever was drawn last; the ui sets up + // the vertex, colour and texture coordinates of the active unit only, so the driver would go on reading + // the rest with the indices of the ui, past the end of that buffer once the ui has more vertices than it + for( auto const unit : m_geometry.units().texture ) { + ::glClientActiveTexture( GL_TEXTURE0 + unit ); + ::glDisableClientState( GL_TEXTURE_COORD_ARRAY ); + } + ::glDisableClientState( GL_NORMAL_ARRAY ); + ::glDisableClientState( GL_COLOR_ARRAY ); ::glClientActiveTexture( GL_TEXTURE0 + m_diffusetextureunit ); // clear state for ui @@ -1922,6 +1931,12 @@ opengl_renderer::Texture( texture_handle const Texture ) const { return m_textures.texture( Texture ); } +void +opengl_renderer::Unload_Texture( texture_handle const Texture ) { + + m_textures.unload( Texture ); +} + void opengl_renderer::Pick_Control_Callback( std::function Callback ) { diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index ecb8a3c50..ef3a9f0f3 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -95,6 +95,8 @@ public: Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/renderer.cpp b/rendering/renderer.cpp index d9d4b5df0..7c4098ef0 100644 --- a/rendering/renderer.cpp +++ b/rendering/renderer.cpp @@ -29,6 +29,11 @@ std::unique_ptr gfx_renderer_factory::create(const std::string &ba return nullptr; } +bool gfx_renderer_factory::has_backend(const std::string &name) const +{ + return backends.contains(name); +} + gfx_renderer_factory *gfx_renderer_factory::get_instance() { if (!instance) @@ -39,6 +44,16 @@ gfx_renderer_factory *gfx_renderer_factory::get_instance() gfx_renderer_factory *gfx_renderer_factory::instance; +void gfx_renderer::Unload_Material( material_handle const Material ) +{ + if( Material == null_handle ) { + return; + } + for( auto const texture : this->Material( Material )->GetAllTextures() ) { + Unload_Texture( texture ); + } +} + material_handle gfx_renderer::Terrain_Material( material_handle const Reuse, std::vector const &Layers, int const Samples, std::uint8_t const *Weights, glm::vec3 const &Placement ) { // without blending the chunk gets the material which covers the most of it diff --git a/rendering/renderer.h b/rendering/renderer.h index 5ad805c4a..c72dcaea9 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -102,6 +102,11 @@ public: virtual void Bind_Texture( std::size_t const Unit, texture_handle const Texture ) = 0; virtual auto Texture( texture_handle const Texture ) -> ITexture & = 0; virtual auto Texture( texture_handle const Texture ) const -> ITexture const & = 0; + // a texture the scene has never drawn taken out of the gfx card and the memory, read again when it's used: the image of a + // texture picker scrolled past. backends which keep their textures otherwise leave it + virtual void Unload_Texture( texture_handle const Texture ) {} + // the same for all the textures of a material, those of its variants with them + void Unload_Material( material_handle const Material ); // utility methods virtual void Pick_Control_Callback( std::function Callback ) = 0; virtual void Pick_Node_Callback( std::function Callback ) = 0; @@ -151,6 +156,7 @@ public: bool register_backend(const std::string &backend, create_method func); std::unique_ptr create(const std::string &name); + bool has_backend(const std::string &name) const; static gfx_renderer_factory* get_instance(); diff --git a/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/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 608b07586..9e979e2ca 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" @@ -43,6 +44,7 @@ namespace { // [s] between the samples of the user's train, the looks at everything else and the full looks at the vehicles constexpr double cabinterval{0.1}; +constexpr double tapeinterval{0.05}; // as the physics logs (deltalog of Driver.cpp) constexpr double lookinterval{1.0}; constexpr double slowlook{20.0}; // [ms] a look around taking longer is told in the log, part by part constexpr double keyframeinterval{60.0}; @@ -234,15 +236,26 @@ void blackbox_recorder::update(double const Deltatime) { if (false == simulation::is_ready) return; m_started = true; - if (false == WriteLogFlag || false == Global.BlackBox || Global.editor_session) + // "blackbox yes" or "no" of eu07.ini decides by itself, with no entry it goes with the physics logs + if (false == Global.BlackBox.value_or(WriteLogFlag || WriteTrainLogFlag) || Global.editor_session) return; + m_taping = true; open(); } - if (m_writer == nullptr) + if (false == m_taping) return; std::scoped_lock lock{m_mutex}; m_time += Deltatime; + // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a + // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with + // a recording which couldn't be made + if (m_time >= m_tapedue) { + keep_tape_line(); + m_tapedue = std::max(m_tapedue + tapeinterval, m_time); + } + if (m_writer == nullptr) + return; if (m_time >= m_cabdue) { write_cab(); m_cabdue = std::max(m_cabdue + cabinterval, m_time); @@ -412,6 +425,13 @@ void blackbox_recorder::write_cab() { sample.vehicle = vehicle_id(vehicle); sample.position = vehicle->GetPosition(); sample.speed_kmh = static_cast(occupied->V * 3.6); + // of the wheels as they turn, which the speedometer shows: apart from that of the vehicle when they slip or skid. + // those of the powered vehicle, as the speedometer has it (TTrain::DynamicSet), which in a unit driven from an + // unpowered car is another one, maybe facing the other way: signed as the occupied one's speed + // the vehicle itself, if none in the unit is powered + auto const *powered{train->Dynamic()->FindPowered()}; + auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->MoverParameters->WheelDiameter * powered->MoverParameters->nrot * 3.6); sample.acceleration = static_cast(controlling->AccS); sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { @@ -480,6 +500,30 @@ void blackbox_recorder::write_cab() { m_writer->cab(sample); } +void blackbox_recorder::keep_tape_line() { + auto const *train{simulation::Train}; + if (train == nullptr || train->Dynamic() == nullptr) + return; + auto const *vehicle{train->Dynamic()}; + // the driver of the vehicle, whose log it would be: it keeps the name of its first vehicle, so a change of the cab + // in a unit goes on in the same log. a passive one stands still (its clock too), so then the driver of the train + auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; + if (driver == nullptr) + return; + auto const &name{driver->physicslog_name()}; + // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has + // no time for, on a hard disk with hundreds of them + PhysicsLogs.put_first(name); + // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice + if (driver->writes_physicslog()) + return; + if (m_tapes.insert(name).second) { + PhysicsLogs.begin(name, TController::physicslog_header()); + WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); + } + PhysicsLogs.append(name, driver->physicslog_line()); +} + void blackbox_recorder::look_around(bool const Keyframe) { auto const &time{simulation::Time.data()}; m_writer->clock(m_time, static_cast(time.wYear), static_cast(simulation::Time.year_day()), second_of_day()); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 677c680b0..18ee052c4 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -31,13 +32,14 @@ enum class user_command; namespace simulation { // the black box of the session (see blackbox_doc.md): written along with the physics logs, in driver mode, -// from the moment the scenario is loaded until the simulator closes or the editor is entered +// from the moment the scenario is loaded until the simulator closes or the editor is entered. the tapes of the user's +// vehicles, with the physics logs off, go on after the editor until the simulator closes class blackbox_recorder { public: // starts the recording once the scenario is ready, if it is to be made, then records what is due. // Deltatime: simulation time passed since the last call void update(double Deltatime); - // writes the end of the recording and closes the file. a recording closed isn't started again + // writes the end of the recording and closes the file. a recording closed isn't started again; its tapes go on void close(); // what happens between the looks, from wherever it happens; the cabs may run on threads of their own. @@ -86,6 +88,11 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); + // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road + // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would + // have it. a driver's log is begun at the first line given for that driver, and goes on + // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap + void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals void look_around(bool Keyframe); void look_at_vehicles(bool Keyframe); @@ -107,8 +114,12 @@ private: std::ofstream m_file; std::unique_ptr m_writer; bool m_started{false}; // tried to start, made or not + bool m_taping{false}; // the recording was to be made: its tapes are kept from then on, the file made or not, closed or not double m_time{0.0}; double m_cabdue{0.0}; + double m_tapedue{0.0}; + // the names of the logs begun by the recording + std::set m_tapes; double m_lookdue{0.0}; double m_keyframedue{0.0}; std::unordered_map m_vehicles; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 41f67398c..60854482c 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -1205,6 +1205,8 @@ include_terrain_file( std::string File, std::string &Includes, scene::scratch_da replace_slashes( File ); erase_extension( File ); + // the parser gives the name in lowercase, the files may be named in another case; the binary file is made next to the text + File = FileStemOnDisk( Global.asCurrentSceneryPath, File, { ".txtf", ".btf" } ); if( std::find( binary.terrain_textfiles.begin(), binary.terrain_textfiles.end(), File ) != binary.terrain_textfiles.end() ) { WriteLog( "Terrain file: " + File + " is already in use, ignored" ); return; diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 89a8a1046..2efa57291 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" +#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -44,6 +46,15 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } +// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of +// the other drivers: the closing at the end of the run drops those it has no time for +void put_physicslog_first(TDynamicObject const &Vehicle) +{ + auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; + if (driver != nullptr) + PhysicsLogs.put_first(driver->physicslog_name()); +} + } // namespace namespace simulation { @@ -124,11 +135,13 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - if (simulation::Vehicles.find(name) == nullptr) + auto const *vehicle { simulation::Vehicles.find(name) }; + if (vehicle == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } + put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; @@ -261,7 +274,9 @@ void test_manager::check_wall_clock(double const Elapsed) // but which doesn't close ends with its result if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit))) ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit)); - // what was logged last gets written, unless the log is held up by a hung thread + // what was logged last gets written, unless the log is held up by a hung thread, or the physics logs by a writer + // holding their files or a disk which doesn't answer: the run ends anyway, two seconds later at most + PhysicsLogs.flush_for(std::chrono::seconds{2}); StopLogService(); std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::_Exit(exit_code()); diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index b11253b49..cad1920a1 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -127,6 +127,7 @@ blackbox::cab_sample sample() { s.clutch = 0.75f; s.converter_fill = 0.25f; s.consist_brake_cylinder = 3.5f; + s.wheel_speed_kmh = 71.5f; return s; } @@ -285,6 +286,8 @@ TEST_CASE("blackbox: a sample of the user's train has the documented size and or CHECK(cab.get() == 0.25f); // the highest brake cylinder pressure of the train CHECK(cab.get() == 3.5f); + // the speed of the wheels + CHECK(cab.get() == 71.5f); CHECK(cab.done()); } diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp new file mode 100644 index 000000000..32fadec03 --- /dev/null +++ b/tests/unit/test_physicslog.cpp @@ -0,0 +1,385 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/physicslog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to + +namespace { + +// a folder of its own for the logs of a test, in the build folder of the tests, removed with the object. the writer +// makes it itself +class log_folder { +public: + explicit log_folder(std::string const &Name) : m_path{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / std::format("eu07_physicslog_test_{}", Name)} { + std::filesystem::remove_all(m_path); + } + ~log_folder() { + std::error_code error; + std::filesystem::remove_all(m_path, error); + } + log_folder(log_folder const &) = delete; + log_folder &operator=(log_folder const &) = delete; + + std::filesystem::path const &path() const { return m_path; } + // the log as it stands, read in text mode as it is written: what was given to it + std::string read(std::string const &Name) const { return read_file(m_path / (Name + ".dat")); } + static std::string read_file(std::filesystem::path const &File) { + std::ifstream file{File}; + if (false == file.is_open()) + return {}; + std::ostringstream text; + text << file.rdbuf(); + return text.str(); + } + // waits up to five seconds for the log to read Text + bool reads(std::string const &Name, std::string const &Text) const { + auto const until{std::chrono::steady_clock::now() + std::chrono::seconds{5}}; + while (read(Name) != Text && std::chrono::steady_clock::now() < until) + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + return read(Name) == Text; + } + +private: + std::filesystem::path m_path; +}; + +constexpr auto header{"Time[s] Velocity[m/s]\r\n"}; + +} // namespace + +TEST_CASE("physicslog: a log begun is emptied and given its header, and its lines follow it at each writing") { + log_folder folder{"begin"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EU07-424", header); + logs.append("EU07-424", "0.0500 0.0000\r\n"); + CHECK(folder.read("EU07-424").empty()); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EU07-424", "0.1000 1.5000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n0.1000 1.5000\r\n"); + + // begun again: the lines not written yet are dropped along with those written + logs.append("EU07-424", "0.1500 3.0000\r\n"); + logs.begin("EU07-424", header); + logs.flush(); + CHECK(folder.read("EU07-424") == header); +} + +TEST_CASE("physicslog: no file is kept open between the writings, and a log not begun is added to as it stands") { + log_folder folder{"closed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("SM42-001", header); + logs.flush(); + // Windows doesn't let a file open in a program be removed. Linux does, so there it checks nothing; the log is + // written again below anyway + std::error_code error; + CHECK(std::filesystem::remove(folder.path() / "SM42-001.dat", error)); + CHECK_FALSE(error); + + logs.append("SM42-001", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SM42-001") == "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: the thread writes the logs by itself") { + log_folder folder{"thread"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("ET22-001", header); + logs.append("ET22-001", "0.0500 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n")); + logs.append("ET22-001", "0.1000 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n")); +} + +TEST_CASE("physicslog: stopping writes what is kept at once, and what comes after waits for a writing") { + log_folder folder{"stop"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EN57-1001", header); + logs.append("EN57-1001", "0.0500 0.0000\r\n"); + logs.stop(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EN57-1001", "0.1000 0.0000\r\n"); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { + log_folder folder{"closingwait"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.stop(); + // the writing of the stop, left behind, is waited for by the writer going + } + CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); +} + +TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { + log_folder folder{"failed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a folder in the way of the file: it can't be opened, as one held by another program + std::filesystem::create_directories(folder.path() / "EU07-005.dat"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("EU07-005", "0.1000 0.5000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-005.dat")); + + std::filesystem::remove(folder.path() / "EU07-005.dat"); + logs.append("EU07-005", "0.1500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { + log_folder folder{"failedvalues"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values second; + second.time = 0.10; + physicslog_values last; + last.time = 0.20; + std::filesystem::create_directories(folder.path() / "EU07-008.dat"); + logs.begin("EU07-008", header); + logs.append("EU07-008", first); + logs.flush(); + // given while the file can't be written: after the lines kept, as text and as values + logs.append("EU07-008", second); + logs.append("EU07-008", "text\r\n"); + logs.append("EU07-008", last); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); + + std::filesystem::remove(folder.path() / "EU07-008.dat"); + logs.flush(); + auto const text{folder.read("EU07-008")}; + CHECK(text.starts_with(std::string{header} + "0.0500 ")); + CHECK(text.find("\r\n0.1000 ") != std::string::npos); + CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); + CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); +} + +TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { + // the logs of a writing as the writer has them, by their names + std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; + std::vector *> order; + for (auto &log : taken) + order.push_back(&log); + physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); + std::vector names; + for (auto const *log : order) + names.push_back(log->first); + CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); +} + +TEST_CASE("physicslog: a log put first is written as the others are") { + log_folder folder{"first"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.put_first("SM42-002"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.begin("SM42-002", header); + logs.append("SM42-002", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { + log_folder folder{"failedbegun"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + std::filesystem::remove(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 2.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == std::string{header} + "0.0500 2.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written doesn't keep the others from theirs") { + log_folder folder{"failedother"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "EU07-006.dat"); + logs.begin("EU07-006", header); + logs.append("EU07-006", "0.0500 0.0000\r\n"); + logs.begin("EU07-007", header); + logs.append("EU07-007", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-006.dat")); + CHECK(folder.read("EU07-007") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a vehicle named in the code page of its scenery has its log, whatever the code page of the system") { + log_folder folder{"codepage"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // "SM42-Łódź" in 1250, as the sceneries have it: not UTF-8, which a Windows set to it would have thrown on + std::string const name{"SM42-\xA3\xF3" "d\x9F"}; // apart, or the d would be read as a digit of the \xF3 + logs.begin(name, header); + logs.append(name, "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(logs.file(name).parent_path() == folder.path()); + CHECK(log_folder::read_file(logs.file(name)) == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what no file name may have on Windows is replaced in the name of the file, on every system") { + log_folder folder{"filename"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a spawned vehicle's name has a ':', which on NTFS would write into a stream of the file "spawn_ezt" + CHECK(logs.file("spawn_ezt:12").filename() == "spawn_ezt_12.dat"); + CHECK(logs.file("ac\"d/e\\f|g?h*i\tj").filename() == "a_b_c_d_e_f_g_h_i_j.dat"); + CHECK(logs.file("EN57-1001 'a'.2").filename() == "EN57-1001 'a'.2.dat"); + // the devices of Windows, with an extension too, aren't files + CHECK(logs.file("nul").filename() == "_nul.dat"); + CHECK(logs.file("Com1.2").filename() == "_Com1.2.dat"); + CHECK(logs.file("con ").filename() == "_con .dat"); + CHECK(logs.file("console").filename() == "console.dat"); + CHECK(logs.file("com0").filename() == "com0.dat"); + CHECK(logs.shown("spawn_ezt:12") == folder.path().generic_string() + "/spawn_ezt_12.dat"); + + logs.begin("spawn_ezt:12", header); + logs.append("spawn_ezt:12", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("spawn_ezt_12") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(false == std::filesystem::exists(folder.path() / "spawn_ezt")); +} + +TEST_CASE("physicslog: stopping twice, from two threads at once, writes once and ends") { + log_folder folder{"stoptwice"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("EP09-001", header); + logs.append("EP09-001", "0.0500 0.0000\r\n"); + { + std::jthread other{[&logs] { logs.stop(); }}; + logs.stop(); + } + CHECK(folder.read("EP09-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a flush with a time limit writes, as flush does") { + log_folder folder{"flushfor"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("ET41-001", header); + logs.append("ET41-001", "0.0500 0.0000\r\n"); + CHECK(logs.flush_for(std::chrono::seconds{1})); + CHECK(folder.read("ET41-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what is kept is written when the writer goes") { + log_folder folder{"end"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + logs.begin("ST44-001", header); + logs.append("ST44-001", "0.0500 0.0000\r\n"); + } + CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { + log_folder folder{"after"}; + std::filesystem::create_directories(folder.path()); + { + std::ofstream before{folder.path() / "SU45-001.dat"}; + before << "earlier run\n"; + } + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("SU45-001", "0.1000 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { + using namespace std::chrono_literals; + using duration = std::chrono::steady_clock::duration; + // quick: the interval + CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); + CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); + // a third of the interval: still the interval + CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); + // longer: three times the writing, the disk busy with the logs a quarter of the time + CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); + // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still + CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); +} + +TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { + log_folder folder{"values"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values line; + line.time = 0.05; + line.wheelspeed = 1.23456; + line.acceleration = -0.5; + line.mainctrl = 3; + line.direction = 1; + line.command = "ShuntVelocity"; + line.value1 = 40.0; + // a float of the vehicle, widened as the stream widened it + line.enginetemperature = 50.1f; + line.vehiclespeed = 36.0; + logs.begin("SM31-001", header); + logs.append("SM31-001", line); + logs.flush(); + CHECK(folder.read("SM31-001") == std::string{header} + + "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " + "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); +} + +TEST_CASE("physicslog: lines given as values and as text are written in the order given") { + log_folder folder{"order"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values last; + last.time = 0.15; + logs.append("EP09-001", first); + logs.append("EP09-001", "text\r\n"); + logs.append("EP09-001", last); + logs.flush(); + auto const text{folder.read("EP09-001")}; + CHECK(text.starts_with("0.0500 ")); + CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); +} diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 11acb9b8f..48d10e8b1 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -578,6 +578,56 @@ TEST_CASE("utilities: a file is found by its name in another case") { CHECK(FileCased("eu07_unit_test_no_such_file.xyz").empty()); } +TEST_CASE("utilities: a file is found in folders named in another case, the way the parser gives the names in lowercase") { + test::scratch_folder const folder{"utilities_cased_folders"}; + folder.write("Scenery/Braniewo/rozklady/Os91121.txt", "x"); + folder.write("Textures/Tabl/L101-2m.BMP", "x"); + + // every part of the path in lowercase: the file as it's on the disk where the case matters, the name given where it doesn't + auto const timetable{FileCased(folder.path("scenery/braniewo/rozklady/os91121.txt"))}; + REQUIRE_FALSE(timetable.empty()); + CHECK(std::filesystem::exists(timetable)); + CHECK(ToLower(timetable) == ToLower(folder.path("Scenery/Braniewo/rozklady/Os91121.txt"))); + CHECK(FileOnDisk(folder.path("scenery/braniewo/rozklady/os91121.txt")) == timetable); + // the folders written the Windows way as well + CHECK_FALSE(FileCased(folder.path() + "scenery\\braniewo\\rozklady\\os91121.txt").empty()); + // a folder missing in any case + CHECK(FileCased(folder.path("scenery/nowhere/rozklady/os91121.txt")).empty()); + CHECK(FileOnDisk(folder.path("scenery/nowhere/rozklady/os91121.txt")) == folder.path("scenery/nowhere/rozklady/os91121.txt")); + + // among names and extensions: found in any case, given back as named, the name being the key of the banks + auto const texture{FileExists(std::vector{folder.path("textures/tabl/l101-2m")}, std::vector{".dds", ".bmp"})}; + REQUIRE_FALSE(texture.first.empty()); + CHECK(texture.first == folder.path("textures/tabl/l101-2m")); + CHECK(texture.second == ".bmp"); + CHECK(std::filesystem::exists(FileOnDisk(texture.first + texture.second))); + + // a file written after the folder was gone through is found as well + CHECK(FileCased(folder.path("textures/tabl/l7-2m.bmp")).empty()); + folder.write("Textures/Tabl/L7-2m.bmp", "x"); + auto const added{FileCased(folder.path("textures/tabl/l7-2m.bmp"))}; + REQUIRE_FALSE(added.empty()); + CHECK(std::filesystem::exists(added)); +} + +TEST_CASE("utilities: a terrain file is found in another case, by its text or by its binary file") { + test::scratch_folder const folder{"utilities_cased_terrain"}; + folder.write("Scenery/L204/Teren/Woda_ter.txtf", "x"); + folder.write("Scenery/Nmt/Gory_ter.btf", "x"); + auto const scenery{folder.path("Scenery/")}; + std::vector const extensions{".txtf", ".btf"}; + + // the name as the parser gives it: the files are there under the name given back, which differs only in case + auto const text{FileStemOnDisk(scenery, "l204/teren/woda_ter", extensions)}; + CHECK(ToLower(text) == "l204/teren/woda_ter"); + CHECK(std::filesystem::exists(scenery + text + ".txtf")); + auto const binary{FileStemOnDisk(scenery, "nmt/gory_ter", extensions)}; + CHECK(ToLower(binary) == "nmt/gory_ter"); + CHECK(std::filesystem::exists(scenery + binary + ".btf")); + // neither file in any case: the name stays as given + CHECK(FileStemOnDisk(scenery, "nmt/nowhere_ter", extensions) == "nmt/nowhere_ter"); +} + TEST_CASE("utilities: the time a file was changed is given, zero for a file which isn't there") { test::scratch_folder const folder{"utilities_modified"}; auto const name{folder.write("fresh.txt", "x")}; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index c6816f850..90c206dfa 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -381,6 +381,8 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to if (token == "gfxrenderer") { ParseOne(Parser, GfxRenderer); + // read in any case, as the starter does: "Legacy" written by hand is the legacy renderer + GfxRenderer = ToLower(GfxRenderer); if (GfxRenderer == "full") GfxRenderer = "default"; @@ -605,9 +607,18 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the physics logs of the trains only, of the drivers of rail vehicles; "physicslog yes" writes them all anyway + if (token == "physicslog.trains") + { + ParseOne(Parser, WriteTrainLogFlag); + return true; + } + if (token == "blackbox") { - ParseOne(Parser, BlackBox); + bool blackbox{false}; + ParseOne(Parser, blackbox); + BlackBox = blackbox; return true; } @@ -1872,7 +1883,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); - export_as_text( Output, "blackbox", BlackBox ); + export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + if( BlackBox ) { + export_as_text( Output, "blackbox", *BlackBox ); + } export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 7bb2833bc..ceb9948c4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,7 +119,9 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; - bool BlackBox{ true }; // with the physics logs on, the black box of the session is written as well (blackbox_doc.md) + // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" + // never, and with no entry it is written along with the physics logs + std::optional BlackBox; bool ShowSystemConsole{ false }; // toggle visibility of the OS console window with log output unsigned int DisabledLogTypes{ 0 }; bool ParserLogIncludes{ true }; diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp new file mode 100644 index 000000000..d37ea69e7 --- /dev/null +++ b/utilities/physicslog.cpp @@ -0,0 +1,491 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/physicslog.h" +#include "utilities/Logs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#endif + +physicslog_writer PhysicsLogs; + +namespace { + +// the most of all the logs kept while their files can't be written, shared by those, a log never less than the +// least: the oldest lines go beyond it +constexpr std::size_t keptwhilefailing{64 * 1024 * 1024}; +constexpr std::size_t keptwhilefailingleast{64 * 1024}; + +// the text cut to its last lines within Most +void keep_last(std::string &Text, std::size_t const Most) { + if (Text.size() <= Most) + return; + auto const cut{Text.find('\n', Text.size() - Most)}; + Text.erase(0, cut == std::string::npos ? Text.size() : cut + 1); +} + +// the name of the file of the log Name, its extension too. what no file name may have on Windows is replaced, on every +// system, so the logs are named alike everywhere: a spawned vehicle is named :, and on NTFS "a:1.dat" +// isn't even an error but the stream 1.dat of the file a, which nothing lists +std::string file_name(std::string const &Name) { + std::string name{Name}; + for (auto &character : name) { + if (static_cast(character) < 0x20 || std::string_view{R"(<>:"/\|?*)"}.find(character) != std::string_view::npos) + character = '_'; + } + // a device rather than a file, with any extension: con.dat is the console. told by the name before its first dot + auto stem{name.substr(0, name.find('.'))}; + while (false == stem.empty() && stem.back() == ' ') + stem.pop_back(); + std::ranges::transform(stem, stem.begin(), [](unsigned char const Character) { return static_cast(std::toupper(Character)); }); + auto const numbered{stem.size() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem[3] >= '1' && stem[3] <= '9'}; + if (numbered || stem == "CON" || stem == "PRN" || stem == "AUX" || stem == "NUL") + name.insert(0, 1, '_'); + return name + ".dat"; +} + +// told in the log of the simulator, if there's the memory for it +void tell(std::string const &Text) noexcept { + try { + ErrorLog(Text); + } catch (...) { + // out of memory for a line of the log too: nothing more to be done about it + } +} + +// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the +// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking +// when there are hundreds of them +void lower_disk_priority() noexcept { +#ifdef _WIN32 + // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of + // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a + // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without + // end. a thread which can't have it writes as it did before + static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); +#elif defined(__linux__) && defined(SYS_ioprio_set) + // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the + // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has + constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 + constexpr int classbesteffort{2}; + constexpr int classshift{13}; + constexpr int lowest{7}; + static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); +#endif +} + +} // namespace + +void physicslog_values::append_to(std::string &Text) const { + std::ostringstream line; + line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " + << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " + << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " + << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " + << wateraux << " " << vehiclespeed << "\r\n"; + Text.append(line.str()); +} + +void physicslog_writer::pending::to_text() { + if (values.empty()) + return; + // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was + std::string lines; + for (auto const &line : values) + line.append_to(lines); + text.append(lines); + values.clear(); +} + +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} + +physicslog_writer::~physicslog_writer() { + try { + stop(); + // the writings left behind by the stops use the object, which goes + std::vector> closings; + { + std::scoped_lock lock{m_mutex}; + closings.swap(m_closings); + } + for (auto const &closing : closings) + closing.wait(); + } catch (...) { + // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse + } +} + +void physicslog_writer::begin(std::string const &Name, std::string_view const Header) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + lines.fresh = true; + lines.header.assign(Header); + lines.text.clear(); + lines.values.clear(); + start(); +} + +void physicslog_writer::append(std::string const &Name, std::string_view const Line) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + // after the lines given as values before it + lines.to_text(); + lines.text.append(Line); + start(); +} + +void physicslog_writer::append(std::string const &Name, physicslog_values Values) { + std::scoped_lock lock{m_mutex}; + m_pending[Name].values.push_back(std::move(Values)); + start(); +} + +void physicslog_writer::put_first(std::string const &Name) { + std::scoped_lock lock{m_mutex}; + m_first.insert(Name); +} + +void physicslog_writer::flush() { + std::scoped_lock files{m_filemutex}; + write(writing::flush); +} + +bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { + // on a thread of its own, left behind if it doesn't end in time: a disk which doesn't answer holds it up in the + // writing, not only the lock. for the end of the process, which doesn't wait for it + auto done{std::make_shared>()}; + auto ended{done->get_future()}; + std::thread([this, done] { + flush_safely(writing::flush); + done->set_value(); + }).detach(); + return ended.wait_for(Timeout) == std::future_status::ready; +} + +void physicslog_writer::stop() { + std::jthread thread; + bool itself; + closing_time closeby; + { + std::scoped_lock lock{m_mutex}; + m_stopped = true; + // taken by the first to stop, so it's joined once + thread = std::move(m_thread); + itself = m_writer == std::this_thread::get_id(); + // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun + // ends at the log at hand, leaving the others to it + closeby = closing_begun(); + } + // the stop asked outside the lock, which waking the writer takes + if (thread.joinable()) + thread.request_stop(); + // stopped from the writer itself, by the end of a run which failed in it: the files may be held by it + if (itself) { + if (thread.joinable()) + thread.detach(); + return; + } + if (close_aside(thread, closeby)) + return; + // no thread for it, out of memory say: written here, the logs past the time dropped all the same + if (thread.joinable()) + thread.join(); + flush_safely(writing::closing); +} + +physicslog_writer::closing_time physicslog_writer::closing_begun() { + std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); + // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the + // longer, nor give the writing of the first more of it + if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) + return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; + auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; + m_closeby = closeby.time_since_epoch().count(); + return {closeby, true}; +} + +bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { + // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which + // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, + // the writing with it + auto started{false}; + try { + auto done{std::make_shared>()}; + std::shared_future const closing{done->get_future()}; + { + std::scoped_lock lock{m_mutex}; + m_closings.push_back(closing); + } + // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it + std::thread([this, done, writer = std::move(Thread)]() mutable { + if (writer.joinable()) + writer.join(); + flush_safely(writing::closing); + done->set_value(); + }).detach(); + started = true; + // told by the stop which gave the time, not again by one after it + if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) + tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", + std::chrono::duration{m_closingwait}.count())); + return true; + } catch (...) { + // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun + // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it + return started; + } +} + +std::filesystem::path physicslog_writer::file(std::string const &Name) const { + auto const name{file_name(Name)}; +#ifdef _WIN32 + // in the code page of the system, as the standard library would convert it, but with the bytes not of it replaced + // instead of an exception thrown: a vehicle of a scenery written in 1250 on a Windows set to UTF-8, say + auto const size{static_cast(name.size())}; + std::wstring wide(static_cast(::MultiByteToWideChar(CP_ACP, 0, name.data(), size, nullptr, 0)), L'\0'); + ::MultiByteToWideChar(CP_ACP, 0, name.data(), size, wide.data(), static_cast(wide.size())); + return m_folder / wide; +#else + // the bytes are the name of the file as they are + return m_folder / name; +#endif +} + +std::string physicslog_writer::shown(std::string const &Name) const { + return m_shownfolder + '/' + file_name(Name); +} + +std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { + // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the + // waits growing with no end, and a crash would lose more of them + return std::clamp(Took * 3, Interval, Interval * 5); +} + +void physicslog_writer::start() { + if (m_stopped || m_thread.joinable()) + return; + m_thread = std::jthread([this](std::stop_token const &Stop) { run(Stop); }); + m_writer = m_thread.get_id(); +} + +void physicslog_writer::run(std::stop_token const &Stop) { + lower_disk_priority(); + // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is + // either about to wait, and sees the stop, or waiting already + std::stop_callback const wake{Stop, [this] { + { std::scoped_lock lock{m_mutex}; } + m_wake.notify_all(); + }}; + std::chrono::steady_clock::duration wait{m_interval}; + while (false == Stop.stop_requested()) { + { + std::unique_lock lock{m_mutex}; + // woken early only to stop, which writes the rest itself + if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + return; + } + auto const start{std::chrono::steady_clock::now()}; + // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's + auto const logs{flush_safely(writing::thread)}; + auto const took{std::chrono::steady_clock::now() - start}; + wait = wait_after(m_interval, took); + if (wait > m_interval && false == m_slowtold) { + m_slowtold = true; + using seconds = std::chrono::duration; + try { + WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " + "written less often from now on, every {:.1f} s at most", + logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); + } catch (...) { + // out of memory for a line of the log: the logs are written all the same + } + } + } +} + +std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { + try { + std::scoped_lock files{m_filemutex}; + return write(Mode); + } catch (std::exception const &Error) { + tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); + } catch (...) { + tell("Bad physics log: the writing failed, the lines taken for it are lost"); + } + return 0; +} + +bool physicslog_writer::past_closing() const { + auto const closeby{m_closeby.load()}; + return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; +} + +void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; + for (auto &[name, lines] : Failed) { + // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as + // text they go before what came since + try { + lines.to_text(); + } catch (std::exception const &) { + // kept as values, below + } + keep_last(lines.text, most); + } + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : Failed) + put_back(name, lines); + for (auto *log : Left) + put_back(log->first, log->second); +} + +void physicslog_writer::put_back(std::string const &Name, pending &Lines) { + auto &now{m_pending[Name]}; + // a log begun anew since drops them + if (now.fresh) + return; + // the lines in the order given: those kept, then those come since, as text and as values. values kept before text + // come since are made into text first, as those before a line given as text are; values which can't be, out of + // memory, are dropped then, as the order can't be kept otherwise + if (false == now.text.empty() && false == Lines.values.empty()) { + try { + Lines.to_text(); + } catch (std::exception const &) { + Lines.values.clear(); + } + } + Lines.text.append(now.text); + // added at once, allocated first: one failing moves none of them + if (Lines.values.empty()) + Lines.values = std::move(now.values); + else + Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); + now = std::move(Lines); +} + +std::size_t physicslog_writer::write(writing const Mode) { + std::map taken; + std::set first; + std::vector *> order; + { + std::scoped_lock lock{m_mutex}; + if (m_pending.empty()) + return 0; + // a stop come before the thread's writing: the lines are all the closing's, left as they are + if (Mode == writing::thread && m_closeby.load() != 0) + return 0; + // had before the lines are taken: without the memory for it they're left for the next writing + first = m_first; + order.reserve(m_pending.size()); + taken.swap(m_pending); + } + auto const logs{taken.size()}; + std::error_code error; + std::filesystem::create_directories(m_folder, error); + std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); + writing_order(order, first); + std::map failed; + std::size_t dropped{0}; + std::size_t reached{0}; + for (auto *log : order) { + // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has + // them with the lines given since, those put first first + if (Mode == writing::thread && m_closeby.load() != 0) + break; + ++reached; + auto &[name, lines]{*log}; + // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer + if (Mode == writing::closing && past_closing()) { + ++dropped; + continue; + } + if (false == write_taken(name, lines)) + failed.emplace(name, std::move(lines)); + } + if (dropped > 0) + tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, + std::chrono::duration{m_closingwait}.count())); + // what is left of the order: the logs the thread hasn't come to + order.erase(order.begin(), order.begin() + static_cast(reached)); + if (false == failed.empty() || false == order.empty()) + keep(failed, order); + return logs; +} + +bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + // the text of the lines given as values, here on the writer's thread rather than the simulation's + Lines.to_text(); + if (Lines.text.empty() && false == Lines.fresh) + return true; + written = write_log(Name, Lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(Name) > 0) + WriteLog("Physics log: " + shown(Name) + " written again"); + return true; + } + if (m_failed.insert(Name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); + return false; +} + +bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { + auto const path{file(Name)}; + // one write to the file: the header of a log begun with its lines, not the one after the other + std::string begun; + if (Lines.fresh) + begun = Lines.header + Lines.text; + std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". + // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines + // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't + // asked for the length before, one access less of hundreds of logs + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; + if (false == stream.is_open()) + return false; + auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; + stream.write(text.data(), static_cast(text.size())); + stream.close(); + if (false == stream.fail()) + return true; + // a log begun is written anew from its header the next time anyway + if (false == Lines.fresh && before >= 0) { + std::error_code error; + std::filesystem::resize_file(path, static_cast(before), error); + } + return false; +} diff --git a/utilities/physicslog.h b/utilities/physicslog.h new file mode 100644 index 000000000..286df7e87 --- /dev/null +++ b/utilities/physicslog.h @@ -0,0 +1,189 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which +// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty +// lines a second each. the columns as physicslog_header of the driver names them +struct physicslog_values { + double time{0.0}; + double wheelspeed{0.0}; + double acceleration{0.0}; + double couplerdistance{0.0}; + double couplerforce{0.0}; + double tractionforce{0.0}; + double frictionforce{0.0}; + double brakeforce{0.0}; + double brakepressure{0.0}; + double pipepressure{0.0}; + double motorcurrent{0.0}; + int mainctrl{0}; + int scndctrl{0}; + double brakectrl{0.0}; + double localbrake{0.0}; + int direction{0}; + std::string command; + double value1{0.0}; + double value2{0.0}; + int security{0}; + int wheelslip{0}; + double enginetemperature{0.0}; + double oiltemperature{0.0}; + double watertemperature{0.0}; + double wateraux{0.0}; + double vehiclespeed{0.0}; + + // the line, as the logs always had it, at the end of Text + void append_to(std::string &Text) const; +}; + +// the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's +// has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, +// each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk +// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next +// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the +// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind +// them. the closing waits for the writing a second at most (below) +class physicslog_writer { +public: + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, + std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + physicslog_writer(physicslog_writer const &) = delete; + physicslog_writer &operator=(physicslog_writer const &) = delete; + // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, + // global, never goes this way: the process ends with _Exit + ~physicslog_writer(); + + // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. + // the lines of it not written yet are dropped + void begin(std::string const &Name, std::string_view Header); + // Line at the end of the log Name. a log not begun is added to as its file stands + void append(std::string const &Name, std::string_view Line); + // the same, a line of the values, made into text by the writer's thread when it writes the log + void append(std::string const &Name, physicslog_values Values); + // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the + // tested trains, which a closing short of time would otherwise drop by the order of their names + void put_first(std::string const &Name); + // writes what is kept, now + void flush(); + // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left + // behind. for the end of the process, the files held up or the disk not answering + bool flush_for(std::chrono::milliseconds Timeout); + // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by + // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a + // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with + // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + void stop(); + // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name + // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a + // scenery (1250) stay as they are, also on a Windows set to UTF-8, where the standard library would throw making a + // path of them: there they become U+FFFD + std::filesystem::path file(std::string const &Name) const; + // the same, for the log of the simulator + std::string shown(std::string const &Name) const; + // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long + // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the + // logs a quarter of the time rather than all of it, and their lines wait in memory the longer + static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); + // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: + // those put first (First) before the others, each in the order they were + template static void writing_order(std::vector &Logs, std::set const &First) { + std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); + } + +private: + // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the + // closing's, which drops the logs past the time the stop gives it + enum class writing { flush, thread, closing }; + + // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way + struct closing_time { + std::chrono::steady_clock::time_point by; + bool fresh{true}; + }; + + struct pending { + bool fresh{false}; // its file is to be emptied first, and the header written into it + std::string header; + std::string text; + // the lines given as values since, after the text: made into text when written + std::vector values; + + // the lines of the values at the end of the text + void to_text(); + }; + + // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held + closing_time closing_begun(); + // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no + // thread could be had for it, out of memory say; Thread may be the writer still then + bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; + // the thread, on the first line given, unless stopped. called with m_mutex held + void start(); + void run(std::stop_token const &Stop); + // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. + // returns: the number of logs there were to write + std::size_t flush_safely(writing Mode) noexcept; + // called with m_filemutex held. returns: the number of logs there were to write + std::size_t write(writing Mode); + // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if + // it wasn't, its lines to be kept for the next try + bool write_taken(std::string const &Name, pending &Lines); + // whether the time a stop gave the writing is over + bool past_closing() const; + // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, + // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as + // they were taken: their values are made into text by that writing, which drops them past its time, not on the way + // unless text was given since + void keep(std::map &Failed, std::vector *> const &Left); + // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held + void put_back(std::string const &Name, pending &Lines); + // the lines of the log Name written into its file. returns: true if they all were + bool write_log(std::string const &Name, pending const &Lines) const; + + std::filesystem::path const m_folder; + std::string const m_shownfolder; + std::chrono::milliseconds const m_interval; + std::chrono::milliseconds const m_closingwait; + // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop + std::atomic m_closeby{0}; + std::mutex m_mutex; // the lines kept and the thread + std::map m_pending; + std::set m_first; // the logs put first + bool m_stopped{false}; + std::condition_variable m_wake; + std::jthread m_thread; + std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it + std::vector> m_closings; // the writings of the stops, which may outlast them + std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order + std::set m_failed; // the logs whose file couldn't be written, told once + bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own +}; + +// the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles +extern physicslog_writer PhysicsLogs; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 238e276f5..edc694852 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -633,6 +633,140 @@ bool FileExists(std::string const &Filename) return std::filesystem::exists(Filename); } +#ifndef _WIN32 +namespace +{ + +// the names in a folder by their lowercase, the time the folder was changed and the time they were read +struct cased_folder +{ + bool read{false}; + std::filesystem::file_time_type changed{}; + std::filesystem::file_time_type listed{}; + // when the time of the change was last looked at + std::chrono::steady_clock::time_point checked{}; + std::unordered_map names; +}; + +std::mutex cased_mutex; +std::unordered_map cased_folders; +// a folder by the name it's given with (parts split by '/', a '/' at the end): as it's named on the disk, or missing in any case +// since the time given +struct cased_path +{ + std::string name; + bool missing{false}; + std::chrono::steady_clock::time_point checked{}; +}; +std::unordered_map cased_paths; + +// the names in the folder into Cached by their lowercase, with the time the folder was changed and the time they were read. a named +// function rather than a lambda capturing Cached, which Sonar takes for a reference to null (S2259) +void read_cased_folder(cased_folder &Cached, std::filesystem::path const &Folder, std::filesystem::file_time_type const Changed) +{ + Cached.names.clear(); + Cached.changed = Changed; + Cached.listed = std::filesystem::file_time_type::clock::now(); + std::error_code error; + for (std::filesystem::directory_iterator entry{Folder, error}, end; (false == bool(error)) && (entry != end); entry.increment(error)) + { + auto const name{entry->path().filename().string()}; + Cached.names.try_emplace(ToLower(name), name); + } + // a listing cut short isn't kept + Cached.read = (false == bool(error)); +} + +// the name in the folder matching the one given in any case, empty when there's none. the folder is read again once it was +// changed, as the editor writes files while it runs, the time of the change looked at once a second at most, which keeps a +// missing file as cheap as a single check; a name missing from a folder changed shortly before it was read is looked for again, +// the time of the change being as coarse as the clock of the file system. to be called with cased_mutex held +std::string cased_name(std::string const &Folder, std::string const &Name) +{ + std::filesystem::path const folder{Folder.empty() ? std::string{"."} : Folder}; + std::error_code error; + auto &cached{cased_folders[Folder]}; + auto const now{std::chrono::steady_clock::now()}; + auto changed{cached.changed}; + if ((false == cached.read) || (now - cached.checked >= std::chrono::seconds{1})) + { + changed = std::filesystem::last_write_time(folder, error); + if (error) + { + // a folder found before may have been renamed or removed since + cased_folders.erase(Folder); + cased_paths.clear(); + return {}; + } + cached.checked = now; + } + auto const wanted{ToLower(Name)}; + if ((false == cached.read) || (cached.changed != changed)) + read_cased_folder(cached, folder, changed); + auto found{cached.names.find(wanted)}; + // a folder changed in the future, as from another clock, isn't read again on every miss + if (auto const age{cached.listed - cached.changed}; (found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) + { + read_cased_folder(cached, folder, changed); + found = cached.names.find(wanted); + } + return found != cached.names.end() ? found->second : std::string{}; +} + +// keeps the folder by the name it's given with as Name, or as missing since the time given when Name is empty, and puts Name into +// Cased; false when it's missing +bool keep_cased_path(std::string const &Folder, std::string const &Name, std::chrono::steady_clock::time_point const Now, std::string &Cased) +{ + auto &path{cased_paths[Folder]}; + path.name = Name; + path.missing = Name.empty(); + path.checked = Now; + Cased = Name; + return false == Name.empty(); +} + +// the folder as it's named on the disk into Cased, from the one given with '/' between its parts and at its end ("" the current +// folder); false when it's missing in any case. the folders found are kept, and the missing ones for a second, so a file missing +// costs a check of its folder alone. to be called with cased_mutex held +bool cased_folder_path(std::string const &Folder, std::string &Cased) +{ + if (Folder.empty() || (Folder == "/")) + { + Cased = Folder; + return true; + } + auto const now{std::chrono::steady_clock::now()}; + if (auto const found{cased_paths.find(Folder)}; found != cased_paths.end()) + { + if (false == found->second.missing) + { + Cased = found->second.name; + return true; + } + if (now - found->second.checked < std::chrono::seconds{1}) + return false; + } + std::error_code error; + if (std::filesystem::is_directory(Folder, error)) + { + // named as it is on the disk + return keep_cased_path(Folder, Folder, now, Cased); + } + // the parent, then the last part among the names in it + auto const last{Folder.size() - 1}; + auto const split{Folder.rfind('/', last - 1)}; + auto const parent{split == std::string::npos ? std::string{} : Folder.substr(0, split + 1)}; + auto const part{Folder.substr(parent.size(), last - parent.size())}; + std::string casedparent; + if (false == cased_folder_path(parent, casedparent)) + return keep_cased_path(Folder, {}, now, Cased); + auto const name{((part == ".") || (part == "..")) ? part : cased_name(casedparent, part)}; + return keep_cased_path(Folder, name.empty() ? std::string{} : casedparent + name + '/', now, Cased); +} + +} // namespace +#endif + std::string FileCased(std::filesystem::path const &Filename) { std::error_code error; @@ -643,16 +777,59 @@ std::string FileCased(std::filesystem::path const &Filename) // code page to throw on return {}; #else - // only the name of the file itself, a folder named in another case isn't found - auto const directory{Filename.has_parent_path() ? Filename.parent_path() : std::filesystem::path{"."}}; - auto const wanted{ToLower(Filename.filename().string())}; - for (std::filesystem::directory_iterator entry{directory, error}, end; entry != end; entry.increment(error)) - if (ToLower(entry->path().filename().string()) == wanted) - return Filename.has_parent_path() ? (directory / entry->path().filename()).string() : entry->path().filename().string(); - return {}; + // the folder, then the file in it: the folders can be named in another case as well as the file + auto text{Filename.string()}; + std::replace(text.begin(), text.end(), '\\', '/'); + std::string folder{(false == text.empty()) && (text.front() == '/') ? "/" : ""}; + std::string file; + for (std::size_t start{0}; start < text.size();) + { + auto end{text.find('/', start)}; + if (end == std::string::npos) + end = text.size(); + if (end > start) + { + if (false == file.empty()) + folder += file + '/'; + file = text.substr(start, end - start); + } + start = end + 1; + } + if (file.empty()) + return {}; + std::string cased; + { + std::scoped_lock const lock{cased_mutex}; + if (false == cased_folder_path(folder, cased)) + return {}; + auto const name{((file == ".") || (file == "..")) ? file : cased_name(cased, file)}; + if (name.empty()) + return {}; + cased += name; + } + return std::filesystem::exists(cased, error) ? cased : std::string{}; #endif } +std::string FileOnDisk(std::string const &Filename) +{ + auto cased{FileCased(Filename)}; + return cased.empty() ? Filename : cased; +} + +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions) +{ + for (auto const &extension : Extensions) + { + auto const cased{FileCased(Folder + Name + extension)}; + if (cased.size() > Folder.size() + extension.size() && cased.starts_with(Folder) && cased.ends_with(extension)) + { + return cased.substr(Folder.size(), cased.size() - Folder.size() - extension.size()); + } + } + return Name; +} + std::pair FileExists(std::vector const &Names, std::vector const &Extensions) { @@ -660,7 +837,8 @@ std::pair FileExists(std::vector const &N { for (auto const &extension : Extensions) { - if (FileExists(name + extension)) + // found in any case, given back as named here: the name stays the key of the banks, the file is opened by FileOnDisk() + if (false == FileCased(name + extension).empty()) { return {name, extension}; } diff --git a/utilities/utilities.h b/utilities/utilities.h index 7e3a227f1..25ee3882c 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -233,10 +233,17 @@ template bool extract_value(Type_ &Variable, std::string const template <> bool extract_value(bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default); bool FileExists(std::string const &Filename); -// the file as it's named on the disk when only the case of its name differs, as in the sceneries made on Windows; empty when -// there's none. the folders have to be named in their case; on Windows, finding the names in any case itself, the file given or none +// the file as it's named on the disk when only the case of its name or of its folders differs, as in the sceneries made on Windows; +// empty when there's none. on Windows, finding the names in any case itself, the file given or none std::string FileCased(std::filesystem::path const &Filename); +// the file to open: as it's named on the disk, the name given when there's none +std::string FileOnDisk(std::string const &Filename); +// the name (relative to the folder, without extension) as it's named on the disk with the first of the extensions it has a file with, +// found in any case; the name given when there's none +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions); +// the first name with one of the extensions which has a file in any case, in the order given; given back as named here, the file +// is opened by FileOnDisk() std::pair FileExists(std::vector const &Names, std::vector const &Extensions); // returns time of last modification for specified file diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index bfa0e70c7..2b3633433 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" @@ -170,6 +171,7 @@ const double FSOverchargeCRP = 0.05; const double FSMaxTime = 10.0; const double DepartBlockedFSDelay = 10.0; bool WriteLogFlag = false; +bool WriteTrainLogFlag = false; double const deltalog = 0.05; // przyrost czasu std::string StopReasonTable[] = { @@ -2339,33 +2341,16 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd } - SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + if( mvOccupied != nullptr ) { + SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + } TableClear(); - if( WriteLogFlag ) { -#ifdef _WIN32 - CreateDirectory( "physicslog", nullptr); -#elif __unix__ - mkdir( "physicslog", 0740 ); -#endif - LogFile.open( std::string( "physicslog/" + VehicleName + ".dat" ), - std::ios::in | std::ios::out | std::ios::trunc ); -#if LOGPRESS == 0 - LogFile - << "Time[s] Velocity[m/s] Acceleration[m/ss] " - << "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " - << "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " - << "MCP SCP BCP LBP Direction Command CVal1 CVal2 " - << "Security Wheelslip " - << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " - << "VehicleVelocity[km/h]" - << "\r\n"; - LogFile << std::fixed << std::setprecision( 4 ); -#endif -#if LOGPRESS == 1 - LogFile << string( "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP" ).c_str() << "\n"; -#endif - LogFile.flush(); + // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line + // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles + // are made passive before it starts, so they get no file with only the header + if( WriteLogFlag && false == drives_road_vehicle() ) { + begin_physicslog(); } // HACK: give the simulation a small window to potentially replace the AI with a human driver @@ -2374,7 +2359,6 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, TController::~TController() { // wykopanie mechanika z roboty - // LogFile is closed by its own destructor }; // zamiana kodu rozkazu na opis @@ -5390,58 +5374,80 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N return false; // nierozpoznana - wysłać bezpośrednio do pojazdu }; -void TController::PhysicsLog() -{ // zapis logu - na razie tylko wypisanie parametrów - if (LogFile.is_open()) - { +std::string_view TController::physicslog_header() { + // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: + // a new one goes at the end + return "Time[s] Velocity[m/s] Acceleration[m/ss] " + "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " + "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " + "MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip " + "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + "VehicleVelocity[km/h]" + "\r\n"; +} + +physicslog_values TController::physicslog_line() const { + // the values only: the writer of the logs makes them into text on its own thread + physicslog_values line; + line.time = ElapsedTime; + line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); + line.acceleration = mvControlling->AccS; + line.couplerdistance = mvOccupied->Couplers[1].Dist; + line.couplerforce = mvOccupied->Couplers[1].CForce; + line.tractionforce = mvOccupied->Ft; + line.frictionforce = mvOccupied->Ff; + line.brakeforce = mvOccupied->Fb; + line.brakepressure = mvOccupied->BrakePress; + line.pipepressure = mvOccupied->PipePress; + line.motorcurrent = mvControlling->Im; + line.mainctrl = static_cast(mvControlling->MainCtrlPos); + line.scndctrl = static_cast(mvControlling->ScndCtrlPos); + line.brakectrl = mvOccupied->fBrakeCtrlPos; + line.localbrake = mvOccupied->LocalBrakePosA; + line.direction = static_cast(mvControlling->DirActive); + line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); + line.value1 = mvOccupied->CommandIn.Value1; + line.value2 = mvOccupied->CommandIn.Value2; + line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); + line.wheelslip = static_cast(mvControlling->SlippingWheels); + // floats, as the stream wrote them: widened to double + line.enginetemperature = mvControlling->dizel_heat.Ts; + line.oiltemperature = mvControlling->dizel_heat.To; + line.watertemperature = mvControlling->dizel_heat.temperatura1; + line.wateraux = mvControlling->dizel_heat.temperatura2; + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + line.vehiclespeed = mvOccupied->V * 3.6; + return line; +} + +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers #if LOGPRESS == 0 -/* -<< "Time[s] Velocity[m/s] Acceleration[m/ss] " -<< "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " -<< "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " -<< "MCP SCP BCP LBP DmgFlag Command CVal1 CVal2 " -<< "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]" -*/ - LogFile - << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " - << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " - << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << mvOccupied->V * 3.6 - << "\r\n"; + PhysicsLogs.begin( VehicleName, physicslog_header() ); #endif #if LOGPRESS == 1 - LogFile << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) - << "\t"; - LogFile << Controlling->AccS << "\t"; - LogFile << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - LogFile << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); +#endif + PhysicsLogBegun = true; +} + +void TController::PhysicsLog() +{ // zapis logu - na razie tylko wypisanie parametrów +#if LOGPRESS == 0 + PhysicsLogs.append( VehicleName, physicslog_line() ); +#endif +#if LOGPRESS == 1 + std::ostringstream line; + line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) + << "\t"; + line << mvControlling->AccS << "\t"; + line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" + << mvOccupied->BrakePress << "\t"; + line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.append( VehicleName, line.str() ); #endif - LogFile.flush(); - } }; void @@ -6392,6 +6398,10 @@ void TController::ControllingSet() // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT + if( pVehicle == nullptr ) { + // a driver of no vehicle has nothing to control + return; + } mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego @@ -6493,10 +6503,18 @@ TController::update_timers( double dt ) { void TController::update_logs( double const dt ) { // log vehicle data + if( false == writes_physicslog() ) { + // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, + // it would write a line every 0.05 s from then on, not one each update to make up for the time before + LastUpdatedTime = 0.0; + return; + } LastUpdatedTime += dt; - if( WriteLogFlag - && LastUpdatedTime > deltalog ) { + if( LastUpdatedTime > deltalog ) { // zapis do pliku DAT + if( false == PhysicsLogBegun ) { + begin_physicslog(); + } PhysicsLog(); LastUpdatedTime -= deltalog; } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 2ed51b6a1..113be3b94 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include "utilities/Classes.h" #include "utilities/utilities.h" #include "MOVER.h" @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" +#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -197,6 +199,9 @@ static const bool Humandriver = false; static const int maxorders = 64; // ilość rozkazów w tabelce static const int maxdriverfails = 4; // ile błędów może zrobić AI zanim zmieni nastawienie extern bool WriteLogFlag; // logowanie parametrów fizycznych +// the physics logs of the trains only (physicslog.trains yes): of each driver of rail vehicles who drives them, not +// of the passengers nor of the vehicles of the roads +extern bool WriteTrainLogFlag; static const int BrakeAccTableSize = 20; static const int gbh_NP = -2; //odciecie w hamulcu ogolnym @@ -721,9 +726,12 @@ private: // logs // methods + // the line of the log, to PhysicsLogs (utilities/physicslog.h) void PhysicsLog(); + // its log begun anew, its file emptied and given the header + void begin_physicslog(); // members - std::ofstream LogFile; // zapis parametrow fizycznych + bool PhysicsLogBegun = false; // its log was begun, by this driver double LastUpdatedTime = 0.0; // czas od ostatniego logu double ElapsedTime = 0.0; // czas od poczatku logu @@ -731,6 +739,22 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } + // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with + // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. + // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + std::string const &physicslog_name() const { + return VehicleName; } + // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with + // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of + // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes + // the log of one the user is in + bool writes_physicslog() const { + return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } + // a driver of a road vehicle; not one of no vehicle + bool drives_road_vehicle() const { + return mvOccupied != nullptr && is_car(); } + static std::string_view physicslog_header(); + physicslog_values physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index 8612df1bd..fc05f7483 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -205,6 +205,7 @@ void writer::cab(cab_sample const &Sample) { out.f32(Sample.clutch); out.f32(Sample.converter_fill); out.f32(Sample.consist_brake_cylinder); + out.f32(Sample.wheel_speed_kmh); emit(record::cab); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 58735ff60..55ee06ca3 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -257,6 +257,9 @@ struct cab_sample { float clutch{0.0f}; // the clutch of a diesel's gearbox, 0 open .. 1 closed float converter_fill{0.0f}; // the filling of a diesel's hydraulic torque converter, 0..1 float consist_brake_cylinder{0.0f}; // the highest brake cylinder pressure of the vehicles of the train [bar] + // [km/h] of the wheels as they turn, which the speedometer shows, signed as speed_kmh: apart from it while the wheels + // slip, and 0 while they are locked in a skid + float wheel_speed_kmh{0.0f}; }; // a station of the timetable of the user's train; the times in minutes of the day, -1 none @@ -354,7 +357,7 @@ struct signal_passing { // sizes of the parts of fixed size, as the readers expect them inline constexpr std::size_t header_size{12}; inline constexpr std::size_t record_header_size{5}; -inline constexpr std::size_t cab_sample_size{190}; +inline constexpr std::size_t cab_sample_size{194}; inline constexpr std::size_t vehicle_state_size{25}; // writes the records to a stream. nothing is written until header() is diff --git a/world/mtable.cpp b/world/mtable.cpp index ce10eaafd..23a48e3a7 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -310,6 +310,15 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach // (kolejny pociąg dostaje numer +2) fin.open(s.c_str()); // otwieranie pliku + if (false == fin.is_open()) + { + // the name of the train comes in lowercase, the file can be named in another case + if (auto const cased{FileCased(s)}; false == cased.empty()) + { + fin.clear(); + fin.open(cased); + } + } replace_slashes(s); if (!fin.is_open())