From 0ce190eab2e4e87654f5fb970115ddd1d2cec232 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 09:15:11 +0100 Subject: [PATCH] fix: the review of the renderers PR: physics switches off by default, crashes on exit and at start, renderer, shader and editor fixes --- .github/workflows/coverage.yml | 6 +- .github/workflows/shaders.yml | 2 + .gitignore | 3 + CMakeLists.txt | 62 ++++- McZapkie/MOVER.h | 4 + McZapkie/Mover.cpp | 49 +++- McZapkie/hamulce.h | 7 + application/application.cpp | 74 +++++- application/editormode.cpp | 73 ++++-- application/editormodecatenary.cpp | 72 +++++- application/editormodecatenary.h | 3 + audio/radiostream.cpp | 2 +- audio/radiostream.h | 6 +- ci_shadervalidator/build.sh | 5 +- ci_shadervalidator/main.cpp | 269 ++++++++++++++++++-- environment/weather.cpp | 7 +- gl/streambuffer.cpp | 34 ++- lang/editor_pl.po | 9 + model/Model3d.cpp | 3 +- rendering/common/cabprobe.h | 2 +- rendering/common/exposure.h | 5 +- rendering/common/instancecull.h | 4 +- rendering/common/locallights.cpp | 13 +- rendering/common/locallights.h | 4 + rendering/common/localshadows.h | 4 +- rendering/common/scenewalk.cpp | 2 +- rendering/common/scenewalk.h | 4 +- rendering/common/scenewalkindirect.cpp | 2 +- rendering/common/shadersource.cpp | 6 + rendering/common/shadersource.h | 4 +- rendering/common/skylight.h | 4 +- rendering/common/skyocclusion.h | 4 +- rendering/common/walksync.h | 2 +- rendering/common/weatherstate.h | 4 +- rendering/opengl46/opengl46ao.cpp | 22 +- rendering/opengl46/opengl46ao.h | 3 +- rendering/opengl46/opengl46cabprobe.cpp | 43 +++- rendering/opengl46/opengl46cabprobe.h | 3 +- rendering/opengl46/opengl46exposure.cpp | 38 ++- rendering/opengl46/opengl46exposure.h | 3 +- rendering/opengl46/opengl46hiz.cpp | 19 +- rendering/opengl46/opengl46hiz.h | 3 +- rendering/opengl46/opengl46instancecull.cpp | 25 +- rendering/opengl46/opengl46instancecull.h | 8 +- rendering/opengl46/opengl46localshadows.cpp | 57 ++++- rendering/opengl46/opengl46localshadows.h | 5 +- rendering/opengl46/opengl46renderer.cpp | 127 ++++++--- rendering/opengl46/opengl46shadowfit.cpp | 21 +- rendering/opengl46/opengl46shadowfit.h | 3 +- rendering/opengl46/opengl46sky.cpp | 38 ++- rendering/opengl46/opengl46sky.h | 3 +- rendering/opengl46/opengl46timbers.cpp | 76 +++++- rendering/opengl46/opengl46timbers.h | 14 +- rendering/opengl46/opengl46weather.cpp | 50 +++- rendering/opengl46/opengl46weather.h | 3 +- rendering/vulkan14/vulkan14context.h | 10 +- rendering/vulkan14/vulkan14frame.cpp | 14 +- rendering/vulkan14/vulkan14raytracing.h | 6 + rendering/vulkan14/vulkan14renderer.cpp | 70 ++++- rendering/vulkan14/vulkan14renderer.h | 2 +- rendering/vulkan14/vulkan14scene.cpp | 27 +- rendering/vulkan14/vulkan14swapchain.cpp | 36 ++- rendering/vulkan14/vulkan14swapchain.h | 15 ++ rendering/vulkan14/vulkan14walkers.cpp | 2 +- shaders/README.md | 3 +- shaders/compile_spirv.py | 7 +- shaders/ogl46/gtao_main.comp | 37 ++- shaders/ogl46/tonemapping.glsl | 3 +- shaders/vk14/gtao_main.comp | 37 ++- shaders/vk14/tonemapping.glsl | 3 +- starter/eu07_starter.cpp | 62 +++-- tools/fetch_dlss_sdk.cmake | 8 + utilities/Globals.cpp | 3 +- utilities/Globals.h | 6 +- utilities/utilities.cpp | 5 + utilities/utilities.h | 2 + vehicle/DynObj.cpp | 21 +- world/RailCarve.cpp | 8 +- world/TrackBlend.h | 5 +- world/TrackSleepers.cpp | 18 +- world/Traction.cpp | 56 ++-- world/Traction.h | 3 + world/catenary_catalog.cpp | 2 + world/catenary_scene.cpp | 109 +++++--- world/catenary_span.cpp | 39 ++- 85 files changed, 1519 insertions(+), 418 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 27fa64bc2..2e9a9c4b4 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -83,7 +83,6 @@ jobs: run: | cmake -S . -B build \ -DCMAKE_BUILD_TYPE=Debug \ - -DWITH_BETTER_RENDERER=OFF \ -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \ -DCMAKE_CXX_FLAGS="--coverage -O0 -Wno-attributes -fno-inline-functions-called-once" \ -DPython3_EXECUTABLE="$(which python3)" @@ -95,15 +94,14 @@ jobs: - name: Run the unit tests run: ./build/tests/unit/eu07_unit_tests - # the game's own sources only: no submodules, no vendored code, not the tests themselves. - # betterRenderer/ is left out for its thirdparty/yaml-cpp, which every target of the game links and so builds here + # the game's own sources only: no submodules, no vendored code, not the tests themselves - name: Coverage report run: | # a failure of gcovr fails the step, though its output goes through tee set -o pipefail mkdir -p coverage-report/html gcovr --root . build \ - --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' --exclude 'betterRenderer/' \ + --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' \ --exclude 'tests/' --exclude 'build/' \ --gcov-ignore-parse-errors=negative_hits.warn_once_per_file \ --gcov-ignore-errors=no_working_dir_found \ diff --git a/.github/workflows/shaders.yml b/.github/workflows/shaders.yml index 2d6135de4..b90be3d06 100644 --- a/.github/workflows/shaders.yml +++ b/.github/workflows/shaders.yml @@ -15,6 +15,7 @@ on: - 'shaders/**' - 'gl/**' - 'rendering/common/**' + - 'rendering/vulkan14/vulkan14bindings.h' - 'ci_shadervalidator/**' - '.github/workflows/shaders.yml' pull_request: @@ -23,6 +24,7 @@ on: - 'shaders/**' - 'gl/**' - 'rendering/common/**' + - 'rendering/vulkan14/vulkan14bindings.h' - 'ci_shadervalidator/**' - '.github/workflows/shaders.yml' diff --git a/.gitignore b/.gitignore index 9c9706dba..e428a464b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ vcpkg.json tools/python314/ __pycache__/ *.pyc + +# reviews of other pull requests, kept locally +/pr-reviews/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 60663355e..999b21ca8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,25 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake_modules/") set(DEPS_DIR ${DEPS_DIR} "${CMAKE_CURRENT_SOURCE_DIR}/ref") project("eu07") +# the submodules a clone hasn't filled (an older clone, whose .gitmodules didn't list them yet): told at once, before the error of the +# first one used, which names only its missing file +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.gitmodules") + file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/.gitmodules" EU07_SUBMODULE_PATHS REGEX "^[ \t]*path[ \t]*=") + set(EU07_EMPTY_SUBMODULES "") + foreach (line IN LISTS EU07_SUBMODULE_PATHS) + string(REGEX REPLACE "^[ \t]*path[ \t]*=[ \t]*" "" submodule "${line}") + string(STRIP "${submodule}" submodule) + file(GLOB submodule_files "${CMAKE_CURRENT_SOURCE_DIR}/${submodule}/*") + if (NOT submodule_files) + list(APPEND EU07_EMPTY_SUBMODULES "${submodule}") + endif() + endforeach() + if (EU07_EMPTY_SUBMODULES) + string(REPLACE ";" ", " EU07_EMPTY_SUBMODULES "${EU07_EMPTY_SUBMODULES}") + message(WARNING "empty submodules: ${EU07_EMPTY_SUBMODULES}. fill them with: git submodule sync && git submodule update --init --recursive") + endif() +endif() + #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fsanitize=undefined") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fsanitize=undefined -Wformat") #set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} -fsanitize=address -fsanitize=undefined") @@ -73,6 +92,12 @@ endif() option(WITH_OPENGL_MODERN "Compile with OpenGL modern renderer" ON) option(WITH_VULKAN "Compile with the Vulkan 1.4 renderer (gfxrenderer vulkan); needs the submodules ref/volk and ref/Vulkan-Headers" ON) option(WITH_DLSS "Compile the Vulkan renderer with NVIDIA DLSS (gfx.antialiasing dlss); needs the DLSS SDK in DLSS_SDK_ROOT, cmake -P tools/fetch_dlss_sdk.cmake" OFF) +# the development libraries of dlss (the indicator and the debug keys, gfx.dlss.developer) next to the program, in ngx_dev/. the license +# of the sdk lets only the production libraries go out with the program, so a build to be given out leaves them off +option(DLSS_DEVELOPMENT_LIBRARIES "With WITH_DLSS, copy the development libraries of DLSS to ngx_dev/ next to the program (not to be distributed)" OFF) +if (WITH_DLSS AND NOT WITH_VULKAN) + message(WARNING "WITH_DLSS=ON is for the Vulkan renderer, which WITH_VULKAN=OFF leaves out: the build has no DLSS") +endif() option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) @@ -786,7 +811,7 @@ if (WITH_VULKAN) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${DLSS_RUNTIME_RELEASE} "$") endif() - if (DLSS_RUNTIME_DEVELOPMENT) + if (DLSS_DEVELOPMENT_LIBRARIES AND DLSS_RUNTIME_DEVELOPMENT) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "$/ngx_dev" COMMAND ${CMAKE_COMMAND} -E copy_if_different ${DLSS_RUNTIME_DEVELOPMENT} "$/ngx_dev") @@ -1032,14 +1057,29 @@ if (UNIX AND NOT APPLE AND BUNDLE_RUNTIME_LIBS) endif() if(WIN32 AND WITH_PYTHON) + # the Python runtime next to the game, copied when it isn't there yet or the Python install changed, rather + # than after every link of the game: the library alone is thousands of files. the folder is the game's + # RUNTIME_OUTPUT_DIRECTORY, spelled out: $ here would make this target depend on the game + get_property(EU07_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if (EU07_MULTI_CONFIG) + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin/$") + else() + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin") + endif() + set(EU07_PY_STAMP "${EU07_PY_TARGET_DIR}/python64/python_runtime.stamp") add_custom_command( - TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "$" - # Lib with its site-packages is huge, the script copies it only when the Python install has changed - COMMAND ${CMAKE_COMMAND} "-DPY_LIBDIR=${EU07_PY_LIBDIR}" "-DPY_DLLSDIR=${EU07_PY_DLLSDIR}" "-DDEST_DIR=$" - -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake_modules/CopyPythonRuntime.cmake" - ) + OUTPUT "${EU07_PY_STAMP}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_LIBDIR}" "${EU07_PY_TARGET_DIR}/python64/Lib" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_DLLSDIR}" "${EU07_PY_TARGET_DIR}/python64/DLLs" + COMMAND ${CMAKE_COMMAND} -E touch "${EU07_PY_STAMP}" + DEPENDS "${EU07_PY_DLL}" "${EU07_PY_ZLIB}" + COMMENT "Copying the Python runtime next to the game" + VERBATIM) + add_custom_target(eu07_python_runtime DEPENDS "${EU07_PY_STAMP}") + set_target_properties(eu07_python_runtime PROPERTIES FOLDER "libraries") + add_dependencies(${PROJECT_NAME} eu07_python_runtime) endif() # the Visual C++ runtime the simulator is built with, next to it: older runtimes installed in the system crash the programs of newer @@ -1061,7 +1101,11 @@ if (WITH_WASM) target_link_libraries(${PROJECT_NAME} eu07_wamr) endif () -# yaml-cpp, for the descriptions of scenery templates edited in the scenery editor and for the heightmap terrain +# yaml-cpp, for the descriptions of scenery templates edited in the scenery editor and for the heightmap terrain. a clone made before +# the submodule was added has it empty, or under an older url +if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/ref/yaml-cpp/CMakeLists.txt") + message(FATAL_ERROR "the submodule ref/yaml-cpp is empty: git submodule sync && git submodule update --init --recursive") +endif() add_subdirectory("ref/yaml-cpp" "${CMAKE_CURRENT_BINARY_DIR}/yaml-cpp" EXCLUDE_FROM_ALL) target_link_libraries(eu07_settings INTERFACE yaml-cpp) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index cc39d6c18..b4814f990 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2198,6 +2198,7 @@ class TMoverParameters double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ + double BrakePressStep = 0.0; // how much BrakePress changed in the last step of the brakes [bar], see accelerating() double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ @@ -2666,6 +2667,9 @@ class TMoverParameters // standing still, its acceleration is the pull of the slope and of the couplers, as the brakes and the resistance count only // against a speed (FTotal); with Global.physics_sleepheld one held by them, the way ComputeMovement() keeps it standing, doesn't bool accelerating() const; + // with Global.physics_sleepheld, wakes the physics of a vehicle a brake of which was set by hand: one held by its brakes sleeps + // with the brake force it had (accelerating()) + void wake_for_brake(); double LocalBrakeRatio(void) const; double ManualBrakeRatio(void) const; double PipeRatio(void) const; /*ile napelniac*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index de75e64e8..ace1269cc 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -4266,6 +4266,7 @@ bool TMoverParameters::SpringBrakeActivate(bool State) if (SpringBrake.Activate != State) { SpringBrake.Activate = State; + wake_for_brake(); return true; } } @@ -4296,6 +4297,7 @@ bool TMoverParameters::SpringBrakeRelease() if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) { SpringBrake.IsReady = false; + wake_for_brake(); return true; } else @@ -5054,6 +5056,7 @@ bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) { LocalBrakePosA = std::min(1.0, LocalBrakePosA + CtrlSpeed / LocalBrakePosNo); + wake_for_brake(); IBL = true; } else @@ -5072,6 +5075,7 @@ bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) if (LocalBrakePosA > 0) { LocalBrakePosA = std::max(0.0, LocalBrakePosA - CtrlSpeed / LocalBrakePosNo); + wake_for_brake(); DBL = true; } else @@ -5166,6 +5170,7 @@ bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) ManualBrakePos++; CtrlSpeed--; } + wake_for_brake(); IMBL = true; } else @@ -5188,6 +5193,7 @@ bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) ManualBrakePos--; CtrlSpeed--; } + wake_for_brake(); DMBL = true; } else @@ -5510,7 +5516,9 @@ void TMoverParameters::UpdateBrakePressure(double dt) Hamulec->ForceLeak(dt * AirLeakRate * 0.25); // fake air leaks from brake system reservoirs + auto const brakepress{BrakePress}; BrakePress = Hamulec->GetBCP(); + BrakePressStep = std::abs(BrakePress - brakepress); // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; Volume = Hamulec->GetBRP(); } @@ -6084,13 +6092,26 @@ namespace { // whether the air flowing to a coupled vehicle along a pipe wakes its physics: any flow did, but a vehicle standing next to one // whose physics is on gets a trickle of it all the time, as their pressures settle, and each wake kept it on for 5 s. with -// Global.physics_pipewake only a flow which brings its pressure, with what has flown in while it slept, that much away from the -// pressure of the vehicle the air comes from +// Global.physics_pipewake only a flow which leaves its pressure, with what has flown in while it slept, that much away from the +// pressure of the vehicle the air comes from, or which has changed it by that much since it fell asleep: a pressure followed in +// small steps would never reach the valves of a vehicle asleep otherwise bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe) { if (Flow * Flow <= 0.00000000000001) return false; - return (Global.physics_pipewake <= 0.f) || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake); + return (Global.physics_pipewake <= 0.f) + || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake) + || (std::abs(Pipe.P_pending() - Pipe.P_applied()) > Global.physics_pipewake); +} + +// the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: +// with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would +// carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since +double neighbour_pipe_pressure(TMoverParameters const &Neighbour, double const Pressure, TReservoir const &Pipe) +{ + if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) + return Pressure; + return Pipe.P_pending(); } } // namespace @@ -6111,7 +6132,7 @@ double TMoverParameters::GetDVc(double dt) if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + dv1 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); c->Pipe->Flow(-dv1); if (pipe_wakes(dv1, PipePress, *c->Pipe)) c->switch_physics(true, wake_cause::mainpipe); @@ -6120,7 +6141,7 @@ double TMoverParameters::GetDVc(double dt) if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + dv2 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); c->Pipe->Flow(-dv2); if (pipe_wakes(dv2, PipePress, *c->Pipe)) c->switch_physics(true, wake_cause::mainpipe); @@ -6154,7 +6175,7 @@ double TMoverParameters::GetScndDVc(double dt) if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) { c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + dv1 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); c->Pipe2->Flow(-dv1); if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) c->switch_physics(true, wake_cause::scndpipe); @@ -6163,7 +6184,7 @@ double TMoverParameters::GetScndDVc(double dt) if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + dv2 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); c->Pipe2->Flow(-dv2); if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) c->switch_physics(true, wake_cause::scndpipe); @@ -11391,11 +11412,21 @@ bool TMoverParameters::accelerating() const if (std::abs(AccS) <= 0.0001) return false; // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() - // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by - auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain)}; + // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by. a vehicle whose + // brake cylinders still fill or release isn't held yet: asleep, it would keep the brake force (and the pressure the AI waits on + // to set off) it had when it fell asleep + auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && BrakePressStep <= 0.0001}; return false == held; } +void TMoverParameters::wake_for_brake() +{ + if (Global.physics_sleepheld) + { + switch_physics(true, wake_cause::command); + } +} + // ************************************************************************************************* // Kasowanie zmiennych pracy fizyki // ************************************************************************************************* diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index b8be1733c..2b08e1f63 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -275,6 +275,13 @@ class TReservoir return std::max(0.0, Vol + dVol) / Cap; } /// + /// Pressure the reservoir has now, without the flow accumulated for the step (Vol / Cap), in bar: P() of a const reservoir. + /// + double P_applied() const + { + return Vol / Cap; + } + /// /// Applies the accumulated flow (dVol) to the volume and resets dVol. /// Volume is clamped to be non-negative. /// diff --git a/application/application.cpp b/application/application.cpp index ce06141ae..563cba5c1 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -39,7 +39,9 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtest.h" #include "utilities/physicslog.h" #include +#include #include +#include #include #include #include @@ -197,6 +199,56 @@ void glfw_error_callback(int const Code, char const *Description) ErrorLog(message); } +#ifdef WITH_CRASHPAD +// there while the renderer starts (init_gfx()): left behind by a start which crashed in it +constexpr char const *GFX_START_MARK{"crashdumps/gfx_start.pending"}; +#endif + +// the mark of the start of the renderer put down (Starting) or taken away +void mark_gfx_start(bool const Starting) +{ +#ifdef WITH_CRASHPAD + std::error_code error; + if (Starting) + { + std::ofstream mark(GFX_START_MARK, std::ios::trunc); + } + else + { + std::filesystem::remove(GFX_START_MARK, error); + } +#else + (void)Starting; +#endif +} + +// the question about the report of the last crash, asked before the renderer starts when that crash came while it started: the window +// of the question is drawn by the renderer (run_crashgui()), so a crash in its start, which repeats at every start, would never let it +// show. a box of the system asks instead, on Windows, where the reports are made +void ask_crash_report_before_gfx() +{ +#if defined(WITH_CRASHPAD) && defined(_WIN32) + std::error_code error; + if ((false == crashreport_is_pending()) || Global.test.enabled || (false == std::filesystem::exists(GFX_START_MARK, error))) + { + return; + } + auto const polish{Global.asLang == "pl"}; + auto const *text{ + polish ? L"Podczas ostatniego uruchomienia symulator uległ awarii przy uruchamianiu grafiki.\nWysłać raport o błędzie do deweloperów?" : + L"The simulator crashed while starting the graphics during the last launch.\nSend the crash report to the developers?"}; + auto const *caption{polish ? L"Raportowanie błędów" : L"Crash reporting"}; + if (::MessageBoxW(nullptr, text, caption, MB_YESNO | MB_ICONERROR) == IDYES) + { + crashreport_upload_accept(); + } + else + { + crashreport_upload_reject(); + } +#endif +} + } // namespace // public: @@ -473,17 +525,23 @@ int eu07_application::init(int Argc, char *Argv[]) return result; } + ask_crash_report_before_gfx(); + mark_gfx_start(true); if ((result = init_gfx()) != 0) { + // a start which failed, not one which crashed + mark_gfx_start(false); ErrorLog("Failed to initialize GFX!"); return result; } if ((result = init_ui()) != 0) { // ui now depends on activated renderer + mark_gfx_start(false); ErrorLog("Failed to init UI!"); return result; } + mark_gfx_start(false); if (crashreport_is_pending() && false == Global.test.enabled) { // run crashgui as early as possible: it's drawn by the renderer if ((result = run_crashgui()) != 0) @@ -1433,20 +1491,8 @@ 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; - } + // a renderer this build doesn't have: the values of the removed renderers are taken for "default" as eu07.ini is read + // (global_settings::ConfigParse), and a vulkan renderer which can't run here falls back to opengl (select_gfx_backend()) return 0; } diff --git a/application/editormode.cpp b/application/editormode.cpp index a7c2b6ab9..2cb34401c 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -35,6 +35,7 @@ extern char **environ; #include "editor/editorIncludeInfo.hpp" #include "editor/editorGroundMesh.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorCatenaryFile.hpp" #include "editor/editorAlignmentStore.hpp" #include "editor/editorSwitchStore.hpp" #include "world/catenary_scene.h" @@ -3314,33 +3315,16 @@ bool editor_mode::save() } first_step_done(first_step::save); - // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own - std::vector rootstatements; - std::map> statements; - if (m_streamer.active()) + // what can refuse the save is checked before anything is written, and the catenary files go first, all of them or none: + // a save refused there leaves the files on the disk as they were + for (auto const &file : catenary_scene_new_files()) { - std::string error; - if (false == m_streamer.save(&error)) - { - ui()->set_status(format(STR_C("The terrain couldn't be saved: %s"), error.c_str()), true); - return false; - } - if (false == scene::Layers.terrain_directive()) - { - auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; - if (auto const layer{output_layer("teren")}; layer != null_handle) - statements[layer].push_back(directive); - else - rootstatements.push_back(directive); - } + if (catenary_file_name_valid(file)) + continue; + ui()->set_status(format(STR_C("The catenary in \"%s\" couldn't be saved: %s"), file.c_str(), STR_C("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it")), true); + return false; } - - auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; - if (m_profile.changed) - profile_store(); - switch_store::tidy(); - switch_store::settle(); - infra_store(); + bool catenarywritten{false}; // the catenary (cantilevers on the poles) lives in files of its own; a file made in the editor needs the directive, in the file // of the layer it was made on (the scenario file when that layer can't take it) std::vector catenarynew; @@ -3383,8 +3367,40 @@ bool editor_mode::save() ui()->set_status(format(STR_C("The catenary couldn't be saved: %s"), message.c_str()), true); return false; } + catenarywritten = false == message.empty(); WriteLog("Editor: catenary written: " + message, logtype::generic); } + + // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own + std::vector rootstatements; + std::map> statements; + if (m_streamer.active()) + { + std::string error; + if (false == m_streamer.save(&error)) + { + if (catenarywritten) + ui()->set_status(format(STR_C("The terrain couldn't be saved: %s. The catenary files are written already, the scenery files aren't: save again once it's fixed"), error.c_str()), true); + else + ui()->set_status(format(STR_C("The terrain couldn't be saved: %s"), error.c_str()), true); + return false; + } + if (false == scene::Layers.terrain_directive()) + { + auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; + if (auto const layer{output_layer("teren")}; layer != null_handle) + statements[layer].push_back(directive); + else + rootstatements.push_back(directive); + } + } + + auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; + if (m_profile.changed) + profile_store(); + switch_store::tidy(); + switch_store::settle(); + infra_store(); for (auto const &file : catenary_scene_new_files()) { auto const layer{static_cast(catenary_scene_file_layer(file))}; @@ -3444,6 +3460,13 @@ bool editor_mode::save() if (result.success) for (auto const &file : catenarynew) catenary_scene_file_included(file); + if (false == result.success && (catenarywritten || m_streamer.active())) + { + // the files of the terrain and of the catenary went before the scenery files + ui()->set_status(format("%s %s", result.message.c_str(), STR_C("Files of the terrain or of the catenary may be written already, the scenery files aren't: save again once it's fixed")), true); + WriteLog("Editor: " + result.message, logtype::generic); + return false; + } ui()->set_status(result.message, false == result.success); WriteLog("Editor: " + result.message, logtype::generic); return result.success; diff --git a/application/editormodecatenary.cpp b/application/editormodecatenary.cpp index 5e8557d24..b2bbb61c4 100644 --- a/application/editormodecatenary.cpp +++ b/application/editormodecatenary.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editormodecatenary.h" #include "application/editoruilayer.h" #include "application/editorprojection.h" +#include "editor/editorCatenaryFile.hpp" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" @@ -399,6 +400,27 @@ bool grouped_items(std::vector const &Names, int &Chosen, std::func char const *const kStates[] = {"new", "worn", "tarnished"}; int const kStateValues[] = {0, 2, 1}; +// the chain the other way round: what is at its ends (the anchors, the holders of the middle anchor's rope) changes ends with the list +void reverse_chain(catenary::chain &Chain) +{ + std::ranges::reverse(Chain.suspensions); + std::swap(Chain.anchor_start, Chain.anchor_end); + std::swap(Chain.anchor_start_contact, Chain.anchor_end_contact); + std::swap(Chain.middle_heights[0], Chain.middle_heights[1]); +} + +// the new entries can go into the file: a scenery file (layer), a catenary file the scenery includes already, or a new one +// whose name the directive including it can carry +bool file_takes_entries(std::string const &File) +{ + if (catenary_scene_file_inline(File)) + return true; + auto const files{catenary_scene_files()}; + auto const fresh{catenary_scene_new_files()}; + auto const included{std::ranges::find(files, File) != files.end() && std::ranges::find(fresh, File) == fresh.end()}; + return included || catenary_file_name_valid(File); +} + } // namespace void catenary_editor::catenary_scan() @@ -1626,8 +1648,12 @@ void catenary_editor::catenary_apply(catenary_spot const &Spot) std::copy(std::begin(current->spread), std::end(current->spread), data.spread); // dragging a slider changes it many times: all of that is taken back at once auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || last.chain || last.index != index || last.removed || false == last.before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 1 || last.chain || last.index != index || last.removed || false == last.before.has_value()) + { tool.undo.push_back({++tool.group, false, index, *current, std::nullopt, false}); + tool.slider_group = tool.group; + tool.slider = 1; + } catenary_scene_update(index, data); tool.spots[index] = Spot; tool.spots[index].data = data; @@ -2123,6 +2149,11 @@ void catenary_editor::catenary_place(catenary_spot const &Spot) chain_insert insert; auto const inserting{catenary_insert_at(Spot, insert)}; std::string const file{inserting ? catenary_chain_file(static_cast(insert.chain)) : std::string{tool.file}}; + if (false == inserting && false == file_takes_entries(file)) + { + tool.status = STR("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it"); + return; + } data.name = catenary_scene_new_name(file); // a drop on a gantry takes the texture of the gantry if (auto const *gantry{tool.gantry_selected >= 0 ? catenary_gantry_get(static_cast(tool.gantry_selected)) : nullptr}; gantry != nullptr && data.pole_type != tool.poles[std::clamp(tool.pole, 0, static_cast(tool.poles.size()) - 1)]) @@ -2674,13 +2705,23 @@ void catenary_editor::catenary_connect(std::size_t const To) // From's chain with From last, then To (and To's chain from To on) auto changed{*chaina}; if (pa == 0 && changed.suspensions.size() > 1) - std::reverse(changed.suspensions.begin(), changed.suspensions.end()); + reverse_chain(changed); if (chainb != nullptr) { - auto other{chainb->suspensions}; + auto other{*chainb}; if (pb != 0) - std::reverse(other.begin(), other.end()); - changed.suspensions.insert(changed.suspensions.end(), other.begin(), other.end()); + reverse_chain(other); + changed.suspensions.insert(changed.suspensions.end(), other.suspensions.begin(), other.suspensions.end()); + // the joined ends are inside the chain now: it ends where To's chain ended, with what that end had + changed.anchor_end = other.anchor_end; + changed.anchor_end_contact = other.anchor_end_contact; + changed.messenger_from.insert(changed.messenger_from.end(), other.messenger_from.begin(), other.messenger_from.end()); + if (changed.middle.empty() && false == other.middle.empty()) + { + changed.middle = other.middle; + changed.middle_device = other.middle_device; + std::copy(std::begin(other.middle_heights), std::end(other.middle_heights), changed.middle_heights); + } tool.undo.push_back({tool.group, true, static_cast(cb), std::nullopt, *chainb, false}); catenary_chain_remove(static_cast(cb)); } @@ -2857,6 +2898,11 @@ void catenary_editor::catenary_press(track_intent const &Intent) return; catenary::gantry gantry; std::string const file{tool.file}; + if (false == file_takes_entries(file)) + { + tool.status = STR("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it"); + return; + } gantry.name = catenary_scene_new_gantry_name(file); gantry.beam = beam; gantry.high = tool.gantry_high; @@ -2992,8 +3038,12 @@ void catenary_editor::catenary_chain_apply() if (false == tool.networks.empty()) changed.type = tool.networks[std::clamp(tool.network, 0, static_cast(tool.networks.size()) - 1)]; auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || false == last.chain || last.index != index || false == last.chain_before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 2 || false == last.chain || last.index != index || false == last.chain_before.has_value()) + { tool.undo.push_back({++tool.group, true, index, std::nullopt, *chain, false}); + tool.slider_group = tool.group; + tool.slider = 2; + } catenary_chain_update(index, changed); } @@ -4292,6 +4342,8 @@ void catenary_editor::render_catenary_cantilever_ui() if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The catenary file follows the active layer again")); } + if (tool.file[0] != '\0' && false == file_takes_entries(tool.file)) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", STR_C("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it")); { // where it ends up: straight in the file of a layer, or a catenary file of its own and the layer whose file includes it if (catenary_scene_file_inline(tool.file)) @@ -5017,10 +5069,12 @@ void catenary_editor::render_catenary_ui() // both together, and each by itself no more than 0.20 m from the other auto const heighten = [&](catenary::gantry const &Changed) { auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || false == last.gantry || last.index != static_cast(tool.gantry_selected) || false == last.gantry_before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 3 || false == last.gantry || last.index != static_cast(tool.gantry_selected) || false == last.gantry_before.has_value()) { catenary_change change; change.group = ++tool.group; + tool.slider_group = tool.group; + tool.slider = 3; change.gantry = true; change.index = static_cast(tool.gantry_selected); change.gantry_before = *gantry; @@ -5734,9 +5788,11 @@ void catenary_editor::catenary_gantry_reshape(std::string const &Beam, double co } auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; // turning in small steps is taken back at once - if (Turn == 0.0 || tool.undo.empty() || false == last.gantry || last.index != selected || false == last.gantry_before.has_value()) + if (Turn == 0.0 || tool.undo.empty() || last.group != tool.slider_group || tool.slider != 4 || false == last.gantry || last.index != selected || false == last.gantry_before.has_value()) { ++tool.group; + tool.slider_group = Turn == 0.0 ? 0 : tool.group; + tool.slider = 4; // the selected span last: the next small turn finds it at the top of the undo and joins this group for (auto move{moves.rbegin()}; move != moves.rend(); ++move) { diff --git a/application/editormodecatenary.h b/application/editormodecatenary.h index cdafc45eb..7d78df61f 100644 --- a/application/editormodecatenary.h +++ b/application/editormodecatenary.h @@ -113,6 +113,9 @@ struct catenary_editor std::map spots; // where the suspensions are by the track, by their numbers std::vector undo; int group{0}; + // the undo group a control of the panel opened: its next changes join it only while nothing else came between + int slider_group{0}; + int slider{0}; // ... which control: 1 the settings of the pole, 2 of the chain, 3 the heights of a gantry, 4 its turn catenary::cantilever_result probe; bool probed{false}; bool probe_good{false}; diff --git a/audio/radiostream.cpp b/audio/radiostream.cpp index 6d231265a..b2673dfa5 100644 --- a/audio/radiostream.cpp +++ b/audio/radiostream.cpp @@ -738,7 +738,7 @@ radio_stream::~radio_stream() { // out of memory while retiring the worker: its thread still stops and is joined by its own destructor below } - // NOTE: destructors of retired workers wait for their threads to finish + // NOTE: destructors of retired workers wait for their threads to finish, before the buffers and the mutexes go (radiostream.h) } // starts reception of specified stream, dropping current one if there's any diff --git a/audio/radiostream.h b/audio/radiostream.h index 5088f1fcc..6300016b2 100644 --- a/audio/radiostream.h +++ b/audio/radiostream.h @@ -92,8 +92,6 @@ class radio_stream void reap(); // members std::string m_url; - worker m_worker; - std::vector m_retired; // workers which were told to stop but may still be busy closing their connection std::atomic m_state{state::idle}; std::atomic m_rate{0}; mutable std::mutex m_mutex; // guards the sample buffer and the generation counter @@ -103,6 +101,10 @@ class radio_stream std::size_t m_samplescount{0}; std::mutex m_messagesmutex; std::deque m_messages; + // the workers last: the members go in the reverse order, so their threads, which store() and post() to the members above, are + // joined before those go + worker m_worker; + std::vector m_retired; // workers which were told to stop but may still be busy closing their connection }; } // namespace audio diff --git a/ci_shadervalidator/build.sh b/ci_shadervalidator/build.sh index 5d359b3ff..fbf4ab39c 100755 --- a/ci_shadervalidator/build.sh +++ b/ci_shadervalidator/build.sh @@ -10,7 +10,10 @@ # Every .vert/.frag/.geom/.comp of shaders/ogl46 is compiled as the game compiles the source (features on and off, and the # variant of the multi draws) and to SPIR-V for opengl from the file as it is (as glslc makes the binaries of # shaders/ogl46bin); the constants written in shaders/ogl46/common.glsl are compared with those of the game. The shaders of -# shaders/vk14 are compiled to SPIR-V for vulkan. +# shaders/vk14 are compiled to SPIR-V for vulkan1.4 (vulkan1.3, said at the start and at the end of the run, where +# glslangValidator doesn't know 1.4; ./validateshaders --vulkan-env vulkan1.4 fails then instead), and the constants written in +# shaders/vk14/common.glsl are compared with rendering/vulkan14/vulkan14bindings.h and those of the game. The temporary files +# are made with unique names and removed afterwards. # Exit code is 0 when all shaders pass, 1 otherwise; failing shaders are listed at the end. # # The validator's own stdafx.h and utilities/{Globals,Logs}.h stand in for the game's headers: its directory comes first diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 171324d5e..96af5c0ed 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -4,11 +4,22 @@ #include "utilities/Globals.h" #include "utilities/Logs.h" #include -#include -#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include #include +#ifdef _WIN32 +#include +#else +#include +#endif _global Global; @@ -17,9 +28,91 @@ namespace std::string const ogl46_dir{"../shaders/ogl46/"}; std::string const vk14_dir{"../shaders/vk14/"}; -// the vulkan environment glslang is asked for: 1.4 where it knows it +std::string const vk14_bindings_header{"../rendering/vulkan14/vulkan14bindings.h"}; +// the vulkan environment glslang is asked for: 1.4 where it knows it, or the one given with --vulkan-env std::string vulkan_env{"vulkan1.4"}; +// writes the text to a new file with a unique name in the temporary directory of the system and returns its path, or an empty +// string when it cannot be written. the file is created exclusively, so nothing put in a shared /tmp under a name known in +// advance (a file or a link) is written through +std::string write_temp_file(std::string_view const Text) +{ + std::string path{(std::filesystem::temp_directory_path() / "maszyna-shader-XXXXXX").string()}; + std::FILE *file{nullptr}; +#ifdef _WIN32 + // no mkstemp() in the CRT; a random name, opened with "x", which fails when the file is there already + std::random_device random; + for (int attempt = 0; (attempt < 100) && (file == nullptr); ++attempt) + { + path.replace(path.size() - 6, 6, std::to_string(100000 + random() % 900000)); + if (fopen_s(&file, path.c_str(), "wx") != 0) + file = nullptr; + } +#else + if (int const descriptor{mkstemp(path.data())}; descriptor != -1) + { + file = fdopen(descriptor, "w"); + if (file == nullptr) + { + close(descriptor); + std::remove(path.c_str()); + } + } +#endif + if (file == nullptr) + return {}; + + bool const written{std::fwrite(Text.data(), 1, Text.size(), file) == Text.size()}; + if ((std::fclose(file) != 0) || !written) + { + std::remove(path.c_str()); + return {}; + } + return path; +} + +// a file of the validator in the temporary directory, removed when it goes. glslangValidator writes its output and the shell +// its log into files made this way, so they too are made exclusively beforehand +class temp_file +{ + public: + explicit temp_file(std::string_view const Text) : m_path{write_temp_file(Text)} {} + ~temp_file() + { + if (false == m_path.empty()) + std::remove(m_path.c_str()); + } + temp_file(temp_file const &) = delete; + temp_file &operator=(temp_file const &) = delete; + + std::string const &path() const + { + return m_path; + } + + private: + std::string m_path; +}; + +// runs glslangValidator with the arguments, what it writes into a log file. false when the file can't be made; Result is the +// exit code, Log what it wrote +bool run_glslang(std::string_view const Arguments, int &Result, std::string &Log) +{ + temp_file const log{std::string_view{}}; + if (log.path().empty()) + { + std::cerr << "cannot make a file in the temporary directory" << std::endl; + return false; + } + auto const command{std::format("glslangValidator {} > \"{}\" 2>&1", Arguments, log.path())}; + Result = system(command.c_str()); + std::ifstream file(log.path()); + std::ostringstream text; + text << file.rdbuf(); + Log = text.str(); + return true; +} + char const *stage_name(gfx::shader_stage const Stage) { switch (Stage) @@ -44,17 +137,25 @@ bool check_text(gfx::shader_source const &Source, std::string const &Mode) ErrorLogged = false; return false; } - std::ofstream file("/tmp/shader"); - file << Source.text; - file.close(); + temp_file const source{Source.text}; + temp_file const output{std::string_view{}}; + if (source.path().empty() || output.path().empty()) + { + std::cerr << "cannot write the shader to the temporary directory" << std::endl; + return false; + } // the output only when it fails (glslangValidator names the file it compiled to spir-v) - auto const command{"glslangValidator " + Mode + " -S " + stage_name(Source.stage) + " /tmp/shader" + (Mode.empty() ? "" : " -o /tmp/shader.spv") + " > /tmp/shader.log 2>&1"}; - int ret = system(command.c_str()); + std::string arguments{std::format("{} -S {} \"{}\"", Mode, stage_name(Source.stage), source.path())}; + if (false == Mode.empty()) + arguments += std::format(" -o \"{}\"", output.path()); + int ret{-1}; + std::string log; + if (false == run_glslang(arguments, ret, log)) + return false; if (ret != 0) { - std::ifstream log("/tmp/shader.log"); - std::cerr << std::endl << log.rdbuf(); + std::cerr << std::endl << log; std::cerr << "(source strings:"; for (std::size_t i = 0; i < Source.files.size(); ++i) std::cerr << " " << i << ": " << Source.files[i]; @@ -146,49 +247,159 @@ bool is_stage(std::filesystem::path const &Path) return (ext == ".frag" || ext == ".geom" || ext == ".vert" || ext == ".comp"); } +// whether glslangValidator compiles a shader for the vulkan environment +bool knows_vulkan_env(std::string_view const Env) +{ + temp_file const source{"#version 460\nvoid main() { gl_Position = vec4(0.0); }\n"}; + temp_file const output{std::string_view{}}; + if (source.path().empty() || output.path().empty()) + return false; + int ret{-1}; + std::string log; + return run_glslang(std::format("-V --target-env {} -S vert \"{}\" -o \"{}\"", Env, source.path(), output.path()), ret, log) && (ret == 0); +} + +// the bindings of rendering/vulkan14/vulkan14bindings.h as the #define lines vk14::binding_preamble() makes of them, read from +// the header as it is (the code of the renderer needs vulkan and glslang, which the validator is built without). Names: all +// the constants of the header +std::string vk14_binding_defines(std::unordered_set &Names) +{ + std::ifstream file(vk14_bindings_header); + std::regex const constant{R"(^\s*constexpr\s+std::uint32_t\s+(\w+)\s*=\s*(\d+)\s*;)"}; + std::string defines; + std::string line; + while (std::getline(file, line)) + { + std::smatch match; + if (false == std::regex_search(line, match, constant)) + continue; + Names.insert(match[1].str()); + // the number of the bindings with dynamic offsets is the renderer's own, the shaders aren't given it + if (match[1].str() == "PASS_DYNAMIC_OFFSETS") + continue; + defines += std::format("#define {} {}\n", match[1].str(), match[2].str()); + } + return defines; +} + +// the constants of the game the vulkan renderer gives the shaders as the opengl one does (gl::glsl_common), those of them which +// shaders/vk14/common.glsl writes too; the bindings, which differ between the renderers, left out +std::string vk14_shared_defines(std::unordered_set const &Bindings) +{ + auto const file{gfx::shader_file_defines(gfx::shader_api::vulkan14, "common.glsl", vk14_dir)}; + std::istringstream stream(gl::glsl_common); + std::string defines; + std::string line; + while (std::getline(stream, line)) + { + std::istringstream linestream(line); + std::string directive; + std::string name; + if (!(linestream >> directive >> name) || (directive != "#define") || Bindings.contains(name) || !file.contains(name)) + continue; + defines += line + '\n'; + } + return defines; +} + +// the constants written in common.glsl of a directory compared with those of the game: the binaries are compiled with the +// constants of the file, the game compiles the sources with its own +bool check_constants(std::string_view const Label, gfx::shader_api const Api, std::string const &Directory, std::string const &Preamble) +{ + std::vector differences; + std::cout << "== constants of " << Label << ": " << std::flush; + if (gfx::shader_constants_match(Api, "common.glsl", Preamble, Directory, differences)) + { + std::cout << "the same as in the game" << std::endl; + return true; + } + std::cout << "not the same as in the game:" << std::endl; + for (auto const &difference : differences) + std::cout << " " << difference << std::endl; + return false; +} + +// the vulkan environment from the arguments (--vulkan-env ), empty without it. false on arguments it doesn't know +bool parse_arguments(std::vector const &Arguments, std::string &Required) +{ + if (Arguments.empty()) + return true; + if ((Arguments.size() != 2) || (Arguments[0] != "--vulkan-env")) + return false; + Required = Arguments[1]; + return true; +} + } // namespace -int main() +// --vulkan-env : the vulkan environment to check the shaders of shaders/vk14 against, which glslangValidator has to know; +// without it vulkan1.4, or vulkan1.3 (said at the start and at the end) where glslangValidator doesn't know 1.4 +int main(int argc, char *argv[]) { - if (system("glslangValidator --version > /dev/null 2>&1") != 0) + std::string required; + if (false == parse_arguments(std::vector(argv + 1, argv + argc), required)) + { + std::cerr << "usage: validateshaders [--vulkan-env ]" << std::endl; + return 1; + } + + int ret{-1}; + std::string version; + if (!run_glslang("--version", ret, version) || (ret != 0)) { std::cerr << "glslangValidator not found in PATH" << std::endl; return 1; } + std::cout << "== " << version.substr(0, version.find('\n')) << std::endl; + bool fallback{false}; + if (false == required.empty()) { - std::ofstream file("/tmp/shader_env.vert"); - file << "#version 460\nvoid main() { gl_Position = vec4(0.0); }\n"; + if (false == knows_vulkan_env(required)) + { + std::cerr << "glslangValidator doesn't know the vulkan environment " << required << std::endl; + return 1; + } + vulkan_env = required; } - if (system("glslangValidator -V --target-env vulkan1.4 /tmp/shader_env.vert -o /tmp/shader_env.spv > /dev/null 2>&1") != 0) + else if (false == knows_vulkan_env(vulkan_env)) { vulkan_env = "vulkan1.3"; - std::cout << "== glslangValidator doesn't know vulkan 1.4, the vulkan shaders are checked against vulkan 1.3" << std::endl; + fallback = true; + std::cout << "== WARNING: glslangValidator doesn't know vulkan1.4, the vulkan shaders are checked against vulkan1.3 only" << std::endl; } + std::cout << "== the vulkan shaders are checked against " << vulkan_env << std::endl; bool suc = true; std::vector failed; - // the binaries are compiled with the constants written in common.glsl, the game compiles the sources with its own gl::glsl_common_setup(); - std::vector differences; - std::cout << "== constants of shaders/ogl46/common.glsl: " << std::flush; - if (gl::glsl_common_matches(ogl46_dir, differences)) + if (false == check_constants("shaders/ogl46/common.glsl", gfx::shader_api::opengl46, ogl46_dir, gl::glsl_common)) { - std::cout << "the same as in the game" << std::endl; - } - else - { - std::cout << "not the same as in the game:" << std::endl; - for (auto const &difference : differences) - std::cout << " " << difference << std::endl; suc = false; - failed.push_back("common.glsl"); + failed.emplace_back("ogl46/common.glsl"); + } + std::unordered_set bindings; + if (auto const bindingdefines{vk14_binding_defines(bindings)}; bindingdefines.empty()) + { + std::cout << "== constants of shaders/vk14/common.glsl: " << vk14_bindings_header << " can't be read" << std::endl; + suc = false; + failed.emplace_back("vk14/common.glsl"); + } + else if (false == check_constants("shaders/vk14/common.glsl", gfx::shader_api::vulkan14, vk14_dir, bindingdefines + vk14_shared_defines(bindings))) + { + suc = false; + failed.emplace_back("vk14/common.glsl"); } for (auto const &[directory, api] : {std::pair{ogl46_dir, gfx::shader_api::opengl46}, std::pair{vk14_dir, gfx::shader_api::vulkan14}}) { if (false == std::filesystem::is_directory(directory)) + { + std::cout << "== the directory " << directory << " isn't there" << std::endl; + suc = false; + failed.push_back(directory); continue; + } std::vector names; for (auto &f : std::filesystem::directory_iterator(directory)) if (f.is_regular_file() && is_stage(f.path())) @@ -216,6 +427,8 @@ int main() } } + if (fallback) + std::cout << "==== the vulkan shaders were checked against vulkan1.3, not vulkan1.4" << std::endl; if (suc) std::cout << "==== all checks ok" << std::endl; else { diff --git a/environment/weather.cpp b/environment/weather.cpp index df83e220d..74b2f1e82 100644 --- a/environment/weather.cpp +++ b/environment/weather.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include "simulation/simulationenvironment.h" +#include + namespace { @@ -57,9 +59,12 @@ std::string lower(std::string_view Text) return result; } +// a whole number of up to 9 digits, which std::stoi() reads without going out of the range of int: the numbers of the report are read +// with it only after this test, and a longer one (99999999999SM) threw std::out_of_range out of the parsing. the report comes from +// a memory cell, the weather panel or the scenery bool all_digits(std::string_view Text) { - return !Text.empty() && std::all_of(Text.begin(), Text.end(), [](char c) { return std::isdigit(static_cast(c)) != 0; }); + return !Text.empty() && (Text.size() <= 9) && std::ranges::all_of(Text, [](char c) { return std::isdigit(static_cast(c)) != 0; }); } // a number in the C locale, the whole token diff --git a/gl/streambuffer.cpp b/gl/streambuffer.cpp index 070723aaa..4307027e1 100644 --- a/gl/streambuffer.cpp +++ b/gl/streambuffer.cpp @@ -3,13 +3,13 @@ #include #include -#include +#include #include "utilities/Logs.h" namespace { -// a single frame isn't given more than this; past it the frame waits for the gpu to finish everything and starts the buffer over +// a buffer of a frame doesn't grow past this; a frame which streams more goes on in further buffers of this size constexpr GLsizeiptr STREAM_SIZE_MAX = 256 * 1024 * 1024; constexpr GLbitfield STREAM_MAP_FLAGS = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; @@ -159,25 +159,21 @@ GLintptr gl::frame_stream::reserve(GLsizeiptr Size) { auto const needed{m_start + align_up(Size, m_alignment)}; auto const size{needed > STREAM_SIZE_MAX ? needed : std::min(std::max(needed, 2 * current->size), STREAM_SIZE_MAX)}; - if (size > current->size) + if (size <= current->size) { - // a bigger buffer for the rest of the frame, starting after its header again. the fence of the slot (if any) was - // waited for when the frame took the slot over, the old buffer is only read by this frame, which may still bind it - // for what it wrote there (a recorded draw drawn later), so it's kept, mapped, until the slot is taken over again - m_retired[m_slot].push_back(current->buffer); - current->buffer = 0; - current->data = nullptr; - current->size = 0; - create(*current, size); - ++m_grows; - } - else - { - // the frame wrote as much as a buffer may hold: start it over once the gpu read all of it - ErrorLog("Bad buffer: a frame streamed more than " + std::to_string(STREAM_SIZE_MAX / (1024 * 1024)) + " MiB, waiting for the gpu"); - glFinish(); - ++m_waits; + // the frame wrote as much as a buffer may hold. what it wrote may still be bound by draws it makes later, so it isn't + // written over: the rest of the frame goes to another buffer of the same size + ErrorLog(std::format("Bad buffer: a frame streamed more than {} MiB, another buffer is made for it", STREAM_SIZE_MAX / (1024 * 1024))); } + // a new buffer for the rest of the frame, starting after its header again. the fence of the slot (if any) was waited for + // when the frame took the slot over, the old buffer is only read by this frame, which may still bind it for what it + // wrote there (a recorded draw drawn later), so it's kept, mapped, until the slot is taken over again + m_retired[m_slot].push_back(current->buffer); + current->buffer = 0; + current->data = nullptr; + current->size = 0; + create(*current, size); + ++m_grows; offset = m_start; } m_fill = offset + Size; diff --git a/lang/editor_pl.po b/lang/editor_pl.po index d85870f86..f1260bb5b 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -16289,3 +16289,12 @@ msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" msgid "Preparing the graphics (takes longer at the first start of a new version)" msgstr "Przygotowanie grafiki (przy pierwszym uruchomieniu nowej wersji trwa dłużej)" + +msgid "The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it" +msgstr "Nazwa pliku sieci trakcyjnej nie może zawierać spacji, ';', cudzysłowów, ':' ani \"..\" ani zaczynać się ukośnikiem: dyrektywa dołączająca plik nie odczytałaby jej" + +msgid "The terrain couldn't be saved: %s. The catenary files are written already, the scenery files aren't: save again once it's fixed" +msgstr "Nie udało się zapisać terenu: %s. Pliki sieci trakcyjnej są już zapisane, pliki scenerii nie: zapisz ponownie po usunięciu przyczyny" + +msgid "Files of the terrain or of the catenary may be written already, the scenery files aren't: save again once it's fixed" +msgstr "Pliki terenu lub sieci trakcyjnej mogą być już zapisane, pliki scenerii nie: zapisz ponownie po usunięciu przyczyny" diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 474c0f215..f3ddbc4a5 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1836,8 +1836,9 @@ void assign_lod_ranges(TSubModel *Root, std::string const &Filename) } auto const nearlimit{limits[std::min(phase.index, limitcount - 1)]}; auto farlimit{phase.index + 1 < limitcount ? limits[phase.index + 1] : farthest}; + // the last phase starting at 400 m or farther (_LOD5 and on) of a small part would have an empty range: it's seen 100 m on if (last) - farlimit = vanish; + farlimit = std::max(vanish, nearlimit + 100.f); phase.submodel->fSquareMinDist = nearlimit * nearlimit; phase.submodel->fSquareMaxDist = farlimit * farlimit; } diff --git a/rendering/common/cabprobe.h b/rendering/common/cabprobe.h index 88eed383f..f066f4687 100644 --- a/rendering/common/cabprobe.h +++ b/rendering/common/cabprobe.h @@ -23,7 +23,7 @@ class TModel3d; namespace gfx { -// the probe of the occupied cab (Global.gfx_cabprobe, the stage A4 of claude/renderers-plan.md), the part shared by the renderers; +// the probe of the occupied cab (Global.gfx_cabprobe), the part shared by the renderers; // the backend (opengl46_cab_probe, vk14::cab_probe_maps) keeps the maps and draws to them through the gpu_* methods. // - two cube maps drawn from the middle of the box of the cab model (mdKabina), in the space of the model, so they stay right while // the vehicle moves and turns: the light of the lights of the cab (the lamp, the light points of the cab model, the brightest diff --git a/rendering/common/exposure.h b/rendering/common/exposure.h index 7b3eabb59..53522ef3b 100644 --- a/rendering/common/exposure.h +++ b/rendering/common/exposure.h @@ -7,9 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// what the automatic exposure and the bloom of the renderers share (the part of the stage S3 of -// claude/gl46-renderer-features-plan.md which isn't the work of the gpu, taken out of opengl46_exposure for the vulkan renderer, -// stage P1 of claude/vulkan14-renderer-plan.md): the parameters of the histogram and of the adaptation +// what the automatic exposure and the bloom of the renderers share (the part which isn't the work of the gpu, taken out of +// opengl46_exposure for the vulkan renderer): the parameters of the histogram and of the adaptation // (exposure_histogram.comp, exposure_average.comp), the sizes of the levels of the bloom chain and the parameters of its steps // (postfx_bloom_*.frag), the parameters of the tonemapping and the controls of the debug window diff --git a/rendering/common/instancecull.h b/rendering/common/instancecull.h index fc7fe14e5..1661bf933 100644 --- a/rendering/common/instancecull.h +++ b/rendering/common/instancecull.h @@ -25,8 +25,8 @@ class TAnimModel; namespace gfx { -// the cpu side of the culling of the model instances of a render pass in compute passes, shared by the renderers (stage N6c of -// claude/vulkan14-renderer-plan.md); the backend (opengl46_instance_cull, vk14 instance_cull) keeps the buffers and runs the passes: +// the cpu side of the culling of the model instances of a render pass in compute passes, shared by the renderers; +// the backend (opengl46_instance_cull, vk14 instance_cull) keeps the buffers and runs the passes: // - the records of the instances (scene::basic_cell::instance_record) are kept in one buffer, each bucket of a scene cell // in its own place, and sent again only when the bucket made them anew // - every bucket queued in the pass becomes a job; the buckets of one model and one set of skins make a group, whose diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 9f042afe0..ff6b1465e 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -194,9 +194,15 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re m_scenerycount = m_vehiclecount = m_compartmentcount = 0; m_walkgeometry = &Geometry; - // the editor adds, moves and removes instances in the cells. it can also do it in the frame it is turned off in + // the editor adds, moves and removes instances in the cells. it can also do it in the frame it is turned off in. the cells not + // visited in such a frame (in the daylight, or out of range) are made anew too when they are visited next: an instance replaced in + // the place of another leaves the size and the address of the list of the cell as they were auto const rebuild{EditorModeFlag || m_editorseen}; m_editorseen = EditorModeFlag; + if (rebuild) + { + m_cells.clear(); + } if (Global.gfx_lights_clustered) { @@ -276,6 +282,11 @@ void gfx::local_lights::reset() m_scenerycount = m_vehiclecount = m_compartmentcount = m_placed = m_dropped = 0; } +void gfx::local_lights::forget(scene::basic_node const *) +{ + m_cells.clear(); +} + void gfx::local_lights::gather_instance(TAnimModel *Instance, glm::dvec3 const &Camera, float const Brightness, unsigned int const Framestamp) { if ((false == Instance->m_visible) || (Instance->pModel == nullptr)) diff --git a/rendering/common/locallights.h b/rendering/common/locallights.h index 5cfd6247f..95808c079 100644 --- a/rendering/common/locallights.h +++ b/rendering/common/locallights.h @@ -19,6 +19,7 @@ namespace scene { class basic_region; class basic_cell; +class basic_node; } // namespace scene namespace gfx { @@ -78,6 +79,9 @@ class local_lights void gather(glm::dvec3 const &Camera, scene::basic_region &Region, gfx::geometrybank_manager const &Geometry, unsigned int const Framestamp); // forgets the lights and everything kept about the scene, which is about to be replaced (a scenery being loaded) void reset(); + // a node of the scene is about to go: the lists of the lit instances of the cells, which may hold it, are made anew when the + // cells are visited next + void forget(scene::basic_node const *Node); // the lights of models and vehicles, the most important (closest and brightest) first std::vector const &lights() const { diff --git a/rendering/common/localshadows.h b/rendering/common/localshadows.h index bc50f1da2..b04f4501a 100644 --- a/rendering/common/localshadows.h +++ b/rendering/common/localshadows.h @@ -25,8 +25,8 @@ class opengl_camera; namespace gfx { -// the shadow maps of the lamps (Global.gfx_lights_shadows), the part shared by the renderers (stage P4 of -// claude/vulkan14-renderer-plan.md): which lamps and headlights get maps, when they are drawn, what the shading reads; the +// the shadow maps of the lamps (Global.gfx_lights_shadows), the part shared by the renderers: +// which lamps and headlights get maps, when they are drawn, what the shading reads; the // backend (opengl46_local_shadows, the vulkan renderer) keeps the maps and draws to them through the gpu_* methods. // - the lights of the occupied cab (gfx::local_lights::cab_lights(): its lamps, the lights of its desk), the brightest // Global.gfx_lights_shadows_cab of them, with the shadows cast by the cab (the model drawn by Render_cab()). the map of a light is diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 2e27b081f..fa95b7670 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walk of the scene shared by the renderers (stage N6 of claude/vulkan14-renderer-plan.md): what is drawn in a pass, in +// the walk of the scene shared by the renderers: what is drawn in a pass, in // which order, with which material and transform. the backends get the draws through the walk_* methods, the opengl renderer // makes them at once, the vulkan renderer records them. moved out of opengl46renderer.cpp without changes to what it does diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 1668d74e9..37dbb1b7c 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walk of the scene shared by the renderers (stage N6 of claude/vulkan14-renderer-plan.md, decision K11): the decisions of +// the walk of the scene shared by the renderers: the decisions of // what is drawn in a pass (the sections, cells, tracks, shapes, models, instances, vehicles, the cab, the translucent parts), // in which order, with which material, transform and level of detail. a renderer derives from it and gets the draws through // the walk_* methods: the opengl renderer makes them at once (the same gl calls in the same order as before the walk was @@ -297,7 +297,7 @@ class scene_walk virtual void walk_instances_end() {} // the geometry of the backend and whether it draws blended now, for the draws recorded for the gpu culling virtual gfx::geometrybank_manager &walk_geometry() = 0; - // the walks of the groups of a culling split among several threads (the stage M3 of claude/vulkan14-renderer-plan.md): whether the + // the walks of the groups of a culling split among several threads: whether the // backend does it for this many groups (by default not), and the tasks run, each by a helper given the state of this walk (its // pass, its model block and blending, its recording of the draws), which Work walks a part of the groups with; returns once all of // them are done diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index c526fabce..85f54b699 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ // the part of the shared walk of the scene which feeds the gpu culling of the instances and records the draws made from its -// result (stage N6c of claude/vulkan14-renderer-plan.md): the records of the sleepers and of the models drawn on their own, the +// result: the records of the sleepers and of the models drawn on their own, the // queueing of buckets, the walks of the submodel trees of the culled groups and the order of the recorded draws #include "stdafx.h" diff --git a/rendering/common/shadersource.cpp b/rendering/common/shadersource.cpp index 5d4f4eea0..47373fc18 100644 --- a/rendering/common/shadersource.cpp +++ b/rendering/common/shadersource.cpp @@ -589,6 +589,12 @@ std::vector load_shader_binary(shader_source const &Source, std:: std::lock_guard lock(manifest_mutex); auto const &manifest{manifest_of(directory)}; auto const entry{manifest.entries.find(name)}; + if ((entry == manifest.entries.end()) && Source.has_source) + { + // nothing vouches for the binary, and the source is there to compile from + Reason = name + " isn't in the manifest of " + directory; + return {}; + } if (entry != manifest.entries.end()) { auto const sourcedir{shader_source_dir(Source.api)}; diff --git a/rendering/common/shadersource.h b/rendering/common/shadersource.h index 62fca20e9..1ad572dd7 100644 --- a/rendering/common/shadersource.h +++ b/rendering/common/shadersource.h @@ -170,8 +170,8 @@ shader_source preprocess_shader(shader_api Api, std::string const &Name, std::st std::string const &Basedir = {}); // the SPIR-V binary of a shader from the directory of the binaries of its api. empty when there's none, when the manifest of the -// binaries says the binary was compiled from other sources than those there now, or when the file isn't SPIR-V; Reason says -// which (empty when there's simply no binary) +// binaries says the binary was compiled from other sources than those there now, when the manifest doesn't list it while its +// source is there, or when the file isn't SPIR-V; Reason says which (empty when there's simply no binary) std::vector load_shader_binary(shader_source const &Source, std::string &Reason); // the ids of the specialization constants of a SPIR-V module (OpDecorate ... SpecId) diff --git a/rendering/common/skylight.h b/rendering/common/skylight.h index 28b9b402f..bd8d99f37 100644 --- a/rendering/common/skylight.h +++ b/rendering/common/skylight.h @@ -7,8 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the light of the sky the renderers share (the part of the stage S of claude/gl46-renderer-features-plan.md which isn't the -// work of the gpu, taken out of opengl46_sky for the vulkan renderer, stage P1 of claude/vulkan14-renderer-plan.md): +// the light of the sky the renderers share (the part which isn't the work of the gpu, taken out of opengl46_sky for the vulkan +// renderer): // - the directional part of the ambient light, as spherical harmonics (gl::sky_data), worked out from the colours of the sky // dome or from the physical atmosphere // - the parameters of the physical atmosphere (gl::atmosphere_ubs) and when its look-up tables are to be made again diff --git a/rendering/common/skyocclusion.h b/rendering/common/skyocclusion.h index 80c862b63..3d661cd2a 100644 --- a/rendering/common/skyocclusion.h +++ b/rendering/common/skyocclusion.h @@ -36,8 +36,8 @@ class basic_cell; namespace gfx { -// the occlusion of the sky and of the sun by the scenery around the camera (Global.gfx_skyvisibility, the track T of -// claude/renderers-plan.md), the part shared by the renderers; the backend (opengl46_sky_occlusion, vk14::sky_occlusion_maps) keeps +// the occlusion of the sky and of the sun by the scenery around the camera (Global.gfx_skyvisibility), +// the part shared by the renderers; the backend (opengl46_sky_occlusion, vk14::sky_occlusion_maps) keeps // two textures the shading reads and copies to them what this part works out, through the gpu_* methods. // tunnels, the ground under bridges and roofs, cuttings and the foot of slopes are dark because the geometry around holds back the // sky and the sun, not because of the environment flags of the tracks (tunnel, canyon), which the renderers leave alone now diff --git a/rendering/common/walksync.h b/rendering/common/walksync.h index c99f6650a..5030ee875 100644 --- a/rendering/common/walksync.h +++ b/rendering/common/walksync.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walks of the scene made by several threads at once (the stage M2 of claude/vulkan14-renderer-plan.md). only the vulkan renderer +// the walks of the scene made by several threads at once. only the vulkan renderer // opens the window in which they are (gfx.vulkan.parallelpasses); outside of it everything here does nothing, and the opengl renderer // never opens it. while it's open: // - every thread walking the scene holds the walk lock shared (a pass of a walker from the start to the end, the main thread from the diff --git a/rendering/common/weatherstate.h b/rendering/common/weatherstate.h index b7c254f03..4eb1641c6 100644 --- a/rendering/common/weatherstate.h +++ b/rendering/common/weatherstate.h @@ -7,8 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the weather the renderers draw (the part of the stage F of claude/gl46-renderer-features-plan.md which isn't the work of the -// gpu, taken out of opengl46_weather for the vulkan renderer, stage P2 of claude/vulkan14-renderer-plan.md): the block of the +// the weather the renderers draw (the part which isn't the work of the gpu, taken out of opengl46_weather for the vulkan +// renderer): the block of the // weather of the shaders (gl::weather_ubs) made from the weather of the simulation (environment/weather.h) for the frame and for // each pass, the quality levels, the place of the map of the shadows of the clouds, the bands of the panorama of the clouds, the // sampling of the fog volume over the frames, and the stars of the catalogue (environment/starcatalog.h) diff --git a/rendering/opengl46/opengl46ao.cpp b/rendering/opengl46/opengl46ao.cpp index a5e82d1b1..4198a33cc 100644 --- a/rendering/opengl46/opengl46ao.cpp +++ b/rendering/opengl46/opengl46ao.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -28,18 +31,31 @@ void opengl46_ao::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_main_program = make_compute("gtao_main.comp"); - m_denoise_program = make_compute("gtao_denoise.comp"); + try { + m_main_program = make_compute("gtao_main.comp"); + m_denoise_program = make_compute("gtao_denoise.comp"); gl::shader vertex("quad.vert"); gl::shader fragment("postfx_ssao_apply.frag"); m_apply_program = std::make_unique(std::vector>{vertex, fragment}); } + catch (gl::shader_exception const &e) + { + // off before the viewports are made, which then have no targets for it + ErrorLog(std::format("ambient occlusion not available: {}", e.what())); + m_main_program.reset(); + m_denoise_program.reset(); + m_apply_program.reset(); + Global.gfx_postfx_ao = 0; + return; + } m_vao = std::make_unique(); } void opengl46_ao::compute(opengl_texture &Depth, opengl_texture &Raw, opengl_texture &Smooth, glm::mat4 const &Projection) { + if (m_denoise_program == nullptr) + return; m_timer.begin(); m_timing = true; @@ -70,6 +86,8 @@ void opengl46_ao::compute(opengl_texture &Depth, opengl_texture &Raw, opengl_tex void opengl46_ao::apply(int const Mode, opengl_texture &Depth, opengl_texture &Occlusion, gl::framebuffer &Target, glm::mat4 const &Projection) { + if (m_apply_program == nullptr) + return; Target.bind(); m_apply_program->bind(); m_vao->bind(); diff --git a/rendering/opengl46/opengl46ao.h b/rendering/opengl46/opengl46ao.h index dcc848743..a6e94a710 100644 --- a/rendering/opengl46/opengl46ao.h +++ b/rendering/opengl46/opengl46ao.h @@ -34,7 +34,8 @@ class opengl46_ao opengl46_ao(const opengl46_ao &) = delete; opengl46_ao &operator=(const opengl46_ao &) = delete; - // creates the programs. throws gl::shader_exception + // creates the programs. without them (a shader which doesn't compile) there is no ambient occlusion: logged, and + // gfx.postfx.ao switched off void init(); // ground truth ambient occlusion from the depth of the scene drawn with the given projection: Raw gets the result of // the horizon search, Smooth the smoothed one. both half the size of Depth diff --git a/rendering/opengl46/opengl46cabprobe.cpp b/rendering/opengl46/opengl46cabprobe.cpp index 09afd9b23..67148a31e 100644 --- a/rendering/opengl46/opengl46cabprobe.cpp +++ b/rendering/opengl46/opengl46cabprobe.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -51,20 +53,6 @@ opengl46_cab_probe::~opengl46_cab_probe() void opengl46_cab_probe::init() { - gl::shader vertex("cabprobe.vert"); - gl::shader geometry("cabprobe.geom"); - { - gl::shader fragment("cabprobe.frag"); - m_program = std::make_unique(std::vector>{vertex, geometry, fragment}); - } - { - gl::shader fragment("cabprobe_alpha.frag"); - m_alpha_program = std::make_unique(std::vector>{vertex, geometry, fragment}); - } - { - gl::shader compute("cabprobe_sh.comp"); - m_sh_program = std::make_unique(std::vector>{compute}); - } m_sh = std::make_unique(static_cast(sizeof(gl::cab_probe_data)), gl::CAB_PROBE_SSBO_BINDING); m_sh->update(gl::cab_probe_data{}); @@ -76,6 +64,31 @@ void opengl46_cab_probe::init() glTextureStorage2D(m_white, 1, GL_RGBA8, 1, 1); std::uint8_t const white[4]{255, 255, 255, 255}; glClearTexImage(m_white, 0, GL_RGBA, GL_UNSIGNED_BYTE, white); + + try + { + gl::shader vertex("cabprobe.vert"); + gl::shader geometry("cabprobe.geom"); + { + gl::shader fragment("cabprobe.frag"); + m_program = std::make_unique(std::vector>{vertex, geometry, fragment}); + } + { + gl::shader fragment("cabprobe_alpha.frag"); + m_alpha_program = std::make_unique(std::vector>{vertex, geometry, fragment}); + } + gl::shader compute("cabprobe_sh.comp"); + m_sh_program = std::make_unique(std::vector>{compute}); + } + catch (gl::shader_exception const &e) + { + // the shading reads the stand-ins; no maps are made (gpu_allocate()) + ErrorLog(std::format("cab probe not available: {}", e.what())); + m_program.reset(); + m_alpha_program.reset(); + m_sh_program.reset(); + Global.gfx_cabprobe = 0; + } } void opengl46_cab_probe::bind() @@ -89,6 +102,8 @@ void opengl46_cab_probe::bind() bool opengl46_cab_probe::gpu_allocate(int const Size) { + if (m_sh_program == nullptr) + return false; m_light = make_cube(GL_RGBA16F, Size, true); m_albedo = make_cube(GL_RGBA8, Size, true); m_depth = make_cube(GL_DEPTH_COMPONENT32F, Size, false); diff --git a/rendering/opengl46/opengl46cabprobe.h b/rendering/opengl46/opengl46cabprobe.h index c26f81d31..c920b34de 100644 --- a/rendering/opengl46/opengl46cabprobe.h +++ b/rendering/opengl46/opengl46cabprobe.h @@ -26,7 +26,8 @@ class opengl46_cab_probe : public gfx::cab_probe opengl46_cab_probe() = default; ~opengl46_cab_probe() override; - // creates the programs, the stand-ins and the storage of the spherical harmonics. throws gl::shader_exception + // creates the stand-ins, the storage of the spherical harmonics and the programs. without the programs (a shader which + // doesn't compile) there is no probe: logged, and gfx.cabprobe switched off void init(); // puts the maps (or the stand-ins) on their texture units, gl::CAB_PROBE_TEX, gl::CAB_PROBE_ALBEDO_TEX and the mask on // gl::CAB_PROBE_MASK_TEX, and the spherical harmonics on gl::CAB_PROBE_SSBO_BINDING. once per context and frame diff --git a/rendering/opengl46/opengl46exposure.cpp b/rendering/opengl46/opengl46exposure.cpp index d2b5f3476..ec925dcc7 100644 --- a/rendering/opengl46/opengl46exposure.cpp +++ b/rendering/opengl46/opengl46exposure.cpp @@ -13,8 +13,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -29,11 +32,7 @@ void opengl46_exposure::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_histogram_program = make_compute("exposure_histogram.comp"); - m_average_program = make_compute("exposure_average.comp"); - m_bloom_down = std::make_unique("bloom_down"); - m_bloom_up = std::make_unique("bloom_up"); - + // the tonemapping reads the buffer, also without the passes which work the exposure out m_exposure_ssbo = std::make_unique(sizeof(gl::exposure_data), gl::EXPOSURE_SSBO_BINDING); gl::exposure_data data{}; data.adapted_luminance = Global.gfx_postfx_autoexposure_key; @@ -41,6 +40,31 @@ void opengl46_exposure::init() data.average_luminance = Global.gfx_postfx_autoexposure_key; data.valid = 0; m_exposure_ssbo->update(data); + + try + { + m_histogram_program = make_compute("exposure_histogram.comp"); + m_average_program = make_compute("exposure_average.comp"); + } + catch (gl::shader_exception const &e) + { + ErrorLog(std::format("automatic exposure not available: {}", e.what())); + m_histogram_program.reset(); + m_average_program.reset(); + Global.gfx_postfx_autoexposure = false; + } + try + { + m_bloom_down = std::make_unique("bloom_down"); + m_bloom_up = std::make_unique("bloom_up"); + } + catch (gl::shader_exception const &e) + { + ErrorLog(std::format("bloom not available: {}", e.what())); + m_bloom_down.reset(); + m_bloom_up.reset(); + Global.gfx_postfx_bloom = false; + } } void opengl46_exposure::bind() @@ -76,6 +100,8 @@ std::unique_ptr opengl46_exposure::make_bloom_ch void opengl46_exposure::measure(opengl_texture &Image, double const Deltatime) { + if (m_average_program == nullptr) + return; float data[4]; if (m_readback.pop(data)) std::copy(std::begin(data), std::end(data), std::begin(m_readback_data)); @@ -106,6 +132,8 @@ void opengl46_exposure::measure(opengl_texture &Image, double const Deltatime) opengl_texture *opengl46_exposure::bloom(bloom_chain &Chain, opengl_texture &Image, gl::stream_ubo &Modelubo, gl::model_ubs &Model) { + if (m_bloom_up == nullptr) + return nullptr; m_bloom_timer.begin(); // down, the first step from the image itself for (std::size_t level = 0; level < Chain.sizes.size(); ++level) diff --git a/rendering/opengl46/opengl46exposure.h b/rendering/opengl46/opengl46exposure.h index 44b91a3d3..00f91d7dc 100644 --- a/rendering/opengl46/opengl46exposure.h +++ b/rendering/opengl46/opengl46exposure.h @@ -47,7 +47,8 @@ class opengl46_exposure opengl46_exposure(const opengl46_exposure &) = delete; opengl46_exposure &operator=(const opengl46_exposure &) = delete; - // creates the programs and the buffer. throws gl::shader_exception + // creates the buffer and the programs. a shader which doesn't compile is logged, and gfx.postfx.autoexposure or + // gfx.postfx.bloom switched off void init(); // binds the buffer the tonemapping reads; bindings are context state, so done in every context void bind(); diff --git a/rendering/opengl46/opengl46hiz.cpp b/rendering/opengl46/opengl46hiz.cpp index 142c22867..a431df930 100644 --- a/rendering/opengl46/opengl46hiz.cpp +++ b/rendering/opengl46/opengl46hiz.cpp @@ -13,8 +13,11 @@ http://mozilla.org/MPL/2.0/. #include "gl/ubo.h" #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + opengl46_hiz::~opengl46_hiz() { release(); @@ -22,8 +25,18 @@ opengl46_hiz::~opengl46_hiz() void opengl46_hiz::init() { - gl::shader shader("hiz_build.comp"); - m_program = std::make_unique(std::vector>{shader}); + try + { + gl::shader shader("hiz_build.comp"); + m_program = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + // no pyramid: the instances are culled without the occlusion test + ErrorLog(std::format("occlusion test of the instances not available: {}", e.what())); + m_program.reset(); + Global.gfx_gpucull_occlusion = false; + } } void opengl46_hiz::release() @@ -72,7 +85,7 @@ void opengl46_hiz::allocate(int const Width, int const Height) void opengl46_hiz::build(GLuint const Source, int const Width, int const Height, bool const Second) { - if ((Width <= 0) || (Height <= 0)) + if ((Width <= 0) || (Height <= 0) || (m_program == nullptr)) return; if (m_sourcesize != glm::ivec2{Width, Height}) allocate(Width, Height); diff --git a/rendering/opengl46/opengl46hiz.h b/rendering/opengl46/opengl46hiz.h index c75d6b0bb..9ee48ae7a 100644 --- a/rendering/opengl46/opengl46hiz.h +++ b/rendering/opengl46/opengl46hiz.h @@ -29,7 +29,8 @@ class opengl46_hiz opengl46_hiz(const opengl46_hiz &) = delete; opengl46_hiz &operator=(const opengl46_hiz &) = delete; - // creates the program. throws gl::shader_exception + // creates the program. without it (a shader which doesn't compile) no pyramid is made: logged, and gfx.gpucull.occlusion is + // switched off void init(); // makes the pyramid from the depth attachment of Source, a framebuffer of Width x Height pixels. // leaves the framebuffer bindings alone, texture unit 0 and image unit 0 are used (the unit cache is reset). diff --git a/rendering/opengl46/opengl46instancecull.cpp b/rendering/opengl46/opengl46instancecull.cpp index e36790ef5..a18b1fe23 100644 --- a/rendering/opengl46/opengl46instancecull.cpp +++ b/rendering/opengl46/opengl46instancecull.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -32,6 +35,9 @@ void opengl46_instance_cull::init(opengl46_instance_cull const *Shared) { if (Shared != nullptr) { + // nothing to share when the programs of the one shared aren't there + if (false == Shared->available()) + return; m_shared = Shared->m_shared; share_records(*Shared); } @@ -41,10 +47,21 @@ void opengl46_instance_cull::init(opengl46_instance_cull const *Shared) gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_shared = std::make_shared(); - m_shared->cull_program = make_compute("instance_cull.comp"); - m_shared->offsets_program = make_compute("instance_cull_offsets.comp"); - m_shared->commands_program = make_compute("instance_cull_commands.comp"); + auto shared{std::make_shared()}; + try + { + shared->cull_program = make_compute("instance_cull.comp"); + shared->offsets_program = make_compute("instance_cull_offsets.comp"); + shared->commands_program = make_compute("instance_cull_commands.comp"); + } + catch (gl::shader_exception const &e) + { + // the instances are culled on the cpu + ErrorLog(std::format("instance culling on the gpu not available: {}", e.what())); + Global.gfx_gpucull = 0; + return; + } + m_shared = std::move(shared); m_shared->records = std::make_unique(65536 * RECORD_SIZE, gl::INSTANCE_RECORD_SSBO_BINDING); } diff --git a/rendering/opengl46/opengl46instancecull.h b/rendering/opengl46/opengl46instancecull.h index 7812eac9a..002117399 100644 --- a/rendering/opengl46/opengl46instancecull.h +++ b/rendering/opengl46/opengl46instancecull.h @@ -42,8 +42,14 @@ class opengl46_instance_cull : public gfx::instance_cull opengl46_instance_cull() = default; - // creates the buffers, and the programs and the record buffer, or takes the ones of Shared. throws gl::shader_exception + // creates the buffers, and the programs and the record buffer, or takes the ones of Shared. without the programs (a shader + // which doesn't compile) nothing is made: logged, and gfx.gpucull is switched off void init(opengl46_instance_cull const *Shared = nullptr); + // the programs are there, the culling can run + bool available() const + { + return m_shared != nullptr; + } // runs the culling passes for the buckets added. View: rotation of the view of the pass. Occlusion: the depth pyramid // to test the instances against, or null. Twophase: with the occlusion test, only the instances seen in the previous // frame pass for now, dispatch_second() takes the others diff --git a/rendering/opengl46/opengl46localshadows.cpp b/rendering/opengl46/opengl46localshadows.cpp index 61b0a3c0c..c32f52255 100644 --- a/rendering/opengl46/opengl46localshadows.cpp +++ b/rendering/opengl46/opengl46localshadows.cpp @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -103,6 +105,38 @@ opengl46_local_shadows::~opengl46_local_shadows() } void opengl46_local_shadows::init() +{ + // a shadow sampler with no depth texture to read from is undefined, also where the shading doesn't read it + glCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &m_empty); + glTextureStorage3D(m_empty, 1, GL_DEPTH_COMPONENT32F, 1, 1, 6); + glTextureParameteri(m_empty, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTextureParameteri(m_empty, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); + float const farthest{0.f}; + glClearTexImage(m_empty, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); + m_emptyheadlights = make_array(1, 1); + glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glClearTexImage(m_emptyheadlights, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); + + try + { + init_programs(); + } + catch (gl::shader_exception const &e) + { + // the shading reads the stand-ins; no maps are made (gpu_allocate()) + ErrorLog(std::format("shadows of the lights not available: {}", e.what())); + m_program.reset(); + m_alpha_program.reset(); + m_multidraw_program.reset(); + m_alpha_multidraw_program.reset(); + Global.gfx_lights_shadows = 0; + } +} + +void opengl46_local_shadows::init_programs() { gl::shader vertex("shadowcube.vert"); gl::shader geometry("shadowcube.geom"); @@ -135,20 +169,6 @@ void opengl46_local_shadows::init() m_alpha_multidraw_program.reset(); } set_layer(0); - - // a shadow sampler with no depth texture to read from is undefined, also where the shading doesn't read it - glCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &m_empty); - glTextureStorage3D(m_empty, 1, GL_DEPTH_COMPONENT32F, 1, 1, 6); - glTextureParameteri(m_empty, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTextureParameteri(m_empty, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); - glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); - float const farthest{0.f}; - glClearTexImage(m_empty, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); - m_emptyheadlights = make_array(1, 1); - glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glClearTexImage(m_emptyheadlights, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); } void opengl46_local_shadows::set_near(float const Near) @@ -173,6 +193,9 @@ void opengl46_local_shadows::set_layer(int const Layer) bool opengl46_local_shadows::gpu_allocate(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; m_texture = make_cube_array(Size, Count); m_framebuffer = make_framebuffer(m_texture); return (m_framebuffer != 0); @@ -190,6 +213,9 @@ void opengl46_local_shadows::gpu_release() bool opengl46_local_shadows::gpu_allocate_lamps(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; // the scenery parts and the working copies m_lampstexture = make_cube_array(Size, 2 * Count); m_lampsframebuffer = make_framebuffer(m_lampstexture); @@ -208,6 +234,9 @@ void opengl46_local_shadows::gpu_release_lamps() bool opengl46_local_shadows::gpu_allocate_headlights(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; m_headlightstexture = make_array(Size, Count); glCreateFramebuffers(1, &m_headlightsframebuffer); glNamedFramebufferTextureLayer(m_headlightsframebuffer, GL_DEPTH_ATTACHMENT, m_headlightstexture, 0, 0); diff --git a/rendering/opengl46/opengl46localshadows.h b/rendering/opengl46/opengl46localshadows.h index 225e9e371..e37ce1032 100644 --- a/rendering/opengl46/opengl46localshadows.h +++ b/rendering/opengl46/opengl46localshadows.h @@ -31,7 +31,8 @@ class opengl46_local_shadows : public gfx::local_shadows opengl46_local_shadows() = default; ~opengl46_local_shadows() override; - // creates the programs and the stand-in maps. throws gl::shader_exception + // creates the stand-in maps and the programs. without the programs (a shader which doesn't compile) the lights have no + // shadows: logged, and gfx.lights.shadows is switched off void init(); // puts the maps (or the stand-ins, which shadow nothing) on their texture units, gl::LOCAL_SHADOW_TEX and // gl::LOCAL_SHADOW_LAMPS_TEX. once per context and frame @@ -67,6 +68,8 @@ class opengl46_local_shadows : public gfx::local_shadows void gpu_headlights_timer(bool const Begin) override; private: + // throws gl::shader_exception + void init_programs(); void set_layer(int const Layer); void set_near(float const Near); diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 2196fb3f2..29663ec23 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -31,6 +31,11 @@ http://mozilla.org/MPL/2.0/. #include "rendering/editoroverlay.h" #include +#include +#include +#include +#include + //#define EU07_DEBUG_OPENGL int constexpr EU07_PICKBUFFERSIZE{ 1024 }; // size of (square) textures bound with the pick framebuffer @@ -61,6 +66,61 @@ ErrorCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei l + message ); } +namespace +{ + +// a shader the scene can't be drawn without failed: logged, and on windows the player is told the way a context which can't +// be made is (opengl46backend.cpp), as the game closes then +void shaders_failed(std::string_view const Reason) +{ + ErrorLog(std::format("invalid shader: {}", Reason)); +#ifdef _WIN32 + auto const message{std::format( + "MaSzyna can't draw the scene: a shader of the OpenGL 4.6 renderer could not be compiled by the graphics driver.\n\n" + "Details: {}\n\n" + "Update the graphics driver, or check the shaders folder of the game.", + Reason)}; + MessageBoxA(nullptr, message.c_str(), "MaSzyna", MB_ICONERROR | MB_OK); +#endif +} + +// the most samples a renderbuffer of the format can have; the driver lists the counts from the highest +GLint format_samples(GLenum const Format) +{ + GLint counts{0}; + ::glGetInternalformativ(GL_RENDERBUFFER, Format, GL_NUM_SAMPLE_COUNTS, 1, &counts); + if (counts <= 0) + return 1; + std::vector samples(static_cast(counts), 1); + ::glGetInternalformativ(GL_RENDERBUFFER, Format, GL_SAMPLES, counts, samples.data()); + return std::ranges::max(samples); +} + +// multisampling above what the driver gives the targets of the colour pass (init_viewport()) falls back to the most it gives, +// rather than the targets failing to be made +void clamp_multisampling() +{ + if (Global.iMultisampling <= 0) + return; + GLint maxsamples{1}; + ::glGetIntegerv(GL_MAX_SAMPLES, &maxsamples); + if (false == Global.gfx_skippipeline) + { + maxsamples = std::min({maxsamples, format_samples(Global.gfx_format_color), format_samples(Global.gfx_format_depth)}); + if (Global.gfx_motion_vectors()) + maxsamples = std::min(maxsamples, format_samples(Global.gfx_postfx_motionblur_format)); + } + auto multisampling{Global.iMultisampling}; + while ((multisampling > 0) && ((1 << multisampling) > maxsamples)) + --multisampling; + if (multisampling == Global.iMultisampling) + return; + WriteLog(std::format("multisampling x{} not supported by the graphics driver (at most x{}), using x{}", 1 << Global.iMultisampling, maxsamples, 1 << multisampling)); + Global.iMultisampling = multisampling; +} + +} // namespace + bool opengl46_renderer::Init(GLFWwindow *Window) { if (Global.gfx_gldebug) { @@ -148,7 +208,8 @@ bool opengl46_renderer::Init(GLFWwindow *Window) } catch (gl::shader_exception const &e) { - ErrorLog("invalid shader: " + std::string(e.what())); + // the scene can't be drawn without these + shaders_failed(e.what()); return false; } @@ -205,27 +266,21 @@ bool opengl46_renderer::Init(GLFWwindow *Window) m_scenecommandstream.reset(); } - try - { - m_sky.init(); - m_weather.init(); - m_instancecull.init(); - for (auto &shadowcull : m_shadowcull) - shadowcull.init(&m_instancecull); - m_hiz.init(); - m_timbers.init(); - m_shadowfit.init(); - m_exposure.init(); - m_ao.init(); - m_localshadows.init(); - m_cabprobe.init(); - m_skyocclusion.init(); - } - catch (gl::shader_exception const &e) - { - ErrorLog("invalid shader: " + std::string(e.what())); - return false; - } + // the effects whose shaders don't compile switch themselves off (logged, and their settings put off); the scene is drawn + // without them. they come before the viewports, which leave out the targets of what is off + m_sky.init(); + m_weather.init(); + m_instancecull.init(); + for (auto &shadowcull : m_shadowcull) + shadowcull.init(&m_instancecull); + m_hiz.init(); + m_timbers.init(); + m_shadowfit.init(); + m_exposure.init(); + m_ao.init(); + m_localshadows.init(); + m_cabprobe.init(); + m_skyocclusion.init(); // better initialize with 0 to not crash driver/whole system // when we forget @@ -1488,7 +1543,10 @@ void opengl46_renderer::draw_debug_ui() if (ImGui::Begin("Instance culling")) { char const *modes[]{"cpu", "gpu, drawn from its result", "cpu, compared with the gpu"}; - ImGui::Combo("instance culling (gfx.gpucull)", &Global.gfx_gpucull, modes, IM_ARRAYSIZE(modes)); + if (m_instancecull.available()) + ImGui::Combo("instance culling (gfx.gpucull)", &Global.gfx_gpucull, modes, IM_ARRAYSIZE(modes)); + else + ImGui::TextUnformatted("(instance culling on the gpu not available, see the log)"); if (Global.gfx_gpucull == 1) { ImGui::Checkbox("leave out instances hidden behind the depth drawn before them (gfx.gpucull.occlusion)", &Global.gfx_gpucull_occlusion); @@ -2110,7 +2168,9 @@ if (!Global.gfx_skippipeline) if (Global.gfx_postfx_bloom && vp.bloom) { bloomtexture = m_exposure.bloom(*vp.bloom, *vp.main2_tex, *model_ubo, model_ubs); - bloomlevels = vp.bloom->sizes.size(); + // none when its programs aren't there + if (bloomtexture != nullptr) + bloomlevels = vp.bloom->sizes.size(); } model_ubs.param[0] = m_exposure.tonemap_params(bloomlevels); // the dither goes to the last pass before the window: the chromatic aberration, when it follows @@ -3912,8 +3972,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ ++index; continue; } - if( prepassclass == 2 ) { - m_textures.bind( 0, texture ); + // a texture which isn't there (yet) would leave the one bound before to the alpha test. the draw is left to the colour + // pass, which tests and writes its depth as usual + if( ( prepassclass == 2 ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { + ++index; + continue; } auto const &draw { m_indirectdraws[ index ] }; if( multidrawprogram != nullptr ) { @@ -4016,6 +4079,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ for( std::size_t index = 0; index < count; ) { auto const &draw { m_indirectdraws[ index ] }; auto const texture { Indirect_Shadow_Texture( draw.material ) }; + if( ( texture != null_handle ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { + // a texture which isn't there (yet) would leave the one bound before to the alpha test; no shadow until it is + ++index; + continue; + } auto *multidrawprogram { m_indirectmultidraw ? ( m_cubeshadows ? @@ -4032,9 +4100,6 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ && ( Indirect_Shadow_Texture( m_indirectdraws[ last ].material ) == texture ) ) { ++last; } - if( texture != null_handle ) { - m_textures.bind( 0, texture ); - } multidrawprogram->bind(); auto const drawcount { static_cast( last - index ) }; Bind_Indirect_Blocks( index, drawcount ); @@ -5032,7 +5097,7 @@ std::uint32_t opengl46_renderer::walk_instances(glm::mat4 const *Modelviews, std bool opengl46_renderer::walk_timbers_gpu() const { - return true; + return m_timbers.gpu(); } bool opengl46_renderer::walk_timbers_place(std::vector const &Tracks, bool const Restart) @@ -5484,6 +5549,7 @@ void opengl46_renderer::Update_Pick_Control() void opengl46_renderer::Forget_Node(scene::basic_node const *Node) { + m_locallights.forget(Node); if (m_picksceneryitem == Node) m_picksceneryitem = nullptr; std::replace_if(m_picksceneryitems.begin(), m_picksceneryitems.end(), [Node](scene::basic_node const *Item) { return Item == Node; }, nullptr); @@ -7163,6 +7229,7 @@ bool opengl46_renderer::Init_caps() WriteLog("shadows map size capped at " + std::to_string(m_shadowbuffersize) + "p"); } + clamp_multisampling(); if (Global.iMultisampling) { WriteLog("using multisampling x" + std::to_string(1 << Global.iMultisampling)); diff --git a/rendering/opengl46/opengl46shadowfit.cpp b/rendering/opengl46/opengl46shadowfit.cpp index d84c557c0..bdbe87437 100644 --- a/rendering/opengl46/opengl46shadowfit.cpp +++ b/rendering/opengl46/opengl46shadowfit.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + opengl46_shadow_fit::~opengl46_shadow_fit() { release(); @@ -25,8 +28,20 @@ void opengl46_shadow_fit::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_depthprogram = make_compute("shadow_fit_depth.comp"); - m_boundsprogram = make_compute("shadow_fit_bounds.comp"); + try + { + m_depthprogram = make_compute("shadow_fit_depth.comp"); + m_boundsprogram = make_compute("shadow_fit_bounds.comp"); + } + catch (gl::shader_exception const &e) + { + // the cascades keep to their fixed splits + ErrorLog(std::format("sun shadows fitted to the depth not available: {}", e.what())); + m_depthprogram.reset(); + m_boundsprogram.reset(); + Global.gfx_shadow_sdsm = false; + return; + } m_buffer = std::make_unique(sizeof(gl::shadow_fit_data), gl::SHADOW_FIT_SSBO_BINDING); m_readback = std::make_unique(sizeof(gl::shadow_fit_data)); } @@ -60,7 +75,7 @@ void opengl46_shadow_fit::allocate(int const Width, int const Height) void opengl46_shadow_fit::measure(GLuint const Depth, GLuint const Source, int const Width, int const Height, view const &View, unsigned int const Frame) { - if ((Width <= 0) || (Height <= 0) || (View.range <= 0.f)) + if ((Width <= 0) || (Height <= 0) || (View.range <= 0.f) || (m_boundsprogram == nullptr)) return; m_timer.begin(); diff --git a/rendering/opengl46/opengl46shadowfit.h b/rendering/opengl46/opengl46shadowfit.h index dfc162b49..7accf75a0 100644 --- a/rendering/opengl46/opengl46shadowfit.h +++ b/rendering/opengl46/opengl46shadowfit.h @@ -32,7 +32,8 @@ class opengl46_shadow_fit : public gfx::shadow_fit opengl46_shadow_fit(const opengl46_shadow_fit &) = delete; opengl46_shadow_fit &operator=(const opengl46_shadow_fit &) = delete; - // creates the programs and the buffer. throws gl::shader_exception + // creates the programs and the buffer. without the programs (a shader which doesn't compile) nothing is measured: logged, + // and gfx.shadow.sdsm switched off void init(); // measures the depth of the view: Depth, its resolved depth texture of Width x Height pixels, or 0 to resolve the depth // attachment of Source, the multisampled framebuffer, into a texture of its own. Frame: the frame of the renderer. diff --git a/rendering/opengl46/opengl46sky.cpp b/rendering/opengl46/opengl46sky.cpp index ed21906a4..9f87800a5 100644 --- a/rendering/opengl46/opengl46sky.cpp +++ b/rendering/opengl46/opengl46sky.cpp @@ -11,9 +11,11 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46sky.h" #include +#include #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" @@ -47,11 +49,33 @@ void opengl46_sky::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_transmittance_program = make_compute("atmosphere_transmittance.comp"); - m_multiscattering_program = make_compute("atmosphere_multiscattering.comp"); - m_skyview_program = make_compute("atmosphere_skyview.comp"); - m_ambient_program = make_compute("atmosphere_ambient.comp"); - m_prefilter_program = make_compute("envmap_prefilter.comp"); + try + { + m_transmittance_program = make_compute("atmosphere_transmittance.comp"); + m_multiscattering_program = make_compute("atmosphere_multiscattering.comp"); + m_skyview_program = make_compute("atmosphere_skyview.comp"); + m_ambient_program = make_compute("atmosphere_ambient.comp"); + } + catch (gl::shader_exception const &e) + { + // the sky of the sky dome, as without the atmosphere + ErrorLog(std::format("physical atmosphere not available: {}", e.what())); + m_transmittance_program.reset(); + m_multiscattering_program.reset(); + m_skyview_program.reset(); + m_ambient_program.reset(); + Global.gfx_atmosphere = false; + } + try + { + m_prefilter_program = make_compute("envmap_prefilter.comp"); + } + catch (gl::shader_exception const &e) + { + // the rough reflections keep to the mipmaps of the environment map + ErrorLog(std::format("rough reflections of the environment map not available: {}", e.what())); + Global.gfx_envmap_ggx = false; + } m_sky_ssbo = std::make_unique(sizeof(gl::sky_data), gl::SKY_SSBO_BINDING); m_sky_ssbo->update(m_sky_data); @@ -75,6 +99,8 @@ void opengl46_sky::bind() void opengl46_sky::update_atmosphere(glm::vec3 const &Sundirection) { + if (m_ambient_program == nullptr) + return; bool mediumchanged{false}; if (false == m_light.atmosphere_changed(Sundirection, mediumchanged)) return; @@ -151,6 +177,8 @@ glm::vec3 opengl46_sky::sun_disc_color(glm::vec3 const &Oldcolor) const void opengl46_sky::prefilter(gl::cubemap const &Source) { + if (m_prefilter_program == nullptr) + return; if (!m_prefiltered) { m_prefiltered = std::make_unique(); diff --git a/rendering/opengl46/opengl46sky.h b/rendering/opengl46/opengl46sky.h index 7cc44a2cc..c5fbba8c1 100644 --- a/rendering/opengl46/opengl46sky.h +++ b/rendering/opengl46/opengl46sky.h @@ -43,7 +43,8 @@ class opengl46_sky opengl46_sky(const opengl46_sky &) = delete; opengl46_sky &operator=(const opengl46_sky &) = delete; - // creates the buffers, tables and programs. throws gl::shader_exception + // creates the buffers, tables and programs. a shader which doesn't compile is logged, and gfx.atmosphere or gfx.envmap.ggx + // switched off void init(); // binds the buffers the shaders read; bindings are context state, so done in every context void bind(); diff --git a/rendering/opengl46/opengl46timbers.cpp b/rendering/opengl46/opengl46timbers.cpp index e6d122ff6..39579ed84 100644 --- a/rendering/opengl46/opengl46timbers.cpp +++ b/rendering/opengl46/opengl46timbers.cpp @@ -11,15 +11,20 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46timbers.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "world/Track.h" +#include #include +#include namespace { // the buffer to start with, and how soon after being started over it's too small for the tracks in sight std::uint32_t constexpr initial_capacity{65536}; unsigned int constexpr restart_frames{600}; +// how much bigger than the room for the instances to place a buffer grows by being started over soon +std::uint64_t constexpr restart_growth{8}; // the instances of a track, in the order they lie in the buffer std::uint32_t count_of(track_sleepers::laid const &Laid) @@ -30,6 +35,20 @@ std::uint32_t count_of(track_sleepers::laid const &Laid) return static_cast(count); } +// a buffer for Capacity instances, 0 when there's no memory for it +GLuint make_buffer(std::uint64_t const Capacity) +{ + GLuint buffer{0}; + glCreateBuffers(1, &buffer); + glNamedBufferStorage(buffer, static_cast(Capacity * sizeof(glm::mat4)), nullptr, GL_DYNAMIC_STORAGE_BIT); + if (::glGetError() == GL_OUT_OF_MEMORY) + { + glDeleteBuffers(1, &buffer); + return 0; + } + return buffer; +} + } // namespace opengl46_timbers::~opengl46_timbers() @@ -40,30 +59,58 @@ opengl46_timbers::~opengl46_timbers() void opengl46_timbers::init() { - gl::shader shader("timber_instances.comp"); - m_program = std::make_unique(std::vector>{shader}); + try + { + gl::shader shader("timber_instances.comp"); + m_program = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + // the walk turns the instances on the cpu + ErrorLog(std::format("track sleepers on the gpu not available: {}", e.what())); + m_gpu = false; + return; + } // the modelviews of the origins and the runs, both placed at whole matrices m_ranges = std::make_unique( static_cast(4096 * sizeof(gl::timber_range)), static_cast(sizeof(glm::mat4)), Global.gfx_bufferstreaming); restart(0); + m_gpu = (false == m_failed); } -void opengl46_timbers::restart(std::uint32_t const Needed) +bool opengl46_timbers::restart(std::uint32_t const Needed) { - auto capacity{std::max(m_capacity, initial_capacity)}; + // room for twice the instances to place, and when the buffer was started over not long before, the tracks in sight change + // fast: twice the buffer before, but not more than restart_growth times that room. a buffer started over later goes back to it + std::uint64_t minimum{initial_capacity}; + while (minimum < 2 * static_cast(Needed)) + minimum *= 2; + auto capacity{minimum}; if ((m_capacity > 0) && (m_frame - m_restartframe < restart_frames)) - capacity *= 2; - while (capacity < 2 * Needed) - capacity *= 2; + capacity = std::clamp(2 * static_cast(m_capacity), minimum, restart_growth * minimum); + auto buffer{make_buffer(capacity)}; + if ((buffer == 0) && (capacity > Needed)) + { + // no memory for the room to spare: only the instances to place + capacity = std::max(Needed, 1); + buffer = make_buffer(capacity); + } + if (buffer == 0) + { + // the old buffer stays, the tracks are turned on the cpu from the next frame on + ErrorLog("openGL error: out of memory; failed to create the buffer of the track sleepers, they're placed by the cpu"); + m_failed = true; + return false; + } // the draws and passes issued with the old buffer keep it until the gpu is done with them if (m_buffer != 0) glDeleteBuffers(1, &m_buffer); - glCreateBuffers(1, &m_buffer); - glNamedBufferStorage(m_buffer, static_cast(capacity) * static_cast(sizeof(glm::mat4)), nullptr, GL_DYNAMIC_STORAGE_BIT); - m_capacity = capacity; + m_buffer = buffer; + m_capacity = static_cast(capacity); m_fill = 0; m_restartframe = m_frame; m_tracks.clear(); + return true; } bool opengl46_timbers::place(std::vector const &Tracks, bool const Restart) @@ -85,9 +132,8 @@ bool opengl46_timbers::place(std::vector const &Tracks, bool const Res return true; if (m_fill + needed > m_capacity) { - if (false == Restart) + if ((false == Restart) || (false == restart(all))) return false; - restart(all); } for (auto const *track : Tracks) { @@ -148,5 +194,9 @@ void opengl46_timbers::expand(std::vector const &Origins, std::vector void opengl46_timbers::next_frame() { ++m_frame; - m_ranges->next_frame(); + if (m_ranges) + m_ranges->next_frame(); + // between the frames, so the walks of a frame all gather and draw the timbers the same way + if (m_failed) + m_gpu = false; } diff --git a/rendering/opengl46/opengl46timbers.h b/rendering/opengl46/opengl46timbers.h index 5790e8f2e..b09794d26 100644 --- a/rendering/opengl46/opengl46timbers.h +++ b/rendering/opengl46/opengl46timbers.h @@ -31,7 +31,7 @@ class opengl46_timbers opengl46_timbers &operator=(opengl46_timbers const &) = delete; ~opengl46_timbers(); - // throws gl::shader_exception + // without the program (a shader which doesn't compile) the walk turns the instances on the cpu (gpu()), logged void init(); // the instances of the tracks on the gpu, sent again for a track laid anew since; when those to send don't fit in what's left // of the buffer, it's started over for all the tracks, a bigger one when it was started over not long before. without @@ -43,6 +43,12 @@ class opengl46_timbers // the runs written to the instance buffer Output, each as the modelview of its origin times its transforms, for the draws after void expand(std::vector const &Origins, std::vector const &Ranges, GLuint const Output); void next_frame(); + // the instances are kept and turned on the gpu; false from the frame after a buffer for them couldn't be had, then the walk + // turns them on the cpu + bool gpu() const + { + return m_gpu; + } private: struct placed @@ -51,8 +57,8 @@ class opengl46_timbers std::uint32_t first; }; - // a new buffer, room for Needed instances at least, the tracks to be sent again - void restart(std::uint32_t const Needed); + // a new buffer, room for Needed instances at least, the tracks to be sent again. false: no memory for it, the old one stays + bool restart(std::uint32_t const Needed); std::unique_ptr m_program; std::unique_ptr m_ranges; @@ -61,6 +67,8 @@ class opengl46_timbers std::uint32_t m_fill{0}; unsigned int m_frame{0}; unsigned int m_restartframe{0}; + bool m_failed{false}; // a buffer couldn't be had + bool m_gpu{true}; std::unordered_map m_tracks; std::vector m_upload; // the origins and the runs of an expand(), as they're sent }; diff --git a/rendering/opengl46/opengl46weather.cpp b/rendering/opengl46/opengl46weather.cpp index d3f407445..18c6ecd7c 100644 --- a/rendering/opengl46/opengl46weather.cpp +++ b/rendering/opengl46/opengl46weather.cpp @@ -15,8 +15,11 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -76,20 +79,34 @@ GLuint opengl46_weather::create_texture(GLenum const Target, GLenum const Format void opengl46_weather::init() { - m_noise_program = make_compute("clouds_noise.comp"); - m_march_program = make_compute("clouds_march.comp"); - m_temporal_program = make_compute("clouds_temporal.comp"); - m_shadow_program = make_compute("clouds_shadow.comp"); - m_horizon_program = make_compute("fog_horizon.comp"); - m_inject_program = make_compute("fog_inject.comp"); - m_integrate_program = make_compute("fog_integrate.comp"); - m_sky_program = make_program("quad.vert", "sky_weather.frag"); - m_stars_program = make_program("stars.vert", "stars.frag"); + try + { + m_noise_program = make_compute("clouds_noise.comp"); + m_march_program = make_compute("clouds_march.comp"); + m_temporal_program = make_compute("clouds_temporal.comp"); + m_shadow_program = make_compute("clouds_shadow.comp"); + m_horizon_program = make_compute("fog_horizon.comp"); + m_inject_program = make_compute("fog_inject.comp"); + m_integrate_program = make_compute("fog_integrate.comp"); + m_sky_program = make_program("quad.vert", "sky_weather.frag"); + m_stars_program = make_program("stars.vert", "stars.frag"); + } + catch (gl::shader_exception const &e) + { + // the fog along the ray, no clouds, no stars, the sky as it's drawn without them; the shading reads the block below + ErrorLog(std::format("clouds, volumetric fog and stars not available: {}", e.what())); + for (auto *program : {&m_noise_program, &m_march_program, &m_temporal_program, &m_shadow_program, &m_horizon_program, &m_inject_program, &m_integrate_program, + &m_sky_program, &m_stars_program}) + program->reset(); + Global.gfx_clouds = 0; + Global.gfx_fog = 0; + } m_weather_ubo = std::make_unique(sizeof(gl::weather_ubs), gl::WEATHER_UBO_BINDING); m_weather_ubo->update(m_state.block()); - make_noise(); + if (m_noise_program != nullptr) + make_noise(); auto const stars{gfx::weather_state::star_vertices()}; m_stars_count = static_cast(stars.size() / 2); @@ -172,8 +189,9 @@ void opengl46_weather::upload_header() void opengl46_weather::update(opengl46_sky const &Sky, glm::vec3 const &Keylight, glm::vec3 const &Keycolor, glm::vec3 const &Ambient, glm::vec3 const &Fogcolor, glm::dvec3 const &Camera) { - m_state.update(Sky.atmosphere_weight(), Sky.skyview_table() != 0, Keylight, Keycolor, Ambient, Fogcolor, Camera); - auto const shadows{m_state.shadows_wanted()}; + // without the programs the colours of the horizon are worked out here, and the clouds left out + m_state.update(Sky.atmosphere_weight(), (Sky.skyview_table() != 0) && (m_horizon_program != nullptr), Keylight, Keycolor, Ambient, Fogcolor, Camera); + auto const shadows{m_state.shadows_wanted() && (m_shadow_program != nullptr)}; if (shadows) { if (m_shadow_size != Global.gfx_clouds_shadows_size) @@ -219,7 +237,7 @@ void opengl46_weather::update(opengl46_sky const &Sky, glm::vec3 const &Keylight m_state.shadows_drawn(false); // a band of the panorama of the clouds, all of it the first time - if (m_state.clouds_drawn()) + if (m_state.clouds_drawn() && (m_march_program != nullptr)) { auto const level{gfx::weather_state::quality(Global.gfx_clouds, Global.gfx_fog_quality)}; if (m_panorama_size != level.panorama) @@ -282,6 +300,8 @@ void opengl46_weather::prepare_view(glm::ivec2 const &Size, quality_level const void opengl46_weather::render_view(glm::mat4 const &Projection, glm::mat4 const &View, glm::dvec3 const &Camera, glm::ivec2 const &Size, int const Cablamps) { + if (m_march_program == nullptr) + return; auto const level{gfx::weather_state::quality(Global.gfx_clouds, Global.gfx_fog_quality)}; prepare_view(Size, level); auto const rotation{glm::mat4{glm::mat3{View}}}; @@ -387,7 +407,7 @@ void opengl46_weather::setup_pass(bool const Volume, glm::ivec2 const &Size) void opengl46_weather::draw_stars(glm::mat4 const &View, float const Sunangle, double const Siderealtime, double const Latitude) { - if (!m_stars_vao || m_stars_count == 0) + if (!m_stars_vao || m_stars_count == 0 || !m_stars_program) return; glm::mat4 toworld, toview; glm::vec4 params; @@ -407,6 +427,8 @@ void opengl46_weather::draw_stars(glm::mat4 const &View, float const Sunangle, d void opengl46_weather::draw_sky(glm::mat4 const &Projection, glm::mat4 const &View, bool const Mainview) { + if (m_sky_program == nullptr) + return; int mode{0}; if (m_state.clouds_drawn()) { diff --git a/rendering/opengl46/opengl46weather.h b/rendering/opengl46/opengl46weather.h index 58ce30036..10a6efbad 100644 --- a/rendering/opengl46/opengl46weather.h +++ b/rendering/opengl46/opengl46weather.h @@ -43,7 +43,8 @@ class opengl46_weather opengl46_weather(const opengl46_weather &) = delete; opengl46_weather &operator=(const opengl46_weather &) = delete; - // creates the programs, buffers and noise textures. throws gl::shader_exception + // creates the programs, buffers and noise textures. without the programs (a shader which doesn't compile) there are no + // clouds, volumetric fog and stars: logged, and gfx.clouds and gfx.fog switched off void init(); // binds the buffer and textures the shading reads; bindings are context state, so done in every context void bind(); diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index cdf1b778c..2bbca3551 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -674,6 +674,8 @@ struct vulkan14_renderer::context std::uint64_t present_id{0}; // when the main thread handed it over to the render thread std::chrono::steady_clock::time_point handed{}; + // the frame couldn't be recorded or submitted, the device not lost: left out (skip_frame()), its images aren't presented + bool skipped{false}; }; // the render thread and the job it's given std::thread render_thread; @@ -700,8 +702,14 @@ struct vulkan14_renderer::context // the job done; false: Failure says where it failed bool execute(render_job &Job, char const *&Failure); - // the part of it before the presents: its command buffers recorded and submitted + // the part of it before the presents: its command buffers recorded and submitted. a frame which can't be (out of memory and the + // like) is left out, false only when the device is lost bool submit(render_job &Job, char const *&Failure); + // the frame which failed at What left out: its uploads (with Compute after the part of the compute queue submitted) and the waits + // and the signals of the frame, without the rest of it; false when that can't be submitted either + bool skip_frame(render_job &Job, bool Compute, char const *What, char const *&Failure); + // the frames left out so far (skip_frame(), the render thread or the main thread without it) + std::uint64_t skipped_frames{0}; // the windows of the frame submitted last presented, the frames generated for the main window before it (spread over the time // of a frame when there's the render thread to wait); Id: the id of the present of the main window (0: none); false: the device is lost // (a lost surface is made anew by its swapchain) diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index b1e2f25e8..9a033978a 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1077,6 +1077,15 @@ bool vulkan14_renderer::Render() report_device_lost(failure); return false; } + if (job.skipped) + { + // the frame was left out: its images aren't presented (SwapBuffers()) + for (auto *window : ctx.acquired) + { + window->drop_images(); + } + ctx.acquired.clear(); + } frame.done = ctx.timelinevalue = value; } @@ -2077,7 +2086,9 @@ void vulkan14_renderer::setup_screen_reflections(std::size_t const Index, bool c // the ray traced reflections, of the main view only (as the screen space ones, which they fill in) bool vulkan14_renderer::raytracing_wanted(viewport_config const &Viewport) const { - if ((false == m_raytracingon) || (false == bool(m_context->scene.raytracing)) || (false == Viewport.main) || Global.bWireFrame || Global.gfx_skippipeline) + // not while the set of the frame has no structure to trace through (ray_tracing::begin_frame() without memory for it) + if ((false == m_raytracingon) || (false == bool(m_context->scene.raytracing)) || (false == m_context->scene.raytracing->traceable(m_context->slot)) || (false == Viewport.main) || Global.bWireFrame || + Global.gfx_skippipeline) { return false; } @@ -4426,6 +4437,7 @@ scene::basic_node const *vulkan14_renderer::Pick_Node() const void vulkan14_renderer::Forget_Node(scene::basic_node const *Node) { + m_locallights.forget(Node); if (m_picksceneryitem == Node) { m_picksceneryitem = nullptr; diff --git a/rendering/vulkan14/vulkan14raytracing.h b/rendering/vulkan14/vulkan14raytracing.h index 076364806..52684d777 100644 --- a/rendering/vulkan14/vulkan14raytracing.h +++ b/rendering/vulkan14/vulkan14raytracing.h @@ -89,6 +89,12 @@ class ray_tracing { return (Slot < m_frames.size() ? m_frames[Slot].set : VK_NULL_HANDLE); } + // the set of the frame holds a structure and its records, which the rays may be traced through: not when begin_frame() had no + // memory for them (the shaders read the set only where the rays are traced) + bool traceable(std::uint32_t const Slot) const + { + return (Slot < m_frames.size()) && (m_frames[Slot].written_top != VK_NULL_HANDLE) && (m_frames[Slot].written_records != VK_NULL_HANDLE); + } // a scenery is being loaded, or the geometry is gone: the bottom level structures go void clear(std::uint64_t Value); // for the debug panel: the structures, their memory, the instances of the last frame diff --git a/rendering/vulkan14/vulkan14renderer.cpp b/rendering/vulkan14/vulkan14renderer.cpp index e49b9ce0c..5d07dd832 100644 --- a/rendering/vulkan14/vulkan14renderer.cpp +++ b/rendering/vulkan14/vulkan14renderer.cpp @@ -273,8 +273,7 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) } if (false == record(frame, Job.uploaded, Job.async)) { - Failure = "recording a frame"; - return false; + return skip_frame(Job, false, "recording a frame", Failure); } if (Job.async) { @@ -300,10 +299,15 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) compute.pCommandBufferInfos = &buffer; compute.signalSemaphoreInfoCount = 1; compute.pSignalSemaphoreInfos = &signal; - if (!VK14_VERIFY(vkQueueSubmit2(device.compute_queue(), 1, &compute, VK_NULL_HANDLE))) + if (auto const result{vkQueueSubmit2(device.compute_queue(), 1, &compute, VK_NULL_HANDLE)}; false == vk14::verify_result(result, "vkQueueSubmit2(compute)", __FILE__, __LINE__)) { - Failure = "submitting the async compute of a frame"; - return false; + // a failed submit leaves the semaphores as they were: the frame is left out, unless the device is lost + if (result == VK_ERROR_DEVICE_LOST) + { + Failure = "submitting the async compute of a frame"; + return false; + } + return skip_frame(Job, false, "submitting the async compute of a frame", Failure); } } // the uploads first, in the same submit: their barriers make them done before the frame uses what they copied @@ -359,10 +363,14 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) submit.pCommandBufferInfos = commands.data() + (Job.async ? first : 0); submit.signalSemaphoreInfoCount = static_cast(Job.signals.size()); submit.pSignalSemaphoreInfos = Job.signals.data(); - if (!VK14_VERIFY(vkQueueSubmit2(device.graphics_queue(), count, submits.data(), VK_NULL_HANDLE))) + if (auto const result{vkQueueSubmit2(device.graphics_queue(), count, submits.data(), VK_NULL_HANDLE)}; false == vk14::verify_result(result, "vkQueueSubmit2", __FILE__, __LINE__)) { - Failure = "submitting a frame"; - return false; + if (result == VK_ERROR_DEVICE_LOST) + { + Failure = "submitting a frame"; + return false; + } + return skip_frame(Job, Job.async, "submitting a frame", Failure); } if (lowlatency) { @@ -371,6 +379,52 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) return true; } +// the timeline reaches the value of the frame and the semaphores of its images are waited for and signalled as with the frame drawn; +// the uploads go with it, as what they copy is used by the frames after it. the images of the windows stay acquired, their +// swapchains are made anew (the main thread drops those it presents itself, Render()) +bool vulkan14_renderer::context::skip_frame(render_job &Job, bool const Compute, char const *What, char const *&Failure) +{ + auto waits{Job.waits}; + if (Compute) + { + VkSemaphoreSubmitInfo compute{}; + compute.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO; + compute.semaphore = compute_timeline; + compute.value = Job.value; + compute.stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; + waits.push_back(compute); + } + VkCommandBufferSubmitInfo uploadbuffer{}; + uploadbuffer.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO; + uploadbuffer.commandBuffer = Job.target->uploads; + VkSubmitInfo2 empty{}; + empty.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2; + empty.waitSemaphoreInfoCount = static_cast(waits.size()); + empty.pWaitSemaphoreInfos = waits.data(); + empty.commandBufferInfoCount = (Job.uploaded ? 1 : 0); + empty.pCommandBufferInfos = &uploadbuffer; + empty.signalSemaphoreInfoCount = static_cast(Job.signals.size()); + empty.pSignalSemaphoreInfos = Job.signals.data(); + if (false == VK14_VERIFY(vkQueueSubmit2(device.graphics_queue(), 1, &empty, VK_NULL_HANDLE))) + { + Failure = What; + return false; + } + for (auto *window : Job.windows) + { + window->drop_images(); + } + Job.windows.clear(); + Job.skipped = true; + // said the first time, then now and then while it goes on + ++skipped_frames; + if ((skipped_frames % 600) == 1) + { + vk14::log_error(std::string(What) + " failed, the frame is left out (" + std::to_string(skipped_frames) + " so far)"); + } + return true; +} + bool vulkan14_renderer::context::present(std::vector const &Windows, std::uint64_t const Id) { auto *main{windows.empty() ? nullptr : windows.front().get()}; diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 03ea1e634..7184e7ba5 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the vulkan 1.4 renderer, picked with gfxrenderer vulkan (claude/vulkan14-renderer-plan.md): the gpu, the windows with their +// the vulkan 1.4 renderer, picked with gfxrenderer vulkan: the gpu, the windows with their // swapchains, the frames in flight, the memory and the uploads, the shaders and the pipelines, the pushed descriptors, the passes // with their barriers and gpu times, the textures and the user interface (imgui) with the launcher (the track R of the plan), and // the scene (the track D): the geometry, the materials, the passes of the colour of the scene with the sun shadows, the diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index a194eb08f..75d580bb2 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -59,6 +59,25 @@ VkPrimitiveTopology topology_class(VkPrimitiveTopology const Topology) } } +// the instances of a draw (one when it isn't instanced) within the window of the ring the pass set reads, from its first one on: +// walk_instances() places at most a window of them, those past it aren't drawn. the instances of a culled pass aren't in the window +std::uint32_t drawn_instances(std::size_t const Count, std::uint32_t const First, VkDeviceSize const Capacity, bool const Culled) +{ + if (Count == 0) + { + return 1; + } + if (Culled) + { + return static_cast(Count); + } + if (First >= Capacity) + { + return 0; + } + return static_cast(std::min(Count, Capacity - First)); +} + vk14::vertex_layout layout_of(vk14::vertex_kind const Kind) { vk14::vertex_layout layout; @@ -2090,6 +2109,13 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co m_prepassincomplete = (m_prepassincomplete || draw.depthpass); return; } + auto const instances{drawn_instances(m_current_instance_count, m_current_instance_base, m_context->scene.instances.window / m_context->scene.instances.stride, draw.cull_sets != nullptr)}; + if (instances == 0) + { + // all of them past the window of their ring (walk_instances() places at most a window of them) + m_prepassincomplete = (m_prepassincomplete || draw.depthpass); + return; + } auto &ctx{*m_context}; auto &scene{ctx.scene}; auto const commands{draw.commands}; @@ -2140,7 +2166,6 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co draw.vertices = chunk.vertices; draw.userdata = chunk.userdata; } - auto const instances{m_current_instance_count > 0 ? static_cast(m_current_instance_count) : 1u}; auto const firstinstance{m_current_instance_count > 0 ? m_current_instance_base : 0u}; if (chunk.indices != VK_NULL_HANDLE) { diff --git a/rendering/vulkan14/vulkan14swapchain.cpp b/rendering/vulkan14/vulkan14swapchain.cpp index 314537cab..7ceb07941 100644 --- a/rendering/vulkan14/vulkan14swapchain.cpp +++ b/rendering/vulkan14/vulkan14swapchain.cpp @@ -14,6 +14,9 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14device.h" #include "utilities/Globals.h" +#include +#include + namespace vk14 { @@ -386,6 +389,8 @@ swapchain::acquire_result swapchain::acquire(std::uint32_t const Frame, std::uin m_states.resize(m_images.size()); } m_states[m_image] = image_state{VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_2_NONE}; + ++m_acquired; + destroy_retired(false); } // the images of the generated frames, shown before the one drawn; the swapchain has one image more for each of them, so the // images of a frame can all be acquired. one which can't be had leaves fewer of them @@ -599,25 +604,42 @@ void swapchain::release_images() vkDestroyImageView(device, view, nullptr); } } - for (auto semaphore : m_presentsemaphores) - { - if (semaphore != VK_NULL_HANDLE) - { - vkDestroySemaphore(device, semaphore, nullptr); - } - } + // the presentation may still wait for the semaphores after the queue is idle: kept till an image of the next swapchain comes back + std::ranges::copy_if(m_presentsemaphores, std::back_inserter(m_retiredsemaphores), [](VkSemaphore const Semaphore) { return Semaphore != VK_NULL_HANDLE; }); + m_acquired = 0; m_views.clear(); m_presentsemaphores.clear(); m_images.clear(); m_states.clear(); } +void swapchain::destroy_retired(bool const Now) +{ + // an image acquired more times than the swapchain has of them was acquired twice, and so came back from a present queued after + // those of the swapchains before + if (m_retiredsemaphores.empty() || ((false == Now) && (m_acquired <= m_images.size()))) + { + return; + } + auto const device{m_device != nullptr ? m_device->handle() : VK_NULL_HANDLE}; + if (device == VK_NULL_HANDLE) + { + return; + } + for (auto const semaphore : m_retiredsemaphores) + { + vkDestroySemaphore(device, semaphore, nullptr); + } + m_retiredsemaphores.clear(); +} + void swapchain::destroy() { auto const device{m_device != nullptr ? m_device->handle() : VK_NULL_HANDLE}; if (device != VK_NULL_HANDLE) { release_images(); + destroy_retired(true); if (m_swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, m_swapchain, nullptr); diff --git a/rendering/vulkan14/vulkan14swapchain.h b/rendering/vulkan14/vulkan14swapchain.h index 7183d26de..2079ec0c8 100644 --- a/rendering/vulkan14/vulkan14swapchain.h +++ b/rendering/vulkan14/vulkan14swapchain.h @@ -104,6 +104,12 @@ class swapchain } // the result of the presentation of the image: out of date or suboptimal makes the swapchain anew before the next image void presented(VkResult const Result); + // the images acquired for a frame left out aren't presented: they stay acquired and their present semaphores signalled, so the + // swapchain is made anew before the next image + void drop_images() + { + m_rebuild = true; + } // the most images of the generated frames it can acquire with an image (as made, within what the program may hold at once) std::uint32_t generated_room() const { @@ -168,7 +174,11 @@ class swapchain bool restore_surface(std::string &Reason); // what a result of the surface, the swapchain or a present says of them: the device or the surface is lost void note_failure(VkResult Result); + // the views of the images go, their present semaphores are kept till the presentation is done with them (destroy_retired()) void release_images(); + // the present semaphores of the swapchains before this one, once an image of this one came back from the presentation: the + // presents queued before it are done by then. all of them with Now + void destroy_retired(bool Now); // whether the swapchain has to be made anew before the next image bool outdated() const; @@ -200,6 +210,11 @@ class swapchain std::vector m_views; // one per image: a semaphore given to the presentation can be reused only once the image comes back std::vector m_presentsemaphores; + // those of the swapchains before this one: a wait of the queue doesn't say the presentation is done with them (that only + // VK_KHR_swapchain_maintenance1 tells, which the device isn't made with), an image of this one acquired twice does. the images + // acquired from this one so far + std::vector m_retiredsemaphores; + std::size_t m_acquired{0}; // one per frame in flight (and one more for each generated frame): free again once the frame which waited for it is done std::vector m_acquiresemaphores; std::uint32_t m_image{0}; diff --git a/rendering/vulkan14/vulkan14walkers.cpp b/rendering/vulkan14/vulkan14walkers.cpp index 76ade7413..3e6fc9605 100644 --- a/rendering/vulkan14/vulkan14walkers.cpp +++ b/rendering/vulkan14/vulkan14walkers.cpp @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the passes walked by the walkers (the stage M2 of claude/vulkan14-renderer-plan.md, gfx.vulkan.parallelpasses). the main thread sets +// the passes walked by the walkers (gfx.vulkan.parallelpasses). the main thread sets // a pass up as it would walk it itself (the camera, the culling, the map it draws to with its barrier, the timestamps around it), hands // the state of the frame over to a walker, splices the stream the walker records into the commands of the frame there and goes on with // the frame; the walkers walk the passes at the same time as the main thread walks the colour pass of the main view, and are joined once diff --git a/shaders/README.md b/shaders/README.md index f11326e6f..34c7122f9 100644 --- a/shaders/README.md +++ b/shaders/README.md @@ -24,7 +24,8 @@ compiles every shader of `ogl46/` (with the variant `MODEL_DRAWS` of the vertex glslc --target-env=opengl4.5 -DMODEL_DRAWS=1 ogl46/vertex.vert -o ogl46bin/vertex.vert.MODEL_DRAWS.spv glslc --target-env=vulkan1.4 vk14/imgui.frag -o vk14bin/imgui.frag.spv -A binary made by hand isn't in the manifest, so it is taken without being compared with its source. After a change of a +A binary made by hand isn't in the manifest, so it is used only where its source isn't there (otherwise the source is compiled +and the log says so). After a change of a source, compile the binaries again (or delete them): a binary older than its source is not used, and the log says so. ## Writing shaders diff --git a/shaders/compile_spirv.py b/shaders/compile_spirv.py index 061783c1a..da0aa3053 100644 --- a/shaders/compile_spirv.py +++ b/shaders/compile_spirv.py @@ -12,7 +12,7 @@ # glslc --target-env=opengl4.5 shaders/ogl46/mat_default.frag -o shaders/ogl46bin/mat_default.frag.spv # glslc --target-env=opengl4.5 -DMODEL_DRAWS=1 shaders/ogl46/vertex.vert -o shaders/ogl46bin/vertex.vert.MODEL_DRAWS.spv # glslc --target-env=vulkan1.4 shaders/vk14/imgui.frag -o shaders/vk14bin/imgui.frag.spv -# (a binary compiled by hand isn't in the manifest, so the game takes it without comparing it with its sources) +# (a binary compiled by hand isn't in the manifest, so the game takes it only where its source isn't there) import argparse import os @@ -115,6 +115,11 @@ def main(): if result.returncode != 0: failed.append('%s/%s' % (binarydir, binary)) sys.stderr.write(result.stderr) + # the binary of an earlier run would stay beside a source it no longer matches + stale = os.path.join(binaries, binary) + if os.path.isfile(stale): + os.remove(stale) # NOSONAR: a developer tool removing its own output beside the shaders it is given + print('removed the stale %s/%s' % (binarydir, binary), file=sys.stderr) continue if result.stderr.strip(): sys.stderr.write(result.stderr) diff --git a/shaders/ogl46/gtao_main.comp b/shaders/ogl46/gtao_main.comp index bae03d6dc..152bb48d7 100644 --- a/shaders/ogl46/gtao_main.comp +++ b/shaders/ogl46/gtao_main.comp @@ -31,7 +31,7 @@ const float FALLOFF_RANGE = 0.615; float half_depth(ivec2 texel) { ivec2 full_size = textureSize(depth_tex, 0); - return texelFetch(depth_tex, min(texel * 2, full_size - 1), 0).r; + return texelFetch(depth_tex, clamp(texel * 2, ivec2(0), full_size - 1), 0).r; } vec3 view_position(ivec2 texel, float depth) @@ -42,6 +42,27 @@ vec3 view_position(ivec2 texel, float depth) return position.xyz / position.w; } +// the step to the neighbour on one axis which is closer in depth. a neighbour outside the target or in the sky has no +// position and is left out; with neither left, zero +vec3 neighbour_delta(ivec2 texel, ivec2 offset, vec3 position, ivec2 size) +{ + ivec2 before = texel - offset; + ivec2 after = texel + offset; + float depthbefore = all(greaterThanEqual(before, ivec2(0))) ? half_depth(before) : 0.0; + float depthafter = all(lessThan(after, size)) ? half_depth(after) : 0.0; + bool hasbefore = depthbefore > 0.0; + bool hasafter = depthafter > 0.0; + if (!hasbefore && !hasafter) + return vec3(0.0); + if (!hasbefore) + return view_position(after, depthafter) - position; + if (!hasafter) + return position - view_position(before, depthbefore); + vec3 deltabefore = position - view_position(before, depthbefore); + vec3 deltaafter = view_position(after, depthafter) - position; + return (abs(deltaafter.z) < abs(deltabefore.z)) ? deltaafter : deltabefore; +} + // 4x4 ordered pattern, values 0..15 const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0); @@ -61,14 +82,12 @@ void main() vec3 position = view_position(texel, depth); vec3 view = normalize(-position); - // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it - vec3 left = view_position(texel - ivec2(1, 0), half_depth(texel - ivec2(1, 0))); - vec3 right = view_position(texel + ivec2(1, 0), half_depth(texel + ivec2(1, 0))); - vec3 down = view_position(texel - ivec2(0, 1), half_depth(texel - ivec2(0, 1))); - vec3 up = view_position(texel + ivec2(0, 1), half_depth(texel + ivec2(0, 1))); - vec3 dx = (abs(right.z - position.z) < abs(position.z - left.z)) ? right - position : position - left; - vec3 dy = (abs(up.z - position.z) < abs(position.z - down.z)) ? up - position : position - down; - vec3 normal = normalize(cross(dx, dy)); + // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it. with no + // neighbour on an axis (a thin wire against the sky, the edge of the image) the surface faces the camera + vec3 dx = neighbour_delta(texel, ivec2(1, 0), position, size); + vec3 dy = neighbour_delta(texel, ivec2(0, 1), position, size); + vec3 normal = cross(dx, dy); + normal = (dot(normal, normal) > 1e-24) ? normalize(normal) : view; if (dot(normal, view) < 0.0) normal = -normal; diff --git a/shaders/ogl46/tonemapping.glsl b/shaders/ogl46/tonemapping.glsl index 4dd648457..ae08bada8 100644 --- a/shaders/ogl46/tonemapping.glsl +++ b/shaders/ogl46/tonemapping.glsl @@ -162,7 +162,8 @@ vec4 tonemap(vec4 x) // Last-line-of-defense sanitize so NaN/Inf/negative HDR values do not // escape into log2()/pow() and produce black flashes or invalid output. vec3 hdr = x.rgb; - hdr = mix(hdr, vec3(0.0), vec3(any(isnan(hdr)) || any(isinf(hdr)))); + // the bvec3 overload selects instead of blending, so a NaN does not get through 0 * NaN + hdr = mix(hdr, vec3(0.0), bvec3(any(isnan(hdr)) || any(isinf(hdr)))); hdr = max(hdr, vec3(0.0)); return FBOUT(vec4(ApplyAgX(hdr), x.a)); //return FBOUT(vec4(ACESFilm(hdr), x.a)); diff --git a/shaders/vk14/gtao_main.comp b/shaders/vk14/gtao_main.comp index 14f74ef41..f50205223 100644 --- a/shaders/vk14/gtao_main.comp +++ b/shaders/vk14/gtao_main.comp @@ -37,7 +37,7 @@ const float FALLOFF_RANGE = 0.615; float half_depth(ivec2 texel) { ivec2 full_size = textureSize(depth_tex, 0); - return texelFetch(depth_tex, min(texel * 2, full_size - 1), 0).r; + return texelFetch(depth_tex, clamp(texel * 2, ivec2(0), full_size - 1), 0).r; } vec3 view_position(ivec2 texel, float depth) @@ -48,6 +48,27 @@ vec3 view_position(ivec2 texel, float depth) return position.xyz / position.w; } +// the step to the neighbour on one axis which is closer in depth. a neighbour outside the target or in the sky has no +// position and is left out; with neither left, zero +vec3 neighbour_delta(ivec2 texel, ivec2 offset, vec3 position, ivec2 size) +{ + ivec2 before = texel - offset; + ivec2 after = texel + offset; + float depthbefore = all(greaterThanEqual(before, ivec2(0))) ? half_depth(before) : 0.0; + float depthafter = all(lessThan(after, size)) ? half_depth(after) : 0.0; + bool hasbefore = depthbefore > 0.0; + bool hasafter = depthafter > 0.0; + if (!hasbefore && !hasafter) + return vec3(0.0); + if (!hasbefore) + return view_position(after, depthafter) - position; + if (!hasafter) + return position - view_position(before, depthbefore); + vec3 deltabefore = position - view_position(before, depthbefore); + vec3 deltaafter = view_position(after, depthafter) - position; + return (abs(deltaafter.z) < abs(deltabefore.z)) ? deltaafter : deltabefore; +} + // 4x4 ordered pattern, values 0..15 const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0); @@ -67,14 +88,12 @@ void main() vec3 position = view_position(texel, depth); vec3 view = normalize(-position); - // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it - vec3 left = view_position(texel - ivec2(1, 0), half_depth(texel - ivec2(1, 0))); - vec3 right = view_position(texel + ivec2(1, 0), half_depth(texel + ivec2(1, 0))); - vec3 down = view_position(texel - ivec2(0, 1), half_depth(texel - ivec2(0, 1))); - vec3 up = view_position(texel + ivec2(0, 1), half_depth(texel + ivec2(0, 1))); - vec3 dx = (abs(right.z - position.z) < abs(position.z - left.z)) ? right - position : position - left; - vec3 dy = (abs(up.z - position.z) < abs(position.z - down.z)) ? up - position : position - down; - vec3 normal = normalize(cross(dx, dy)); + // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it. with no + // neighbour on an axis (a thin wire against the sky, the edge of the image) the surface faces the camera + vec3 dx = neighbour_delta(texel, ivec2(1, 0), position, size); + vec3 dy = neighbour_delta(texel, ivec2(0, 1), position, size); + vec3 normal = cross(dx, dy); + normal = (dot(normal, normal) > 1e-24) ? normalize(normal) : view; if (dot(normal, view) < 0.0) normal = -normal; diff --git a/shaders/vk14/tonemapping.glsl b/shaders/vk14/tonemapping.glsl index cee58e5df..bb9e15f21 100644 --- a/shaders/vk14/tonemapping.glsl +++ b/shaders/vk14/tonemapping.glsl @@ -162,7 +162,8 @@ vec4 tonemap(vec4 x) // Last-line-of-defense sanitize so NaN/Inf/negative HDR values do not // escape into log2()/pow() and produce black flashes or invalid output. vec3 hdr = x.rgb; - hdr = mix(hdr, vec3(0.0), vec3(any(isnan(hdr)) || any(isinf(hdr)))); + // the bvec3 overload selects instead of blending, so a NaN does not get through 0 * NaN + hdr = mix(hdr, vec3(0.0), bvec3(any(isnan(hdr)) || any(isinf(hdr)))); hdr = max(hdr, vec3(0.0)); return FBOUT(vec4(ApplyAgX(hdr), x.a)); //return FBOUT(vec4(ACESFilm(hdr), x.a)); diff --git a/starter/eu07_starter.cpp b/starter/eu07_starter.cpp index c756b51ac..b52c167b3 100644 --- a/starter/eu07_starter.cpp +++ b/starter/eu07_starter.cpp @@ -69,18 +69,42 @@ bool file_exists(std::wstring const &Path) return (attributes != INVALID_FILE_ATTRIBUTES) && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0); } +// a path a function of the system writes to the buffer it's given (Get(buffer, size) returns the length written, or the size needed when +// the buffer is too small, or the size itself when it cut the path short), in a buffer grown until the path fits: a path longer than +// MAX_PATH (a folder with long paths enabled) isn't cut off nor taken for none. empty when there's none +template +std::wstring sized_path(Fill const &Get) +{ + std::wstring buffer(MAX_PATH, L'\0'); + while (true) + { + auto const length{static_cast(Get(buffer.data(), static_cast(buffer.size())))}; + if (length == 0) + { + return {}; + } + if (length < buffer.size()) + { + buffer.resize(length); + return buffer; + } + if (buffer.size() >= 32768) + { + // the longest path windows has + return {}; + } + buffer.resize(std::max(length + 1, buffer.size() * 2)); + } +} + std::wstring system_directory() { - wchar_t path[MAX_PATH]; - auto const length{::GetSystemDirectoryW(path, MAX_PATH)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(path, length) : std::wstring(); + return sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetSystemDirectoryW(Buffer, Size); }); } std::wstring windows_directory() { - wchar_t path[MAX_PATH]; - auto const length{::GetWindowsDirectoryW(path, MAX_PATH)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(path, length) : std::wstring(); + return sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetWindowsDirectoryW(Buffer, Size); }); } int show(std::wstring const &Text, UINT const Type) @@ -205,9 +229,7 @@ std::wstring locate(library_check const &Check, std::wstring const &Name, bool & return path; } } - wchar_t found[MAX_PATH]; - auto const length{::SearchPathW(nullptr, Name.c_str(), nullptr, MAX_PATH, found, nullptr)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(found, length) : std::wstring(); + return sized_path([&Name](wchar_t *Buffer, DWORD const Size) { return ::SearchPathW(nullptr, Name.c_str(), nullptr, Size, Buffer, nullptr); }); } // the libraries of the image and of the libraries next to the simulator, which the installation brings. the system ones are taken as they are @@ -347,16 +369,22 @@ bool check_system(std::wstring const &Simulator, std::wstring const &Directory) { runtime = runtime || is_runtime_library(lowercase(library)); } - std::wstring const text{L"The simulator can't start, these libraries are missing:" + join(check.missing)}; + // the check reads the imports itself and looks for them as the loader does, which it may not match in every case: the player can + // start the simulator anyway, and the loader has the last word + std::wstring const text{L"The simulator may not start, these libraries are missing:" + join(check.missing)}; if (runtime) { - offer_redistributable(text + L"\n\nThey belong to the Microsoft Visual C++ Redistributable.", false); + if (offer_redistributable(text + L"\n\nThey belong to the Microsoft Visual C++ Redistributable.", true)) + { + return false; + } } - else + else if (show(text + L"\n\nThe installation is incomplete: on Steam, verify the integrity of the game files, otherwise install the simulator again." + L"\n\nStart the simulator anyway?", + MB_YESNO | MB_ICONERROR | MB_DEFBUTTON2) != IDYES) { - show(text + L"\n\nThe installation is incomplete: on Steam, verify the integrity of the game files, otherwise install the simulator again.", MB_OK | MB_ICONERROR); + return false; } - return false; } #if defined(_MSC_VER) && (_MSC_VER >= 1940) @@ -443,13 +471,11 @@ wchar_t const *arguments() int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { - wchar_t path[MAX_PATH * 2]; - auto const length{::GetModuleFileNameW(nullptr, path, MAX_PATH * 2)}; - if ((length == 0) || (length >= MAX_PATH * 2)) + auto directory{sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetModuleFileNameW(nullptr, Buffer, Size); })}; + if (directory.empty()) { return 1; } - std::wstring directory(path, length); directory.erase(directory.find_last_of(L"\\/")); auto const simulator{directory + L"\\" + widen(EU07_SIMULATOR_EXE)}; diff --git a/tools/fetch_dlss_sdk.cmake b/tools/fetch_dlss_sdk.cmake index c0fca521a..b0fcdee1a 100644 --- a/tools/fetch_dlss_sdk.cmake +++ b/tools/fetch_dlss_sdk.cmake @@ -16,6 +16,8 @@ endif() get_filename_component(DLSS_SDK_ROOT "${DLSS_SDK_ROOT}" ABSOLUTE) if(NOT DLSS_SDK_TAG) set(DLSS_SDK_TAG "v310.9.16") + # the commit the tag is expected at: a tag can be moved, a commit can't. another tag given by hand is taken as it is + set(DLSS_SDK_COMMIT "9981c6350dc58c0ce21f024fd65e31e851c31689") endif() if(NOT DLSS_SDK_PLATFORMS) if(CMAKE_HOST_WIN32) @@ -83,4 +85,10 @@ else() run_git(-C "${DLSS_SDK_ROOT}" sparse-checkout set --no-cone ${patterns}) run_git(-C "${DLSS_SDK_ROOT}" checkout) endif() +if(DLSS_SDK_COMMIT) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${DLSS_SDK_ROOT}" rev-parse HEAD OUTPUT_VARIABLE checkedout OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE result) + if(NOT result EQUAL 0 OR NOT checkedout STREQUAL DLSS_SDK_COMMIT) + message(FATAL_ERROR "the DLSS SDK tag ${DLSS_SDK_TAG} is at the commit ${checkedout}, not at ${DLSS_SDK_COMMIT} as expected: check the release before building with it") + endif() +endif() message(STATUS "the DLSS SDK is in ${DLSS_SDK_ROOT}; configure with -DWITH_DLSS=ON") diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 97b6b33b1..a5ac87be6 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -418,7 +418,8 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to else if (GfxRenderer == "vulkan14") GfxRenderer = "vulkan"; - if ((GfxRenderer != "default") && (GfxRenderer != "vulkan")) + // "null" draws nothing and loads no textures, for the test runs + if ((GfxRenderer != "default") && (GfxRenderer != "vulkan") && (GfxRenderer != "null")) { // the legacy OpenGL 2.1 renderer ("legacy", "simple" and other values) and the NVRHI renderer ("experimental") were removed WriteLog("eu07.ini: gfxrenderer \"" + GfxRenderer + "\" is no longer supported, using \"default\""); diff --git a/utilities/Globals.h b/utilities/Globals.h index f9ecb9fbb..e5887be33 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -147,9 +147,9 @@ struct global_settings { std::string Weather{ "cloudy:" }; // current weather std::string Period{}; // time of the day, based on sun position bool FullPhysics{ true }; // full calculations performed for each simulation step - bool physics_sleepheld{ true }; // vehicles standing still and held by their brakes let their physics sleep, see TMoverParameters::accelerating() - bool physics_roadlod{ true }; // road vehicles far from the camera go by one step of the physics in a frame, see vehicle_table::update() - float physics_pipewake{ 0.001f }; // bar: air flowing along a pipe wakes the physics of a vehicle when it changes its pressure by more than this. 0: any flow does + bool physics_sleepheld{ false }; // vehicles standing still and held by their brakes let their physics sleep, see TMoverParameters::accelerating() + bool physics_roadlod{ false }; // road vehicles far from the camera go by one step of the physics in a frame, see vehicle_table::update() + float physics_pipewake{ 0.f }; // bar: air flowing along a pipe wakes the physics of a vehicle when it changes its pressure by more than this. 0: any flow does bool performance_multithreading{ true }; // work split over the logical cores of the machine (worker_pool), as many as each job is worth bool debug_memorystats{ false }; // the memory of the parts of the program in the debug panel, with new and delete counted (start_heap_counting()). slows the loading down bool bnewAirCouplers{ true }; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index cb5e5777a..1adb80a5b 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -193,6 +193,11 @@ void set_thread_random_engine(std::mt19937 *Engine) // NOSONAR: randomness of th t_random_engine = Engine; } +std::mt19937 *thread_random_engine() // NOSONAR: randomness of the simulation, not of anything security-relevant +{ + return t_random_engine; +} + double Random(double min, double max) { if (max < min) { std::swap(min, max); } // std::uniform_real_distribution requires min <= max (inverted bounds are UB) diff --git a/utilities/utilities.h b/utilities/utilities.h index 8acec8aca..588aff742 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -84,6 +84,8 @@ int RandomInt(int min, int max); // the engine Random() draws from in the calling thread, in place of Global.random_engine, or none for that one again. the threads // of worker_pool have engines of their own: the one of the simulation can't be shared between threads void set_thread_random_engine(std::mt19937 *Engine); // NOSONAR: randomness of the simulation, not of anything security-relevant +// the engine set for the calling thread by set_thread_random_engine(), or none +std::mt19937 *thread_random_engine(); // NOSONAR: randomness of the simulation, not of anything security-relevant /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 77816f265..7eb6f19a9 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -9720,15 +9721,23 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { kinds.resize( m_items.size() ); // road vehicles far from the camera with nobody inside go by one step of the physics in the frame, as long as all the steps // together (Global.physics_roadlod): their movement goes on, in coarser steps nobody is close enough to tell + // not in a network session: which vehicles go coarse depends on the camera of each machine, so their movement and the draws of + // Random() they make would part ways between the machines. nor with physics.fullphysics off, whose steps are long already: one + // step for all of them would be the time of the whole frame, with the collisions looked at once in it static std::vector coarse; coarse.assign( m_items.size(), 0 ); + auto const roadlod { + Global.physics_roadlod + && Global.FullPhysics + && Global.network_servers.empty() + && ( false == Global.network_client.has_value() ) }; auto const camera { Global.pCamera.Pos }; for( std::size_t index = 0; index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; auto const road { ( vehicle->MoverParameters->CategoryFlag & 2 ) != 0 }; auto const distant { glm::length2( vehicle->GetPosition() - camera ) > Timer::subsystem.VEHICLE_NEAR * Timer::subsystem.VEHICLE_NEAR }; kinds[ index ] = static_cast( ( road ? 2 : 0 ) + ( distant ? 1 : 0 ) ); - coarse[ index ] = static_cast( Global.physics_roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); + coarse[ index ] = static_cast( roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); if( false == vehicle->bEnabled ) { continue; } ++counts.kind[ kinds[ index ] ]; auto const *mover { vehicle->MoverParameters }; @@ -10191,8 +10200,15 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio auto const totaltime { Deltatime * Iterationcount }; auto const coarse = [ & ]( std::uint32_t const Index ) { return ( Index < Coarse.size() ) && ( Coarse[ Index ] != 0 ); }; + // the draws of Random() a group makes come from an engine of its own, seeded from the run's engine and the group: the same in + // every run of a seed, whichever thread takes the group (the engines of the threads are seeded at random) + auto const seed { static_cast( Global.random_engine() ) }; auto const steps = [ & ]( std::uint32_t const Group ) { auto const &members { m_groups[ Group ] }; + std::seed_seq groupseed { seed, members.front() }; + std::mt19937 engine { groupseed }; // NOSONAR: randomness of the simulation, not of anything security-relevant + auto *const threadengine { thread_random_engine() }; + set_thread_random_engine( &engine ); // the hoses join only vehicles coupled with each other, which are in one group: the air they carry is exchanged // within the group after each step, as update_brake_pipes() does for all the vehicles in one thread std::vector pipes; @@ -10218,7 +10234,8 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio for( auto const index : members ) { // the vehicles going by one step take it with the time of all of them m_items[ index ]->UpdateForce( coarse( index ) ? totaltime : Deltatime ); - } }; + } + set_thread_random_engine( threadengine ); }; Workers().run( m_threadgroups.size(), Threads, diff --git a/world/RailCarve.cpp b/world/RailCarve.cpp index dadacdd45..da72a5569 100644 --- a/world/RailCarve.cpp +++ b/world/RailCarve.cpp @@ -287,9 +287,15 @@ bool continues( carve_rail const &A, carve_rail const &B ) { if( A.track == B.track ) { return false; } + // the knuckle and the point of an obtuse crossing, whose ends lie within the reach at a slip centre, go on from each other only + // nearly straight (less than 2.6 degrees apart; 1:9 is 6.4); the rails at any other joint also where it's kinked by up to 8 degrees, + // as tracks laid by hand often are, so their heads aren't planed there + auto const obtuse = []( carve_rail const &Rail ) { + return std::ranges::any_of( Rail.parts, []( carve_part const &Part ) { return Part.obtuse[ 0 ] || Part.obtuse[ 1 ]; } ); }; + auto const straight { ( obtuse( A ) || obtuse( B ) ) ? 0.999 : 0.99 }; for( int a = 0; a < 2; ++a ) { for( int b = 0; b < 2; ++b ) { - if( glm::length( plan( A.ends[ a ] - B.ends[ b ] ) ) < 0.05 && std::abs( glm::dot( A.directions[ a ], B.directions[ b ] ) ) > 0.999 ) { + if( glm::length( plan( A.ends[ a ] - B.ends[ b ] ) ) < 0.05 && std::abs( glm::dot( A.directions[ a ], B.directions[ b ] ) ) > straight ) { return true; } } diff --git a/world/TrackBlend.h b/world/TrackBlend.h index b3e2c7c63..a239ced39 100644 --- a/world/TrackBlend.h +++ b/world/TrackBlend.h @@ -25,8 +25,9 @@ class TTrack; // ballast, a switch the trackbed made for it namespace track_blend { -// how far from an end the textures blend, by default -float constexpr default_length { 3.f }; +// how far from an end the textures blend where the scenery doesn't say (blendrails, blendballast, blend): not at all, so a +// scenery from before looks as it did. a joint blends where the tracks on both sides of it ask for it +float constexpr default_length { 0.f }; // the order of the lengths of TTrack::m_blend enum class kind { diff --git a/world/TrackSleepers.cpp b/world/TrackSleepers.cpp index a24bd443b..4dc3d9fe6 100644 --- a/world/TrackSleepers.cpp +++ b/world/TrackSleepers.cpp @@ -79,7 +79,13 @@ double blade_rise( TTrack const &Track ) { double wing_rise( TTrack const &Track ) { - return ( lays( Track ) ? timber_model( Track )->slide : 0.0 ); + if( false == lays( Track ) ) { + return 0.0; + } + // the chairs the blades slide on are those of the model the timbers are laid of: once they're laid, that of the panel the track + // shares them with (lay()), which can be another one than its own or the one of eu07.ini + auto const *model { Track.m_sleepers3d.timbers }; + return ( model != nullptr ? model : timber_model( Track ) )->slide; } glm::dvec2 stock_stretch( TTrack const &Track, int const Path, int const Side ) { @@ -333,6 +339,8 @@ void instance( TTrack &Track, std::vector &&Beams, bool const Fastened ) { void lay( TTrack &Track, bool const Fastened ) { auto &laid { Track.m_sleepers3d }; + // what the rails of the track were made with + auto const rise { wing_rise( Track ) }; std::vector placed; if( laid.active && in_background() && timber_model( Track ) != nullptr ) { // worked out in the background; till then the track keeps what it has, and tries again @@ -362,6 +370,14 @@ void lay( TTrack &Track, bool const Fastened ) { // the layout of the cluster isn't needed by this track any more, the instances below are what's drawn forget_layout( Track ); instance( Track, std::move( beams ), Fastened ); + // the rails were made with the blades and the wing rails raised for the chairs of the model the track had then: where the model + // of the panel raises them otherwise, they're made again, with it. Made again, they keep that model, so this happens once + if( std::abs( wing_rise( Track ) - rise ) > 1e-4 ) { + auto §ion { simulation::Region->section( Track.location() ) }; + if( section.m_geometrycreated ) { + Track.rebuild_geometry( section.m_geometrybank ); + } + } } void fasten( TTrack &Track ) { diff --git a/world/Traction.cpp b/world/Traction.cpp index 5aa25e1a5..d85a9599c 100644 --- a/world/Traction.cpp +++ b/world/Traction.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/Traction.h" #include "world/catenary_span.h" +#include "world/TractionTail.h" #include "simulation/simulation.h" #include "utilities/Globals.h" @@ -138,41 +139,18 @@ TTraction::Load( cParser *parser, glm::dvec3 const &pOrigin ) { >> WireOffset; m_visible = parser->getToken() == "vis"; - std::string token { parser->getToken() }; - std::string catenarytype; - double catenarytension[ 2 ] { 0.0, 0.0 }; - glm::dvec3 catenaryrope2[ 2 ]; - bool catenaryrope2set[ 2 ] { false, false }; - while( false == token.empty() - && token != "endtraction" ) { - - if( token == "parallel" ) { - // jawne wskazanie innego przęsła, na które może przestawić się pantograf - parser->getTokens(); - *parser >> asParallel; - } - else if( token == "type" ) { - // symbol typu sieci, np. YwsC120-2C; starsze wersje symulatora pomijają ten dopisek - catenarytype = parser->getToken( false ); - } - else if( token == "rope2" ) { - // koniec drugiej liny nośnej przy kotwieniu: "rope2 start|end x y z" - auto const which { parser->getToken() }; - auto const point { LoadPoint( *parser ) + pOrigin }; - auto const end { which == "end" ? 1 : 0 }; - catenaryrope2[ end ] = point; - catenaryrope2set[ end ] = true; - } - else if( token == "tension" ) { - // naciąg liny nośnej i przewodów jezdnych w daN inny niż w typie sieci (brakujące ciężary w kotwieniu) - parser->getTokens( 2 ); - *parser >> catenarytension[ 0 ] >> catenarytension[ 1 ]; - } - token = parser->getToken(); - } + // dopiski: "parallel" (jawne wskazanie innego przęsła, na które może przestawić się pantograf), "type" (symbol typu sieci, + // np. YwsC120-2C; starsze wersje symulatora pomijają ten dopisek), "rope2" (koniec drugiej liny nośnej przy kotwieniu), + // "tension" (naciąg liny nośnej i przewodów jezdnych w daN inny niż w typie sieci, brakujące ciężary w kotwieniu) + traction_tail tail; + tail.parallel = asParallel; + read_traction_tail( *parser, pOrigin, tail ); + asParallel = tail.parallel; + // zapamiętane, żeby zapis z edytora ich nie zgubił + m_tail = tail; Init(); // przeliczenie parametrów - catenary_span_assign( *this, catenarytype, catenarytension[ 0 ], catenarytension[ 1 ], catenaryrope2, catenaryrope2set ); + catenary_span_assign( *this, tail.type, tail.tension[ 0 ], tail.tension[ 1 ], tail.rope2.data(), tail.rope2set.data() ); // calculate traction location location( glm::mix( pPoint2, pPoint1, 0.5 ) ); @@ -705,13 +683,11 @@ TTraction::export_as_text_( std::ostream &Output ) const { // visibility // NOTE: 'invis' would be less wrong than 'unvis', but potentially incompatible with old 3rd party tools Output << ( m_visible ? "vis" : "unvis" ) << ' '; - // optional attributes - if( false == asParallel.empty() ) { - Output << "parallel " << asParallel << ' '; - } - if( auto const catenarytype { catenary_span_symbol( *this ) }; false == catenarytype.empty() ) { - Output << "type " << catenarytype << ' '; - } + // optional attributes, all that Load() reads + auto tail { m_tail }; + tail.parallel = asParallel; + tail.type = catenary_span_symbol( *this ); + write_traction_tail( Output, tail ); // footer Output << "endtraction" diff --git a/world/Traction.h b/world/Traction.h index d1a16f497..32ab3d5c5 100644 --- a/world/Traction.h +++ b/world/Traction.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Segment.h" #include "model/material.h" #include "utilities/Names.h" +#include "world/TractionTail.h" class TTractionPowerSource; namespace gfx @@ -62,6 +63,8 @@ class TTraction : public scene::basic_node gfx::geometry_handle m_geometry; // stan przęsła rysowanego wg typu sieci (dopisek "type"); pusty = przęsło rysowane po staremu. szczegóły w world/catenary_span.h std::shared_ptr m_catenaryspan; + // dopiski wpisu "tension" i "rope2" w postaci wczytanej, zapisywane z powrotem przez export_as_text_ + traction_tail m_tail; explicit TTraction( scene::node_data const &Nodedata ); diff --git a/world/catenary_catalog.cpp b/world/catenary_catalog.cpp index 51bf7cc5b..38912747a 100644 --- a/world/catenary_catalog.cpp +++ b/world/catenary_catalog.cpp @@ -84,6 +84,8 @@ void structure_catalog::parse( std::vector const &Lines, std::strin std::istringstream stream { head }; std::vector words; for( std::string word; stream >> word; ) { words.push_back( word ); } + // a line of white space other than spaces and tabs (\v, \f, \r) is as empty + if( words.empty() ) { continue; } auto const &keyword { words.front() }; if( keyword == "text" ) { auto const body { trimmed( line.substr( 4 ) ) }; diff --git a/world/catenary_scene.cpp b/world/catenary_scene.cpp index 5c943a69a..37b888096 100644 --- a/world/catenary_scene.cpp +++ b/world/catenary_scene.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include #include #include #include @@ -2302,50 +2303,96 @@ catenary_scene_file_layer( std::string const &File, std::size_t const Layer ) { FileLayers[ File ] = Layer; } +namespace { + +// treść pliku sieci w postaci zapisywanej na dysk: nagłówek, tekstura, wpisy w kolejności listy; usunięte pomijane. CRLF jak +// w pozostałych plikach scenerii. Count: liczba podwieszeń +std::string +file_text( scene_file const &File, std::size_t &Count ) { + std::string text; + std::istringstream header { File.header }; + for( std::string line; std::getline( header, line ); ) { text += line + "\r\n"; } + if( false == File.skin.empty() ) { text += "skin " + File.skin + "\r\n"; } + Count = 0; + for( auto const &suspension : Suspensions ) { + if( suspension.removed || suspension.file != File.name ) { continue; } + text += catenary::write_suspension( suspension.data ) + "\r\n"; + ++Count; + } + for( auto const &chain : Chains ) { + if( chain.removed || chain.file != File.name ) { continue; } + text += catenary::write_chain( chain.data ) + "\r\n"; + } + for( auto const &gantry : Gantries ) { + if( gantry.removed || gantry.file != File.name ) { continue; } + text += catenary::write_gantry( gantry.data ) + "\r\n"; + } + for( auto const &anchor : Anchors ) { + if( anchor.removed || anchor.file != File.name ) { continue; } + text += catenary::write_anchor( anchor.data ) + "\r\n"; + } + return text; +} + +// plik zapisany obok docelowego, pod nazwą tymczasową; false, gdy się nie udało (wtedy go nie ma) +bool +write_aside( std::string const &Path, std::string const &Text ) { + { + std::ofstream output { Path, std::ios::binary | std::ios::trunc }; + if( false == output.is_open() ) { return false; } + output << Text; + output.close(); + if( false == output.fail() ) { return true; } + } + std::error_code error; + std::filesystem::remove( Path, error ); + return false; +} + +} // namespace + bool catenary_scene_save( std::string &Message ) { - std::vector written; + // najpierw wszystkie pliki pod nazwami tymczasowymi, dopiero gdy wszystkie się zapisały, w miejsce dotychczasowych: + // nieudany zapis nie zostawia na dysku części plików sieci nowych, a części starych + struct pending { + scene_file *file; + std::string path; + std::size_t count; + }; + std::vector aside; + auto const drop_aside = [ &aside ]() { + std::error_code error; + for( auto const &item : aside ) { std::filesystem::remove( item.path + ".tmp", error ); } + }; for( auto &file : Files ) { // wpisy w pliku scenerii zapisuje zapis scenerii if( false == file.changed || InlineFiles.count( file.name ) != 0 ) { continue; } - // wpisy w kolejności listy; usunięte pomijane. CRLF jak w pozostałych plikach scenerii - std::string text; - std::istringstream header { file.header }; - for( std::string line; std::getline( header, line ); ) { text += line + "\r\n"; } - if( false == file.skin.empty() ) { text += "skin " + file.skin + "\r\n"; } std::size_t count { 0 }; - for( auto const &suspension : Suspensions ) { - if( suspension.removed || suspension.file != file.name ) { continue; } - text += catenary::write_suspension( suspension.data ) + "\r\n"; - ++count; - } - for( auto const &chain : Chains ) { - if( chain.removed || chain.file != file.name ) { continue; } - text += catenary::write_chain( chain.data ) + "\r\n"; - } - for( auto const &gantry : Gantries ) { - if( gantry.removed || gantry.file != file.name ) { continue; } - text += catenary::write_gantry( gantry.data ) + "\r\n"; - } - for( auto const &anchor : Anchors ) { - if( anchor.removed || anchor.file != file.name ) { continue; } - text += catenary::write_anchor( anchor.data ) + "\r\n"; - } + auto const text { file_text( file, count ) }; auto const path { Global.asCurrentSceneryPath + file.name }; - std::ofstream output { path, std::ios::binary | std::ios::trunc }; - if( false == output.is_open() ) { + if( false == write_aside( path + ".tmp", text ) ) { + drop_aside(); Message = "catenary file \"" + file.name + "\" can't be written"; return false; } - output << text; - output.close(); - if( output.fail() ) { - Message = "catenary file \"" + file.name + "\" wasn't written completely"; + aside.emplace_back( &file, path, count ); + } + std::vector written; + for( std::size_t index = 0; index < aside.size(); ++index ) { + auto const &item { aside[ index ] }; + std::error_code error; + std::filesystem::rename( item.path + ".tmp", item.path, error ); + if( error ) { + // te przed nim są już na miejscu (i zapisane), ten i dalsze zostają zmienione do następnego zapisu + Message = "catenary file \"" + item.file->name + "\" can't be written"; + aside.erase( aside.begin(), aside.begin() + static_cast( index ) ); + drop_aside(); return false; } - file.changed = false; - written.push_back( file.name + " (" + std::to_string( count ) + ")" ); + item.file->changed = false; + written.push_back( item.file->name + " (" + std::to_string( item.count ) + ")" ); } Message.clear(); for( auto const &name : written ) { Message += ( Message.empty() ? "" : ", " ) + name; } diff --git a/world/catenary_span.cpp b/world/catenary_span.cpp index d0a686c33..00b62f73d 100644 --- a/world/catenary_span.cpp +++ b/world/catenary_span.cpp @@ -32,6 +32,7 @@ struct catenary_span { std::vector hangergaps; // odstępy wieszaków dobrane do rozpiętości; puste = odcinek bez wieszaków gfx::geometrybank_handle solidbank; // osobny bank na bryły tego przęsła catenary_solid solid; // bryły do oglądania z bliska + catenary_solid chunks; // fragmenty banku zrobione dla brył, używane ponownie bool solidloaded { false }; std::vector attached; // bryła dołączona (lina kotwienia), układ scenerii std::shared_ptr own; // kopia typu z naciągiem z dopisku "tension" @@ -210,6 +211,25 @@ release( gfx::geometry_handle const &Geometry ) { GfxRenderer->Replace( empty, userdata, Geometry, GL_TRIANGLES ); } +// bryła w fragmencie banku przęsła: fragment zrobiony wcześniej dostaje ją w miejsce dawnej zawartości, nowy powstaje tylko +// za pierwszym razem. Pusta bryła zostawia fragment pusty; zwraca uchwyt do rysowania, pusty, gdy nie ma czego rysować +gfx::geometry_handle +fill_chunk( TTraction &Traction, gfx::geometry_handle &Chunk, std::vector const &Solid ) { + if( Solid.empty() ) { + release( Chunk ); + return {}; + } + auto data { vertices( Traction, Solid ) }; + gfx::userdata_array userdata; + if( Chunk == null_handle ) { + Chunk = GfxRenderer->Insert( data, userdata, Traction.m_catenaryspan->solidbank, GL_TRIANGLES ); + } + else { + GfxRenderer->Replace( data, userdata, Chunk, GL_TRIANGLES ); + } + return Chunk; +} + // wygląd metalu: [ metal: miedź, aluminium ][ przewód, osprzęt ][ stan: nowa, przejściowa, zaśniedziała ] // osprzęt sieci miedzianej jest z brązu albo mosiądzu catenary_metal Metals[ 2 ][ 2 ][ 3 ] { @@ -370,20 +390,11 @@ catenary_span_solid( TTraction &Traction, glm::dvec3 const &Camera ) { if( span.solidbank == null_handle ) { span.solidbank = GfxRenderer->Create_Bank(); } - // każde ponowne wczytanie tworzy nowe fragmenty w banku tego przęsła; poprzednie zostały opróżnione przy zwalnianiu - gfx::userdata_array userdata; - { - auto data { vertices( Traction, wires ) }; - span.solid.wires = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } - if( false == fittings.empty() ) { - auto data { vertices( Traction, fittings ) }; - span.solid.fittings = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } - if( false == span.attached.empty() ) { - auto data { vertices( Traction, span.attached ) }; - span.solid.rope = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } + // ponowne wczytanie wypełnia fragmenty banku zrobione za pierwszym razem (opróżnione przy zwalnianiu), nowe powstają + // tylko za pierwszym razem; bank nie rośnie przy każdym podejściu kamery + span.solid.wires = fill_chunk( Traction, span.chunks.wires, wires ); + span.solid.fittings = fill_chunk( Traction, span.chunks.fittings, fittings ); + span.solid.rope = fill_chunk( Traction, span.chunks.rope, span.attached ); span.solidloaded = ( span.solid.wires != null_handle ); return ( span.solidloaded ? span.solid : catenary_solid() ); }