diff --git a/CMakeLists.txt b/CMakeLists.txt index 75dbc5df5..294128b87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -556,6 +556,7 @@ set(CORE_SOURCES "scene/sn_utils.cpp" "scene/regionfile.cpp" "utilities/inionlysettings.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" @@ -568,6 +569,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/EU07.cpp b/EU07.cpp index a76564663..fa6bb15f2 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,9 +22,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -78,8 +82,12 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ExceptionPointers = ExceptionInfo; dumpInfo.ClientPointers = FALSE; - // Wybrana kombinacja flag - MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + // a small dump by default: the stacks with the memory they point to, the threads with their process and thread + // blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data + // (Global among them). all the memory of the simulator, as large as the memory it took, only with + // "crashdump.full yes" in eu07.ini + auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs}; + MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); // in test mode nobody is there to close the box, and the run would wait for it until killed @@ -113,7 +121,7 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); - // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + // the last two seconds of the physics logs, which the runner of the tests reads PhysicsLogs.stop(); finish_log(); fflush(stdout); @@ -172,9 +180,15 @@ int main(int argc, char *argv[]) SetUnhandledExceptionFilter(CrashHandler); #endif #endif + // on Linux, where no dump is written, the stack of a crash in the log and on the standard error + crash_signals::install(VERSION_INFO); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); + // a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it + // from a closing; how the simulator ends after a start that worked stays as it was + int exitcode{0}; + // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { @@ -221,34 +235,54 @@ int main(int argc, char *argv[]) } else { + // below 0 when the start failed (see eu07_application::init()) + int initresult{0}; try { - auto result{Application.init(argc, argv)}; - if (result == 0) + initresult = Application.init(argc, argv); + if (initresult == 0) { - result = Application.run(); + Application.run(); Application.exit(); } } + // an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the + // log and ends with an error code catch (std::bad_alloc const &Error) { ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what())); + exitcode = 1; } #ifdef _WIN32 catch (std::runtime_error const &Error) { + ErrorLog("Critical error: " + std::string(Error.what())); std::string msg = "Simulator crash occured :(\n"; msg += Error.what(); MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); + exitcode = 1; + } +#else + // elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on + // Windows it is left to CrashHandler, whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif - // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } #ifndef _WIN32 fflush(stdout); fflush(stderr); #endif - std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults + std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults } diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b4ba8478d..b1735d0c5 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -940,7 +940,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem PantPress = ScndPipePress; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = std::clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else @@ -952,7 +952,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } - PantPress = std::clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s @@ -4719,7 +4719,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not auto const initialstate{CompressorListPos}; - CompressorListPos = std::clamp(State, 0, CompressorListPosNo); + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); if (Notify != range_t::local) { @@ -6579,7 +6579,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; @@ -6955,7 +6955,7 @@ double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, doub if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -9089,7 +9089,9 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr { Progress = 0.0; } - return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); } } // namespace @@ -9203,18 +9205,18 @@ void TMoverParameters::EIMICFromFourPositions(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -9336,7 +9338,7 @@ void TMoverParameters::EIMICLimit() eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) @@ -9443,7 +9445,7 @@ void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -10451,7 +10453,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun } LoadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); ComputeMass(); return true; } @@ -10496,7 +10498,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam { // pusto lub rozładowano żądaną ilość LoadStatus = 4; // skończony rozładunek - LoadAmount = std::clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny } if (LoadAmount == 0.f) { @@ -14370,7 +14372,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); return OK; } @@ -14996,7 +14998,7 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/application/application.cpp b/application/application.cpp index 2a024bfd6..bc4b7dc1d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -54,6 +57,7 @@ http://mozilla.org/MPL/2.0/. #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "version.lib") +#include #endif #ifdef __unix__ @@ -65,6 +69,36 @@ eu07_application Application; screenshot_manager screenshot_man; ui_layer uilayerstaticinitializer; +namespace +{ +#ifdef _WIN32 +// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms. +// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up +// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or +// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the +// main loop, as it costs some power for as long as it's held +bool timer_period_set{false}; +#endif + +// asks for the finer timer once, when fpslimit is set +void begin_timer_period() +{ +#ifdef _WIN32 + if (!timer_period_set && Global.minframetime.count() > 0.f) + timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR); +#endif +} + +void end_timer_period() +{ +#ifdef _WIN32 + if (timer_period_set) + timeEndPeriod(1); + timer_period_set = false; +#endif +} +} // namespace + #ifdef _WIN32 extern "C" { @@ -140,6 +174,28 @@ void char_callback(GLFWwindow *window, unsigned int c) Application.on_char(c); } +namespace +{ + +// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no +// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context, +// is told once. glfw may call this from any thread that uses it +void glfw_error_callback(int const Code, char const *Description) +{ + auto message{std::format("GLFW error 0x{:08X}: {}", static_cast(Code), Description != nullptr ? Description : "(no description)")}; + + static std::mutex reportedmutex; + static std::set reported; + { + std::scoped_lock lock(reportedmutex); + if (false == reported.insert(message).second) + return; + } + ErrorLog(message); +} + +} // namespace + // public: void eu07_application::queue_screenshot() @@ -222,7 +278,8 @@ int eu07_application::run_crashgui() return 0; } } - return -1; + // the player closed the window: the simulator closes with it, as it always has, but that is no failed start + return 1; } #if WITH_DISCORD_RPC void eu07_application::DiscordRPCService() @@ -352,6 +409,8 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; } + // fpslimit is known now + begin_timer_period(); // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is @@ -407,7 +466,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { - ErrorLog("Failed to run crash gui!"); + // above 0 the player closed the window, which is no error + if (result < 0) + ErrorLog("Failed to run crash gui!"); + else + WriteLog("Crash report window closed, closing"); return result; } } @@ -474,6 +537,11 @@ int eu07_application::init(int Argc, char *Argv[]) if (!init_network()) return -1; + // glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the + // platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key + // codes of its launchers), every frame + glfwSetErrorCallback(nullptr); + return result; } @@ -690,6 +758,8 @@ int eu07_application::run() // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { + // fpslimit may come from the config block of the scenery, read after the settings + begin_timer_period(); std::this_thread::sleep_until(*nextframe); } } @@ -751,7 +821,7 @@ void eu07_application::exit() step("the black box"); simulation::Blackbox.close(); step("the physics logs"); - // what is kept of them, the black box's written last, waited for a second at most: the rest is dropped + // what is kept of them, the black box's written last PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) @@ -786,6 +856,7 @@ void eu07_application::exit() if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + end_timer_period(); step("done"); StopLogService(); auto it = Global.threads.find("LogService"); @@ -1359,6 +1430,9 @@ int eu07_application::init_locale() int eu07_application::init_glfw() { + // set before glfwInit(), so a failure of the start itself is told too + glfwSetErrorCallback(glfw_error_callback); + { int glfw_major, glfw_minor, glfw_rev; glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); diff --git a/application/application.h b/application/application.h index 850b66e1e..881d4f073 100644 --- a/application/application.h +++ b/application/application.h @@ -33,6 +33,7 @@ public: // constructors eu07_application() = default; // methods + // 0 when the simulator started, below 0 when its start failed, above 0 when the player closed it before it started int init( int Argc, char *Argv[] ); int diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 47ab3ae0c..b47a1d4df 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" + +#include + /* namespace input { @@ -627,6 +630,12 @@ bool driver_mode::is_command_processor() const return true; } +double driver_mode::shake_fraction() const +{ + // how far the simulation time has got from the last step of the shake towards the next one + return std::clamp(m_secondaryupdateaccumulator / m_secondaryupdaterate, 0.0, 1.0); +} + void driver_mode::update_camera(double const Deltatime) { @@ -775,7 +784,8 @@ void driver_mode::update_camera(double const Deltatime) // ale bez odbicia Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 } - auto const shakeangles{simulation::Train->Dynamic()->shake_angles()}; + auto const *dynamic{simulation::Train->Dynamic()}; + auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* @@ -796,8 +806,9 @@ void driver_mode::update_camera(double const Deltatime) } float const shakescale{FreeFlyModeFlag ? 5.0f : 1.0f}; - auto shakencamerapos{Camera.m_owneroffset + - shakescale * glm::vec3(1.5 * Camera.m_owner->ShakeState.offset.x, 2.0 * Camera.m_owner->ShakeState.offset.y, 1.5 * Camera.m_owner->ShakeState.offset.z)}; + // the shake steps at a fixed rate, the frames come at their own: taken at the frame's moment between the steps, it moves as smoothly as the vehicle + auto const shake{Camera.m_owner->shake_between(shake_fraction())}; + auto shakencamerapos{Camera.m_owneroffset + shakescale * glm::vec3(1.5 * shake.offset.x, 2.0 * shake.offset.y, 1.5 * shake.offset.z)}; Camera.Pos = Camera.m_owner->GetWorldPosition(FreeFlyModeFlag ? glm::dvec3(shakencamerapos) : // TODO: vehicle collision box for the external vehicle camera simulation::Train->clamp_inside(shakencamerapos)); @@ -805,7 +816,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index 7e86e99f6..7e5b48573 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -97,6 +97,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/application/editormode.cpp b/application/editormode.cpp index ab150cb7b..a40c6e081 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "application/editormode.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" @@ -600,6 +601,9 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); }); Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // with the heightmap terrain, a new tile waits while a chunk under it is still to come; where none is nor will be, or the walk of + // the chunks doesn't reach, it lies on the other ground or on the NMT guess as before. A scenery without it as before + Layer.coming_source([](glm::dvec2 const &Min, glm::dvec2 const &Max) { return EditorTerrain.active() && EditorTerrain.ground_coming(Min, Max); }); // the imagery often comes before the terrain made from the model: it lies where the terrain will be Layer.guess_source([this](double const X, double const Z, double &Height) { if (nmt_ground(X, Z, Height)) @@ -614,6 +618,8 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) editor_mode::~editor_mode() { editor_track::observe(nullptr); + // the capabilities of a WMS service being read are given up rather than waited for to their timeouts + m_wms_adding.closing = true; } std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const @@ -1412,6 +1418,15 @@ bool editor_mode::update() ui()->set_status(text, false); WriteLog("Editor: " + text, logtype::generic); } + // the drives left without their switches are told once, as the scenery is opened + if (auto const stray{stray_drives().size()}; stray > 0) + { + auto const text{format(STR_P("%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view", + "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view", static_cast(stray)), + stray)}; + ui()->set_notice(text); + WriteLog("Editor: " + text, logtype::generic); + } } } // after the tool has told its own status @@ -1652,6 +1667,7 @@ bool editor_mode::update() draw_build_overlay(); steps.step("laying drawn"); draw_blade_tips(); + draw_stray_drives(); draw_track_intent(); draw_tape(); steps.step("track drawn"); @@ -3309,7 +3325,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) return; } scene::Layers.removed(Instance, false == included.removed); - m_drives_standing.reset(); + drives_changed(); ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } @@ -3346,7 +3362,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } - m_drives_standing.reset(); + drives_changed(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -3391,7 +3407,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - m_drives_standing.reset(); + drives_changed(); std::string file; std::vector values; if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && @@ -4087,7 +4103,7 @@ void editor_mode::render_wms_adding() adding.info.reset(); adding.ticked.clear(); adding.service = url; - adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + adding.reading = std::async(std::launch::async, [url, closing = &adding.closing]() { return editor_orthophoto::describe(url, [closing]() { return closing->load(); }); }); } if (adding.reading.valid()) { @@ -4248,6 +4264,11 @@ void editor_mode::render_view_menu() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + if (ImGui::BeginMenu(STR_C("Camera speed"))) + { + render_camera_settings(); + ImGui::EndMenu(); + } ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); @@ -6979,6 +7000,8 @@ void editor_mode::enter() simulation::Blackbox.close(); // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen ui_layer::draw_cursor(m_draw_cursor); + apply_camera_settings(); + Global.EditorCameraOn = true; if (simulation::Region != nullptr) { @@ -7080,6 +7103,7 @@ void editor_mode::exit() track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there ui_layer::draw_cursor(false); + Global.EditorCameraOn = false; Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -7479,6 +7503,22 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in lay_switch_mode(); break; + case GLFW_KEY_GRAVE_ACCENT: + // ~ (left of 1): the orthophoto shown or hidden; with Ctrl what the camera sees downloaded before anything else + if (false == is_press(Action) || ImGui::GetIO().WantTextInput) + break; + if (Mods & GLFW_MOD_CONTROL) + { + orthophoto_hurry(); + break; + } + if (false == anyModifier) + { + m_orthophoto.enabled(false == m_orthophoto.enabled()); + ui()->set_status(m_orthophoto.enabled() ? STR("Orthophoto on (~)") : STR("Orthophoto off (~)")); + } + break; + case GLFW_KEY_BACKSPACE: // the switch being clicked off the view: the last point taken back if (m_switch_designer.open && m_switch_designer.picking) @@ -8084,3 +8124,113 @@ void editor_mode::render_top_tracks_choice(bool const Combo) if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); } + +void editor_mode::apply_camera_settings() +{ + auto const &camera{EditorSettings.camera()}; + Global.EditorCameraSpeed = camera.speed; + Global.EditorCameraFast = camera.fast; + Global.EditorCameraZoomed = camera.zoomed; +} + +void editor_mode::render_camera_settings() +{ + auto &camera{EditorSettings.camera()}; + auto changed{false}; + auto release{false}; + ImGui::PushItemWidth(180.0f * Global.ui_scale); + auto speed{static_cast(camera.speed)}; + if (ImGui::SliderFloat(STR_C("Speed of the camera"), &speed, 0.05f, 10.0f, "x %.2f", ImGuiSliderFlags_Logarithmic)) + { + camera.speed = speed; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was")); + auto fast{static_cast(camera.fast)}; + if (ImGui::SliderFloat(STR_C("Ctrl speeds it up"), &fast, 1.0f, 30.0f, "x %.1f", ImGuiSliderFlags_Logarithmic)) + { + camera.fast = fast; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was")); + ImGui::PopItemWidth(); + if (ImGui::Checkbox(STR_C("In the top view as fast as the view is zoomed"), &camera.zoomed)) + changed = release = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("As it was"))) + { + camera = {}; + changed = release = true; + } + if (changed) + apply_camera_settings(); + if (release) + EditorSettings.save(); +} + +void editor_mode::orthophoto_hurry() +{ + if (false == m_orthophoto.enabled()) + m_orthophoto.enabled(true); + // what the camera sees of the ground: rays through a grid over the screen to the level of the ground under the camera, or as far + // as the reach of the orthophoto along it where they don't come down to it (the sky) + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + auto const camera{GfxRenderer->Camera_Position()}; + // the level of the ground under the camera: the terrain, else the scenery; with neither the rays go as far as the reach + std::optional level; + // only a level below the camera: one above it (in a tunnel, or flown under the terrain) would put the hits behind it + if (double ground{0.0}; m_streamer.active() && m_streamer.height_at(camera.x, camera.z, ground) && ground < camera.y) + level = ground; + else if (std::vector found; Global.EditorOrtho == false) + { + auto const heights{ground_heights({camera}, true, &found)}; + if (false == found.empty() && found.front() != 0 && heights.front() < camera.y) + level = heights.front(); + } + double constexpr reach{2500.0}; + glm::dvec2 low{camera.x, camera.z}; + glm::dvec2 high{camera.x, camera.z}; + for (int j = 0; j <= 6; ++j) + for (int i = 0; i <= 6; ++i) + { + glm::vec2 const ndc{static_cast(i) / 3.0f - 1.0f, static_cast(j) / 3.0f - 1.0f}; + auto const point = [&inverse, &ndc](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + if (Global.EditorOrtho) + { + // the view straight down: the corners of the screen are where it reaches on the ground + auto const corner{camera + point(0.0f)}; // the view matrix is camera-relative + low = glm::min(low, glm::dvec2{corner.x, corner.z}); + high = glm::max(high, glm::dvec2{corner.x, corner.z}); + continue; + } + auto direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + continue; + direction = glm::normalize(direction); + glm::dvec2 flat{direction.x, direction.z}; + auto distance{reach}; + if (level && direction.y < -1e-6) + distance = std::min(reach, (camera.y - *level) / -direction.y * glm::length(flat)); + if (glm::length(flat) < 1e-6) + continue; + flat = glm::normalize(flat) * distance; + glm::dvec2 const hit{camera.x + flat.x, camera.z + flat.y}; + low = glm::min(low, hit); + high = glm::max(high, hit); + } + auto const count{m_orthophoto.hurry(low, high, camera)}; + ui()->set_status(count > 0 ? format(STR_C("Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)"), count) + : std::string{STR("Orthophoto: the view is all shown already (Ctrl+~)")}); +} diff --git a/application/editormode.h b/application/editormode.h index 81347c950..d25840e18 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -871,6 +872,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); + // View > Camera speed: the speed of the free camera, the Ctrl multiplier, in the top view as fast as it's zoomed; kept in the + // settings of the editor and handed to the camera + void render_camera_settings(); + void apply_camera_settings(); + // ~ (Ctrl): the orthophoto of what the camera sees downloaded before the rest, the ones which failed tried again at once + void orthophoto_hurry(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor void render_environment_window(); bool m_environment_open{false}; @@ -909,6 +916,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri { std::array url{}; std::array filter{}; + // the reading is given up: the editor goes. before the reading, so it outlives the future waiting for the reading to end + std::atomic closing{false}; std::future reading; std::optional info; std::string service; // the address the capabilities were read of @@ -2635,8 +2644,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri struct switch_drive { standing_template standing; - int family{-1}; - int index{0}; + int family{-1}; // -1: a drive not described for the editor, e.g. of Rainsted; it can be replaced, not turned over or moved + int index{-1}; }; std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches @@ -2656,10 +2665,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri void switch_drives_committed(std::vector const &Tracks); // the drives of the switches deleted go with them, in the step of the undo history the deletion made last void drives_deleted(std::vector const &Switches); + // the file of a drive not described for the editor throwing one of the switches, empty when there's none; also one the editor + // kept beside a drive described for it + std::string undescribed_drive(std::vector const &Switches); // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved std::size_t drives_to_blade_tips(); bool m_drives_checked{false}; + // the file of each variant of the drives scanned: its family and its index in the family + std::map, std::less<>> drive_variants() const; + // the switches a template of a drive throws, by what follows its first parameter in their names: "" for a variant described for the + // editor, and for any other template whose switch events throw the track named by its first parameter, as the drives of Rainsted do; + // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not + // described for the editor have no family (-1) + std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); + std::map, std::less<>> m_drive_templates; // read once for each file + // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events + // throw nothing + struct stray_drive + { + scene::instance_handle instance{0}; + std::vector switches; // the names of the switches it throws, as its include gives them + std::string name; // of the switches missing from them + std::string file; + glm::dvec3 location{0.0}; + }; + // all the drives standing in the scenery, read from the files once while no include comes or goes + struct drives_named + { + std::vector drives; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_named; + // the include of a drive or a template changed: what's kept of the drives standing is read again + void drives_changed(); + // the drives whose switch isn't in the scenery, checked against the tracks each time + std::vector stray_drives(bool Wait = false); + void render_stray_drives(); + void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; // places them in the active layer or the given one, as one step of the undo. returns: how many were placed std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index 1c2fc9e9c..8f4f5209c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -253,7 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) { - m_drives_standing.reset(); + drives_changed(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -341,7 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { - m_drives_standing.reset(); + drives_changed(); EditorSnapshot snap; for (auto const instance : Instances) { diff --git a/application/editormodeselftestswitch.cpp b/application/editormodeselftestswitch.cpp index 891ca6d68..b9c502d17 100644 --- a/application/editormodeselftestswitch.cpp +++ b/application/editormodeselftestswitch.cpp @@ -549,6 +549,25 @@ editor_mode::selftest_result editor_mode::selftest_switch(std::string const &com WriteLog("SELFTEST drives " + name + ": chosen " + (m_switch.drive >= 0 ? m_switch.drives[m_switch.drive].name : std::string{"none"}) + ", side " + std::to_string(m_switch.drive_side) + ", standing" + files + ", steps " + std::to_string(m_history.size())); return selftest_result::handled; } + if (command == "straydrives") + { + auto const stray{stray_drives(true)}; + std::string names; + for (auto const &drive : stray) + names += " " + drive.name + "(" + drive.file + ")"; + WriteLog(format("SELFTEST straydrives: %zu", stray.size()) + names); + return selftest_result::handled; + } + if (command == "drivewhose") + { + // the drive the editor tells for the switch: its file and family, -1 for one not described + std::string name; + words >> name; + auto *track{simulation::Paths.find(name)}; + auto const found{track != nullptr ? find_switch_drive(*track) : std::nullopt}; + WriteLog("SELFTEST drivewhose " + name + ": " + (found.has_value() ? found->standing.file + " family " + std::to_string(found->family) : std::string{"none"})); + return selftest_result::handled; + } if (command == "driveflip") { std::string name; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 3e0a67854..931350af1 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editormodeshared.h" +#include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" @@ -25,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "imgui/imgui.h" #include +#include #include #include #include @@ -44,6 +46,21 @@ std::string drive_file(std::string Text) return Text; } +// the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as +// they're written +TTrack *track_named(std::string const &Name) +{ + auto *track{simulation::Paths.find(Name)}; + return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); +} + +// a template by the name of its file, with no folder: told to the user, who picks the drives by their names +std::string file_name(std::string const &File) +{ + auto const slash{File.find_last_of('/')}; + return slash != std::string::npos ? File.substr(slash + 1) : File; +} + int drive_side(std::string const &Side) { if (Side == "left") @@ -168,7 +185,8 @@ void editor_mode::switch_drives_committed(std::vector const &Tracks) drives = switch_drives_standing(); auto const found{drives->find(drive_file(track->name()))}; auto const spot{editor_track::drive_spot_of(*track)}; - if (found == drives->end() || false == spot.has_value()) + // a drive not described for the editor has no parameters known to set it with, nor a height above the rail; it stays put + if (found == drives->end() || found->second.family < 0 || false == spot.has_value()) continue; auto const &drive{found->second.standing}; auto const &included{scene::Layers.instance(drive.instance)}; @@ -221,7 +239,15 @@ bool editor_mode::place_switch_drive(TTrack &Switch) item.track = Switch.name(); item.tilt = spot->tilt; if (auto const present{find_switch_drive(Switch)}) + { + // one not described for the editor is kept: it may set the speed over the switch or carry its ballast too + if (present->family < 0) + { + tool.status = format(STR_C("Switch %s keeps its drive %s, which isn't described for the editor"), Switch.name().c_str(), file_name(present->standing.file).c_str()); + return false; + } return replace_switch_drive(Switch, tool.drive, (present->index & 1) != (driveright ? 1 : 0)); + } std::string error; if (place_templates({item}, error) == 0) { @@ -255,22 +281,147 @@ std::map const &editor_mode::switch_driv return included.removed || included.dead; })) return kept->by_switch; + auto const variants{drive_variants()}; + kept.emplace(); + kept->frame = ImGui::GetFrameCount(); + kept->revision = tool.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + auto const variant{variants.find(standing.file)}; + auto const [family, index]{variant != variants.end() ? variant->second : std::pair{-1, -1}}; + // the drive of a double switch of Rainsted stands for each of its switches, a..d + for (auto const &suffix : drive_switches(standing.file, variants)) + { + // a drive described for the editor goes before one of Rainsted set to the same switch, which the editor kept beside it + auto const [entry, fresh]{kept->by_switch.try_emplace(drive_file(standing.values[0] + suffix), switch_drive{standing, family, index})}; + if (false == fresh && entry->second.family < 0 && family >= 0) + entry->second = switch_drive{standing, family, index}; + } + } + return kept->by_switch; +} + +std::vector const &editor_mode::drive_switches(std::string const &File, std::map, std::less<>> const &Variants) +{ + static std::vector const single{std::string{}}; + if (Variants.contains(File)) + return single; + auto const [found, fresh]{m_drive_templates.try_emplace(File)}; + if (fresh) + editor_includes::switched_tracks(File, found->second); + return found->second; +} + +std::map, std::less<>> editor_mode::drive_variants() const +{ + auto const &tool{m_switch}; std::map, std::less<>> variants; for (int family = 0; family < static_cast(tool.drives.size()); ++family) for (int index = 0; index < 4; ++index) if (false == tool.drives[family].files[index].empty()) variants[drive_file(tool.drives[family].files[index])] = {family, index}; - kept.emplace(); - kept->frame = ImGui::GetFrameCount(); - kept->revision = tool.drives_revision; - kept->instances = instances; - for (auto &standing : standing_templates([&](std::string const &File) { return variants.contains(File); })) + return variants; +} + +void editor_mode::drives_changed() +{ + m_drives_standing.reset(); + m_drives_named.reset(); +} + +std::vector editor_mode::stray_drives(bool const Wait) +{ + scan_switch_drives(Wait); + auto const instances{static_cast(scene::Layers.instance_count())}; + auto &kept{m_drives_named}; + if (false == kept.has_value() || kept->revision != m_switch.drives_revision || kept->instances != instances) { - auto const &[family, index]{variants[standing.file]}; - auto name{drive_file(standing.values[0])}; - kept->by_switch.try_emplace(std::move(name), switch_drive{std::move(standing), family, index}); + auto const variants{drive_variants()}; + kept.emplace(); + kept->revision = m_switch.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + stray_drive drive{standing.instance, {}, {}, standing.file, standing.location}; + for (auto const &suffix : drive_switches(standing.file, variants)) + drive.switches.push_back(standing.values[0] + suffix); + kept->drives.push_back(std::move(drive)); + } + } + // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its + // switches gone, while one stands it still throws it + std::vector stray; + for (auto const &drive : kept->drives) + { + auto const &included{scene::Layers.instance(drive.instance)}; + // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts + if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { + auto const *track{track_named(Name)}; + return track != nullptr && false == track->m_editorremoved; + })) + continue; + std::string missing; + for (auto const &name : drive.switches) + missing += (missing.empty() ? "" : ", ") + name; + stray.push_back(drive); + stray.back().name = std::move(missing); + } + return stray; +} + +void editor_mode::render_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + ImGui::PushID("straydrives"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.55f, 0.25f, 1.0f)); + auto const open{ImGui::TreeNode("##straydrives", STR_P("%zu drive with no switch", "%zu drives with no switch", static_cast(stray.size())), stray.size())}; + ImGui::PopStyleColor(); + item_tooltip("Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name"); + if (open) + { + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + auto const label{format("%s (%s, %.0f m)##%d", drive.name.c_str(), file_name(drive.file).c_str(), glm::length(drive.location - camera), static_cast(drive.instance))}; + if (ImGui::Selectable(label.c_str(), m_instance == drive.instance)) + { + select_include(drive.instance); + fly_to(drive.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 25.0); + } + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list +void editor_mode::draw_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + // the ones far off would only crowd the view of the whole line + auto constexpr range{3000.0}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + ImVec2 at; + if (glm::length(drive.location - camera) > range || false == projection.project(drive.location, at)) + continue; + auto const selected{m_instance == drive.instance}; + drawlist->AddCircleFilled(at, 8.0f, IM_COL32(0, 0, 0, 170)); + drawlist->AddCircle(at, 7.0f, selected ? overlay_color::selected : overlay_color::invalid, 0, 3.0f); + auto const text{format(STR_C("%s: no switch of this name"), drive.name.c_str())}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const corner{at.x + 12.0f, at.y - 0.5f * size.y}; + drawlist->AddRectFilled({corner.x - 3.0f, corner.y - 1.0f}, {corner.x + size.x + 3.0f, corner.y + size.y + 1.0f}, IM_COL32(0, 0, 0, 160), 3.0f); + drawlist->AddText(corner, selected ? overlay_color::selected : overlay_color::invalid, text.c_str()); } - return kept->by_switch; } void editor_mode::apply_switch_drive_choice(TTrack &Switch) @@ -280,7 +431,10 @@ void editor_mode::apply_switch_drive_choice(TTrack &Switch) place_switch_drive(Switch); return; } - if (auto const found{find_switch_drive(Switch)}; found.has_value() && remove_templates({found->standing.instance}) > 0) + auto const found{find_switch_drive(Switch)}; + if (found.has_value() && found->family < 0) + m_switch.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found->standing.file).c_str())); + else if (found.has_value() && remove_templates({found->standing.instance}) > 0) m_switch.status = format(STR_C("Switch %s without a drive now"), Switch.name().c_str()); } @@ -299,7 +453,15 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return false; } auto const &found{present->standing}; + // a drive not described for the editor, as one of a double switch, may set the speed over the switch or carry its ballast too: it's kept as it is + if (present->family < 0) + { + tool.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found.file).c_str())); + return false; + } auto const family{Family >= 0 ? Family : present->family}; + if (family >= static_cast(tool.drives.size())) + return false; auto const index{Flip ? present->index ^ 1 : present->index}; template_item item; item.file = tool.drives[family].files[index]; @@ -334,19 +496,82 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return true; } +std::string editor_mode::undescribed_drive(std::vector const &Switches) +{ + // the drives described for the editor read first: before they are, every drive would pass for one not described + scan_switch_drives(true); + std::vector names; + for (auto const *track : Switches) + if (track != nullptr) + names.push_back(drive_file(track->name())); + auto const variants{drive_variants()}; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == variants.contains(File) && false == drive_switches(File, variants).empty(); })) + { + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return std::find(names.begin(), names.end(), drive_file(standing.values[0] + Suffix)) != names.end(); })) + return file_name(standing.file); + } + return {}; +} + void editor_mode::drives_deleted(std::vector const &Switches) { if (m_history.empty()) return; + // the names of the switches deleted, as the game finds them; they're retired already + std::vector deleted; for (auto const *track : Switches) + if (track != nullptr && track->eType == tt_Switch) + deleted.push_back(drive_file(track->name())); + if (deleted.empty()) + return; + auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; + // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, + // still has the drive and the ballast, so it's looked for too + auto const stands = [](std::string const &Name) { + if (auto const *track{track_named(Name)}; track != nullptr) + return false == track->m_editorremoved; + auto const name{drive_file(Name)}; + auto const &tracks{simulation::Paths.sequence()}; + return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); + }; + auto const take_away = [&](scene::instance_handle const Instance) { + if (false == scene::Layers.removable(Instance)) + return; + scene::Layers.removed(Instance, true); + m_history.back().instances.push_back(Instance); + }; + auto const variants{drive_variants()}; + // each drive throwing a switch deleted, also one the editor kept beside a drive described for it; the drive of a double switch throws + // the others too, so it goes with the last of them + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) { - if (track == nullptr || track->eType != tt_Switch) + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return named(standing.values[0] + Suffix); }) && + std::none_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return stands(standing.values[0] + Suffix); })) + take_away(standing.instance); + } + // the sleepers and the ballast laid by a switch, named by it as its drive is: of a double switch by the name its switches have in + // common, a..d or _a.._d, so they go with the last of them + static std::array const parts{"", "a", "b", "c", "d", "_a", "_b", "_c", "_d"}; + std::map> beds; + for (auto const &standing : standing_templates([](std::string const &) { return true; })) + { + auto const &name{standing.values[0]}; + // named by a single switch, it's this switch's alone; a switch named a beside it may be another single one + if (named(name)) + { + if (stands(name)) + continue; + } + else if (std::none_of(parts.begin(), parts.end(), [&](char const *Part) { return named(name + Part); }) || + std::any_of(parts.begin(), parts.end(), [&](char const *Part) { return stands(name + Part); })) continue; - auto const found{find_switch_drive(*track)}; - if (false == found.has_value() || false == scene::Layers.removable(found->standing.instance) || scene::Layers.instance(found->standing.instance).removed) - continue; - scene::Layers.removed(found->standing.instance, true); - m_history.back().instances.push_back(found->standing.instance); + auto const [bed, fresh]{beds.try_emplace(standing.file)}; + if (fresh) + bed->second = drive_switches(standing.file, variants).empty() && editor_includes::switch_bed(standing.file); + if (bed->second) + take_away(standing.instance); } } @@ -359,7 +584,7 @@ std::size_t editor_mode::drives_to_blade_tips() { if (track == nullptr || track->m_editorremoved || track->eType != tt_Switch) continue; - if (auto const found{find_switch_drive(*track)}; found.has_value() && scene::Layers.removable(found->standing.instance)) + if (auto const found{find_switch_drive(*track)}; found.has_value() && found->family >= 0 && scene::Layers.removable(found->standing.instance)) { switches.push_back(track); before.emplace_back(found->standing.instance, scene::Layers.directive(found->standing.instance)); diff --git a/application/editormodeswitchplace.cpp b/application/editormodeswitchplace.cpp index b35ef8c48..82028a943 100644 --- a/application/editormodeswitchplace.cpp +++ b/application/editormodeswitchplace.cpp @@ -1609,6 +1609,13 @@ bool editor_mode::replace_double_slip(TTrack &Part, editor_track::switch_templat return false; } } + // a drive not described for the editor may set the speed or carry the ballast of the slip too: the editor can neither take it + // away nor move it to the switches laid anew, which get other names, so the slip is left as it is + if (auto const drive{undescribed_drive({switches.begin(), switches.end()})}; false == drive.empty()) + { + state.status = refused(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); + return false; + } struct end { TTrack *track; diff --git a/application/editormodeswitchtemplate.cpp b/application/editormodeswitchtemplate.cpp index e6a8496bd..6edef6a65 100644 --- a/application/editormodeswitchtemplate.cpp +++ b/application/editormodeswitchtemplate.cpp @@ -286,6 +286,9 @@ bool editor_mode::change_slip_template(TTrack &Part, int const Index) for (auto const *part : parts) if (false == part->Dynamics.empty()) return fail(STR_C("The slip can't be laid again while vehicles stand on it")); + // its drives go with it and the new one gets its own: a drive not described for the editor can't be told apart from them + if (auto const drive{slip.has_value() ? undescribed_drive(slip->switches) : std::string{}}; false == drive.empty()) + return fail(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); // a single slip laid again joins the pair of the tracks it joined: the point given by them auto const &ends{slip.has_value() ? slip->ends : std::array{}}; auto const pair{slip.has_value() && record.type == "Rkp" ? 0.5 * (ends[0] + ends[3]) : glm::dvec3{0.0}}; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index a37c98f70..878e18aa3 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -282,6 +282,7 @@ void editor_mode::render_switch_ui() ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", tool.status.c_str()); ImGui::PopTextWrapPos(); } + render_stray_drives(); if (ImGui::Button(STR_C("Template editor..."))) m_switch_designer.open = true; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 91bf9c027..6e0fe60c7 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1171,22 +1171,34 @@ void editor_mode::render_turnout_ui() { auto const family{drive->family}; auto const variant{drive->index}; + // a drive not described for the editor is shown by its file + auto const described{family >= 0 && family < static_cast(m_switch.drives.size())}; + auto const &file{drive->standing.file}; + auto const shown{described ? m_switch.drives[family].name : format("%s (%s)", file.substr(file.find_last_of('/') + 1).c_str(), STR_C("not described"))}; if (begin_fields("##standingdrive", 0.3f)) { field_row("Drive##standing"); - if (ImGui::BeginCombo("##standing", m_switch.drives[family].name.c_str())) + if (false == described) + ImGui::TextUnformatted(shown.c_str()); + else if (ImGui::BeginCombo("##standing", shown.c_str())) { for (int i = 0; i < static_cast(m_switch.drives.size()); ++i) if (ImGui::Selectable(m_switch.drives[i].name.c_str(), family == i) && i != family) replace_switch_drive(Switch, i, false); ImGui::EndCombo(); } - if (ImGui::IsItemHovered()) + if (described && ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", STR_C("Puts another drive in place of the drive of this switch, on the same side"), format(STR_C("Drive: events %s+ and %s- switch it, also in the map"), Switch.name().c_str(), Switch.name().c_str()).c_str()); ImGui::EndTable(); } int side{((variant >> 1) == (variant & 1)) ? 0 : 1}; - if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, + if (false == described) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted")); + ImGui::PopTextWrapPos(); + } + else if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, {1, STR_C("other side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}})) flip_switch_drive(Switch); } diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 207a1756e..87366757f 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -88,7 +88,7 @@ std::vector scenarioloader_ui::get_random_trivia() json triviaData = json::parse(fileContent); // select random - int i = Random(0, static_cast(triviaData.size()) - 1); + int i = RandomInt(0, static_cast(triviaData.size()) - 1); std::string triviaStr = triviaData[i]["text"]; std::string background = triviaData[i]["background"]; if (triviaData[i].contains("scenery")) diff --git a/blackbox_doc.md b/blackbox_doc.md index 126cea033..9314b94e6 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -9,9 +9,8 @@ starter, a viewer) can replay the session on the map, or set the user's driving `blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no `blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. -The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are -hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail -vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +The latter writes the `.dat` logs of the trains only: of each driver who drives rail vehicles, not of the +passengers nor of the vehicles of the roads, so a big scenery gives far fewer of them. It is never written in an editor session. The file goes to `physicslog/_.blackbox` (the local time the recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. @@ -27,17 +26,10 @@ goes on in that driver's log, begun then if it is the first time. Back with a dr the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of the driver of its train. So the speed recorder's tape can be read from them as before, also while the simulator runs, without a log of every vehicle. A driver who writes a log of its own, with -`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the -user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the -user drives has no log. Like those of `physicslog yes`, they are written every +`physicslog.trains yes`, isn't written twice. Like those of `physicslog yes`, they are written every two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds -of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +of real time of them (at a higher time speed, more of the simulated time). A file another program holds for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. -The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of -those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as -long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. -Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, -and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no diff --git a/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index ab7f74b24..68b153559 100644 --- a/editor/editorGeoMap.cpp +++ b/editor/editorGeoMap.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorGeoMap.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorHttp.hpp" #include "editor/editorOrthophoto.hpp" #include "utilities/translation.h" @@ -164,6 +165,8 @@ bool parse_place(std::string const &Text, glm::dvec2 &Point) editor_map::~editor_map() { + // the download running is broken off rather than waited for to its end or its timeout + m_closing = true; if (m_request.valid()) m_request.wait(); release(); @@ -328,12 +331,13 @@ void editor_map::request(glm::vec2 const &Size) char bbox[160]; std::snprintf(bbox, sizeof(bbox), "%.1f,%.1f,%.1f,%.1f", low.x, low.y, high.x, high.y); auto const url{kMapService + "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=osm&STYLES=&SRS=EPSG:2180&BBOX=" + bbox + "&WIDTH=" + std::to_string(width) + "&HEIGHT=" + std::to_string(height) + "&FORMAT=image/png"}; - m_request = std::async(std::launch::async, [url, low, high]() { + m_request = std::async(std::launch::async, [url, low, high, closing = &m_closing]() { image result; result.low = low; result.high = high; std::vector data; - if (false == editor_http_get(url, data, result.error)) + thread_local editor_http::client client; + if (false == client.get(url, data, result.error, [closing]() { return closing->load(); })) return result; int w{0}, h{0}, components{0}; // the texture loader turns the stb flip on for the whole process only once it loads its first texture: this thread diff --git a/editor/editorGeoMap.hpp b/editor/editorGeoMap.hpp index 5c160095b..a1dd07124 100644 --- a/editor/editorGeoMap.hpp +++ b/editor/editorGeoMap.hpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -86,6 +87,7 @@ class editor_map glm::vec2 m_pressed{0.f}; bool m_dragging{false}; std::future m_request; + std::atomic m_closing{false}; // the download of the map is given up: the map goes std::uint64_t m_texture{0}; glm::dvec2 m_image_low{0.0}; glm::dvec2 m_image_high{0.0}; diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 81a195aeb..cbda581f0 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -45,15 +45,209 @@ struct client::platform #if defined(_WIN32) +namespace +{ + +DWORD constexpr kStopCheck{50}; // ms between the looks at whether the transfer is to be given up + +// what the callback of WinHTTP hands over to the thread waiting for it +struct transfer_state +{ + HANDLE done{::CreateEventW(nullptr, FALSE, FALSE, nullptr)}; // the operation begun finished or failed + HANDLE closed{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; // the request is called back no more + DWORD error{ERROR_SUCCESS}; // of the operation that failed + DWORD size{0}; // bytes available or read + + transfer_state() = default; + transfer_state(transfer_state const &) = delete; + transfer_state &operator=(transfer_state const &) = delete; + ~transfer_state() + { + if (done != nullptr) + ::CloseHandle(done); + if (closed != nullptr) + ::CloseHandle(closed); + } +}; + +void CALLBACK on_status(HINTERNET, DWORD_PTR const Context, DWORD const Status, LPVOID const Info, DWORD const Length) +{ + auto *state{reinterpret_cast(Context)}; + if (state == nullptr) + return; + switch (Status) + { + case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: + case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: + break; + case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: + state->size = *static_cast(Info); + break; + case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: + state->size = Length; + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + state->error = static_cast(Info)->dwError; + break; + case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: + ::SetEvent(state->closed); + return; + default: + return; + } + ::SetEvent(state->done); +} + +// one GET on a connection of its own. the steps of WinHTTP are asynchronous and waited for while the stop is looked at, so a +// transfer is given up at once also while a service keeps the connection waiting: the closing of the editor doesn't wait for +// the timeouts of a service that doesn't answer +class transfer +{ + public: + transfer(stop_check const &Stop, std::string &Error) : + m_stop(Stop), + m_error(Error) + { + } + ~transfer() + { + close(); + } + transfer(transfer const &) = delete; + transfer &operator=(transfer const &) = delete; + + bool open(HINTERNET const Session, std::wstring const &Host, INTERNET_PORT const Port, std::wstring const &Path, bool const Secure) + { + if (m_state.done == nullptr || m_state.closed == nullptr) + return failed(::GetLastError()); + m_connection = ::WinHttpConnect(Session, Host.c_str(), Port, 0); + if (m_connection == nullptr) + return failed(::GetLastError()); + m_request = ::WinHttpOpenRequest(m_connection, L"GET", Path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, Secure ? WINHTTP_FLAG_SECURE : 0); + if (m_request == nullptr) + return failed(::GetLastError()); + auto context{reinterpret_cast(&m_state)}; + if (false == ::WinHttpSetOption(m_request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context))) + return failed(::GetLastError()); + if (::WinHttpSetStatusCallback(m_request, on_status, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, 0) == WINHTTP_INVALID_STATUS_CALLBACK) + return failed(::GetLastError()); + m_called_back = true; + return true; + } + + bool send() + { + return step([this]() { return ::WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast(&m_state)); }); + } + + bool receive() + { + return step([this]() { return ::WinHttpReceiveResponse(m_request, nullptr); }); + } + + DWORD status() const + { + DWORD status{0}; + DWORD size{sizeof(status)}; + ::WinHttpQueryHeaders(m_request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + return status; + } + + // the whole body of the response + bool read_all(std::vector &Out) + { + while (true) + { + if (m_stop()) + { + m_error = "cancelled"; + return false; + } + if (false == step([this]() { return ::WinHttpQueryDataAvailable(m_request, nullptr); })) + return false; + auto const available{m_state.size}; + if (available == 0) + return true; + if (Out.size() + available > kLargest) + { + m_error = kTooLarge; + Out.clear(); + return false; + } + auto const offset{Out.size()}; + Out.resize(offset + available); + auto const read{step([this, &Out, offset, available]() { return ::WinHttpReadData(m_request, Out.data() + offset, available, nullptr); })}; + Out.resize(offset + (read ? m_state.size : 0)); + if (false == read) + return false; + } + } + + void close() + { + if (m_request != nullptr) + { + ::WinHttpCloseHandle(m_request); + m_request = nullptr; + // the closing is the last callback: after it the state, and the buffer of a read broken off, are no longer written to + if (m_called_back) + ::WaitForSingleObject(m_state.closed, INFINITE); + m_called_back = false; + } + if (m_connection != nullptr) + { + ::WinHttpCloseHandle(m_connection); + m_connection = nullptr; + } + } + + private: + bool failed(DWORD const Code) + { + m_error = "WinHTTP error " + std::to_string(Code); + return false; + } + + // begins an operation and waits for it: false when it failed, or a stop was asked for meanwhile + template bool step(Begin const &Operation) + { + m_state.error = ERROR_SUCCESS; + if (false == Operation()) + return failed(::GetLastError()); + while (::WaitForSingleObject(m_state.done, kStopCheck) != WAIT_OBJECT_0) + { + if (m_stop()) + { + // closed at once: the operation broken off doesn't write into the buffer any more once this returns + close(); + m_error = "cancelled"; + return false; + } + } + if (m_state.error != ERROR_SUCCESS) + return failed(m_state.error); + return true; + } + + stop_check const &m_stop; + std::string &m_error; + transfer_state m_state; + HINTERNET m_connection{nullptr}; + HINTERNET m_request{nullptr}; + bool m_called_back{false}; // the closing of the request is called back +}; + +} // namespace + client::client() : m_platform(std::make_unique()) { wchar_t const *agent = L"MaSzyna-editor"; #ifdef WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); #endif if (m_platform->session == nullptr) // automatic proxy needs windows 8.1+ - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (m_platform->session != nullptr) ::WinHttpSetTimeouts(m_platform->session, 10000, 10000, 15000, 20000); } @@ -94,64 +288,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st std::wstring const host(parts.lpszHostName, parts.dwHostNameLength); std::wstring const path = std::wstring(parts.lpszUrlPath, parts.dwUrlPathLength) + std::wstring(parts.lpszExtraInfo, parts.dwExtraInfoLength); - HINTERNET connection = ::WinHttpConnect(m_platform->session, host.c_str(), parts.nPort, 0); - HINTERNET request = connection ? ::WinHttpOpenRequest(connection, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) - : nullptr; - auto const close = [&]() { - if (request != nullptr) - ::WinHttpCloseHandle(request); - if (connection != nullptr) - ::WinHttpCloseHandle(connection); - }; - - if (request == nullptr || !::WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || !::WinHttpReceiveResponse(request, nullptr)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); + transfer request{Stop, Error}; + if (false == request.open(m_platform->session, host, parts.nPort, path, parts.nScheme == INTERNET_SCHEME_HTTPS) || false == request.send() || false == request.receive()) return false; - } - - DWORD status{0}; - DWORD statussize{sizeof(status)}; - ::WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statussize, WINHTTP_NO_HEADER_INDEX); - - for (;;) - { - if (Stop()) - { - Error = "cancelled"; - close(); - return false; - } - DWORD available{0}; - if (!::WinHttpQueryDataAvailable(request, &available)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - if (available == 0) - break; - if (Out.size() + available > kLargest) - { - Error = kTooLarge; - close(); - Out.clear(); - return false; - } - std::size_t const offset = Out.size(); - Out.resize(offset + available); - DWORD received{0}; - if (!::WinHttpReadData(request, Out.data() + offset, available, &received)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - Out.resize(offset + received); - } - close(); + auto const status{request.status()}; + if (false == request.read_all(Out)) + return false; + request.close(); if (status != 200) { diff --git a/editor/editorIncludeInfo.cpp b/editor/editorIncludeInfo.cpp index ca532f1ce..450cde5a2 100644 --- a/editor/editorIncludeInfo.cpp +++ b/editor/editorIncludeInfo.cpp @@ -548,6 +548,71 @@ bool event_names(std::string const &File, std::vector &Names) return true; } +bool switched_tracks(std::string const &File, std::vector &Suffixes) +{ + Suffixes.clear(); + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + // event switch + auto const tokens{tokenize(text.content)}; + std::string const first{"(p1)"}; + // a drive has the events thrown by the keys and the map, (p1)+ and (p1)-, or moves a model, lights its lamps or throws a double switch at + // once; the sleepers or the ballast of a switch may throw it on their own events too, with nothing else, but they don't drive it + bool driven{false}; + for (std::size_t idx = 0; idx + 2 < tokens.size() && false == driven; ++idx) + { + if (tokens[idx] != "event") + { + continue; + } + auto const &name{tokens[idx + 1]}; + auto const &kind{tokens[idx + 2]}; + driven = (name.size() > first.size() && name.compare(0, first.size(), first) == 0 && (name.back() == '+' || name.back() == '-')) || (kind != "switch" && kind != "trackvel"); + } + if (false == driven) + { + return true; + } + for (std::size_t idx = 0; idx + 4 < tokens.size(); ++idx) + { + if (tokens[idx] != "event" || tokens[idx + 2] != "switch" || tokens[idx + 4].compare(0, first.size(), first) != 0) + { + continue; + } + auto suffix{tokens[idx + 4].substr(first.size())}; + if (std::find(Suffixes.begin(), Suffixes.end(), suffix) == Suffixes.end()) + { + Suffixes.push_back(std::move(suffix)); + } + } + return true; +} + +bool switch_bed(std::string const &File) +{ + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + auto const tokens{tokenize(text.content)}; + for (std::size_t idx = 0; idx < tokens.size(); ++idx) + { + // node track ... + if (tokens[idx] == "include" || (tokens[idx] == "node" && idx + 4 < tokens.size() && tokens[idx + 4] == "track") || + (tokens[idx] == "event" && idx + 2 < tokens.size() && tokens[idx + 2] != "switch" && tokens[idx + 2] != "trackvel")) + { + return false; + } + } + return true; +} + bool signal_speeds(std::string const &File, std::vector &Speeds) { Speeds.clear(); diff --git a/editor/editorIncludeInfo.hpp b/editor/editorIncludeInfo.hpp index 7a2da9dfa..96b84b44a 100644 --- a/editor/editorIncludeInfo.hpp +++ b/editor/editorIncludeInfo.hpp @@ -90,6 +90,13 @@ int parameter_count(std::string const &File); bool signal_speeds(std::string const &File, std::vector &Speeds); // the names of the events the template defines, as they're written after "event", lower case. returns: false if the file can't be read bool event_names(std::string const &File, std::vector &Names); +// the tracks the switch events of the template throw, named by its first parameter: what follows (p1) in their names, lower case, "" +// for the track named (p1) itself, "a" for (p1)a of a double switch; none for the sleepers or the ballast of a switch, whose events only +// throw it or set its speed, with no (p1)+ or (p1)-. returns: false if the file can't be read +bool switched_tracks(std::string const &File, std::vector &Suffixes); +// true if the template can be the sleepers or the ballast of a switch: it puts no track, includes nothing and has no events but those +// throwing a switch or setting its speed. false if the file can't be read +bool switch_bed(std::string const &File); // the aspects of a block signal of the template: 4 where its events give S3, the green light flashing with the next signal at S5, // the warning two signals ahead, else 3. returns: 0 if the file can't be read int block_aspects(std::string const &File); diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index f663dd012..d3254a2c1 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -63,12 +63,6 @@ double steady_seconds() } // namespace -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error) -{ - thread_local http_client client; - return client.get(Url, Out, Error, []() { return false; }); -} - namespace { @@ -688,7 +682,7 @@ std::string xml_element(std::string const &Xml, std::string const &Tag, std::siz } // namespace -editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service) +editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service, std::function const &Stop) { service_info info; auto url{Service}; @@ -700,8 +694,10 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S // a few tries, the services drop connections and time out now and then std::vector data; auto read{false}; - for (int attempt = 0; attempt < 3 && false == read; ++attempt) - read = editor_http_get(url, data, info.error); + stop_check const stopping{Stop ? Stop : stop_check{[]() { return false; }}}; + thread_local http_client client; + for (int attempt = 0; attempt < 3 && false == read && false == stopping(); ++attempt) + read = client.get(url, data, info.error, stopping); if (false == read) return info; info.error.clear(); @@ -937,23 +933,47 @@ void editor_orthophoto::ground_arrived() { if (!m_height) return; - for (auto &entry : m_tiles) + for (auto &[key, t] : m_tiles) { - auto &t{entry.second}; - if (!t.grounded || !t.guessed) - continue; - // the middle and the corners: a chunk of the terrain is much larger than a tile, it covers some of these when it comes. A tile - // lying flat, with nothing to go by, also goes onto the model once it's in - glm::dvec2 const corner = tile_corner(entry.first); - for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) - if (double y; m_height(corner.x - u * tile_size, corner.y - v * tile_size, y) || (t.heights.empty() && m_guess && m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y))) - { - t.grounded = false; - break; - } + if (t.grounded && ground_came(key, t)) + t.grounded = false; } } +bool editor_orthophoto::waits_for_ground(tile_key const &Key) const +{ + // a tile laid out already stays, sampled again when its ground comes (ground_came) + if (!m_coming || m_tiles.contains(Key)) + return false; + glm::dvec2 const corner = tile_corner(Key); + return m_coming(corner - glm::dvec2{tile_size}, corner); +} + +bool editor_orthophoto::ground_came(tile_key const &Key, tile const &Tile) const +{ + glm::dvec2 const corner = tile_corner(Key); + // a tile lying flat, with nothing to go by, also goes onto the model once it's in: the middle and the corners + if (Tile.guessed && Tile.heights.empty() && m_guess) + for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) + if (double y; m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y)) + return true; + // the points the ground didn't answer, every second one of the grid (16 m) and the edges: a chunk of the terrain is about as + // large as a tile and comes over a part of it, often a band along a side; partly answered tiles count too, not only the guessed + static_assert(ground_grid % 2 == 0, "the edges of the grid are among its even points"); + int constexpr samples{ground_grid + 1}; + double constexpr step{tile_size / ground_grid}; + for (auto const index : Tile.unanswered) + { + int const i{index % samples}; + int const j{index / samples}; + if (i % 2 != 0 || j % 2 != 0) + continue; + if (double y; m_height(corner.x - i * step, corner.y - j * step, y)) + return true; + } + return false; +} + void editor_orthophoto::detach_scene() { for (auto &entry : m_tiles) @@ -1032,6 +1052,20 @@ editor_orthophoto::statistics editor_orthophoto::stats() const return out; } +int editor_orthophoto::first_level(tile const &Tile, int const Level) +{ + // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow + // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk + if (Level > standard_pixels && Tile.level < standard_pixels) + return standard_pixels; + return Level; +} + +bool editor_orthophoto::outside_area(tile_key const &Key) const +{ + return false == m_area.empty() && 0 == m_area_tiles.count(Key); +} + int editor_orthophoto::level_for(int Distance, bool Hires) { // coarser imagery further away keeps the memory use of large radii in check @@ -1233,6 +1267,7 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) Tile.scene_dirty = true; Tile.heights.clear(); Tile.surface.clear(); + Tile.unanswered.clear(); glm::dvec2 const corner = tile_corner(Key); glm::dvec2 const min(corner.x - tile_size, corner.y - tile_size); @@ -1304,6 +1339,21 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) } } + // the points the ground didn't answer: the ground coming there later (the terrain loaded after the imagery, which comes from the + // disk cache at once) has the tile sampled again, rather than left at the heights filled in or guessed now + Tile.unanswered.clear(); + auto const columns{static_cast(samples)}; + for (std::size_t index = 0; index < heights.size(); ++index) + { + if (heights[index] != no_height) + continue; + // in the scene the heights come from the triangles, and a steep spot (a wall, a quarry face) gives none: where the heightmap + // terrain answers the point, its ground is there already, and ground_came() would find it again on every chunk that comes + if (double y; surface && m_height && m_height(corner.x - static_cast(index % columns) * step, corner.y - static_cast(index / columns) * step, y)) + continue; + Tile.unanswered.push_back(static_cast(index)); + } + // holes (places without ground) take the average of their neighbours, spreading inwards std::size_t missing = std::count(heights.begin(), heights.end(), no_height); if (missing == heights.size()) @@ -1630,7 +1680,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) { tile_key const key{centre.first + dx, centre.second + dy}; // outside the download area: nothing asked for, nothing shown - if (false == m_area.empty() && 0 == m_area_tiles.count(key)) + if (outside_area(key)) { if (auto const found{m_tiles.find(key)}; found != m_tiles.end()) { @@ -1639,14 +1689,12 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) } continue; } + if (waits_for_ground(key)) + continue; tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; - int level = level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires); - // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow - // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk - if (level > standard_pixels && t.level < standard_pixels) - level = standard_pixels; + int const level = first_level(t, level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires)); if (t.empty || (t.level == level && t.alpha == m_alpha) || (t.requested == level && t.requested_alpha == m_alpha) || now < t.retry_at) continue; schedule(key, t, level, m_alpha); @@ -1713,7 +1761,8 @@ void editor_orthophoto::worker() continue; long long const dx = it->key.first - m_focus.first; long long const dy = it->key.second - m_focus.second; - long long const d = dx * dx + dy * dy; + // the tiles hurried (Ctrl+~) before all the others, the nearest of them first + long long const d = dx * dx + dy * dy - (m_urgent.count(it->key) > 0 ? (1LL << 40) : 0LL); if (d < bestdistance) { bestdistance = d; @@ -1730,6 +1779,7 @@ void editor_orthophoto::worker() { current = *best; m_queue.erase(best); + m_urgent.erase(current.key); m_running.insert(current.key); if (current.level >= hires_pixels) ++m_running_hires; @@ -1957,3 +2007,58 @@ void editor_orthophoto::draw(glm::mat4 const &ViewProjection, glm::dvec3 const & drawlist->PopTextureID(); } } + +bool editor_orthophoto::hurry_tile(tile_key const &Key, int const Distance) +{ + // as update() does: nothing asked for outside the download area, nor outside the area the service covers, where the requests + // can't be answered + if (outside_area(Key)) + return false; + auto &t{m_tiles[Key]}; + if (false == in_service_area(Key.first, Key.second)) + t.empty = true; + if (t.empty) + return false; + auto const level{first_level(t, level_for(Distance, m_config.hires))}; + t.retry_at = 0.0; + if (t.level == level && t.alpha == m_alpha) + return false; // already shown as it should be + if (false == (t.requested == level && t.requested_alpha == m_alpha)) + schedule(Key, t, level, m_alpha); + return true; +} + +std::size_t editor_orthophoto::hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera) +{ + if (false == m_enabled) + return 0; + // the tile of the camera as it is now: it isn't followed while the layer is off + m_camera_tile = camera_tile(Camera); + { + std::lock_guard lock(m_mutex); + m_focus = m_camera_tile; + } + auto const a{camera_tile(glm::dvec3{Min.x, 0.0, Min.y})}; + auto const b{camera_tile(glm::dvec3{Max.x, 0.0, Max.y})}; + tile_key const first{std::min(a.first, b.first), std::min(a.second, b.second)}; + tile_key const last{std::max(a.first, b.first), std::max(a.second, b.second)}; + auto const centre{m_camera_tile}; + int const radius = m_config.radius; + std::vector keys; + for (int y = first.second; y <= last.second; ++y) + for (int x = first.first; x <= last.first; ++x) + { + tile_key const key{x, y}; + auto const distance{std::max(std::abs(x - centre.first), std::abs(y - centre.second))}; + if (distance <= radius && hurry_tile(key, distance)) + keys.push_back(key); + } + auto const count{keys.size()}; + { + std::lock_guard lock(m_mutex); + m_urgent.clear(); + m_urgent.insert(keys.begin(), keys.end()); + } + m_wakeup.notify_all(); + return count; +} diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index d6fd43f8d..b56052e7e 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -28,8 +28,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" // material_handle #include "rendering/geometrybank.h" // gfx::geometry_handle -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error); - namespace scene { class basic_region; @@ -102,6 +100,9 @@ class editor_orthophoto editor_orthophoto(editor_orthophoto const &) = delete; editor_orthophoto &operator=(editor_orthophoto const &) = delete; + // the tiles over a rectangle of the world (x, z; what the camera sees), within the reach around the camera, asked for before anything + // else, the ones which failed tried again at once. returns: how many were put at the front of the queue + std::size_t hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera); bool enabled() const { return m_enabled; } // disabling drops the queue and returns the gpu memory of the resident tiles void enabled(bool State); @@ -117,6 +118,10 @@ class editor_orthophoto // the heights the ground will have where there's none yet, as of the terrain model on its way: a tile laid out before its // ground comes lies there, or level with the tiles beside, rather than at the height of the layer far below or above void guess_source(height_query Query) { m_guess = std::move(Query); } + // true while the ground under an XZ rectangle (Min/Max are x,z) is still to come. A new tile there waits for it, rather than + // being laid out at the height of the layer; elsewhere it lies on whatever ground there is, or on the guess, as without it + using coming_query = std::function; + void coming_source(coming_query Query) { m_coming = std::move(Query); } // the area the imagery is downloaded in, a polygon of PUWG 1992 (easting, northing): its tiles go to the disk cache in the // background, the products the settings ask for, and no tile outside it is asked for around the camera. Empty: no area, the // tiles around the camera as before @@ -176,7 +181,8 @@ class editor_orthophoto bool puwg{false}; std::string error; }; - static service_info describe(std::string const &Service); + // Stop: true to give the reading up + static service_info describe(std::string const &Service, std::function const &Stop = {}); static std::string cache_directory(); private: @@ -236,6 +242,9 @@ class editor_orthophoto float height_max{0.0f}; std::vector surface; // upward facing ground triangles clipped to the tile (3 vertices each) bool guessed{false}; // no ground under it when sampled: the heights guessed, from the terrain model or the tiles beside + // the points of the grid of the heights the ground didn't answer when sampled (rows north->south, as heights): filled from + // the points beside or guessed, and sampled again once the ground comes under one of them + std::vector unanswered; // scene geometry scene::basic_section *section{nullptr}; // section holding the shape (nullptr = not in the scene) scene::basic_cell *cell{nullptr}; // set instead of the section's shape list when the shape is translucent @@ -245,6 +254,12 @@ class editor_orthophoto }; static int level_for(int Distance, bool Hires); + // the level a tile is asked for at first: a tile showing nothing yet takes the standard image before the 4K one + static int first_level(tile const &Tile, int Level); + // the tile is outside the download area set, which then has no imagery asked for it + bool outside_area(tile_key const &Key) const; + // a tile of the view hurried: put at the front of the queue unless it's shown as it should be. true: counted among the hurried + bool hurry_tile(tile_key const &Key, int Distance); tile_key camera_tile(glm::dvec3 const &Camera) const; glm::dvec2 tile_corner(tile_key const &Key) const; // world (x,z) of the north-west corner void schedule(tile_key const &Key, tile &Tile, int Level, std::uint8_t Alpha); @@ -253,6 +268,10 @@ class editor_orthophoto void release_tile(tile &Tile); texture_slot acquire_slot(); void sample_ground(tile_key const &Key, tile &Tile); + // the ground has come under a point of the tile which had none when it was sampled + bool ground_came(tile_key const &Key, tile const &Tile) const; + // a new tile isn't asked for yet: the ground under it is still to come + bool waits_for_ground(tile_key const &Key) const; // the height of the ground sampled under a tile beside Own at the point, the tiles with guessed heights left out bool sampled_height(tile_key const &Own, double const X, double const Z, float &Height) const; void build_shape(tile_key const &Key, tile &Tile); @@ -272,6 +291,7 @@ class editor_orthophoto ground_query m_ground; height_query m_height; height_query m_guess; + coming_query m_coming; scene::basic_region *m_region{nullptr}; // region the scene geometry was put into std::multimap m_free_chunks; // geometry chunks by capacity, reused between tiles // the scene opacity is baked into the textures, which means reading the tiles again; applied once the value settles @@ -300,6 +320,7 @@ class editor_orthophoto bool m_prefetch_paused{false}; source m_prefetch_source; std::uint32_t m_prefetch_generation{0}; + std::set m_urgent; // asked for by hurry(): workers take these first; guarded by m_mutex std::atomic m_stop{false}; std::atomic m_generation{1}; diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index c7e162c46..dd475b183 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -198,6 +198,18 @@ bool editorSettings::load() layer.terms = fields[5]; m_wms_layers.push_back(layer); } + else if (key == "camera_speed") + { + parse(value, m_camera.speed); + m_camera.speed = std::clamp(m_camera.speed, 0.05, 10.0); + } + else if (key == "camera_fast") + { + parse(value, m_camera.fast); + m_camera.fast = std::clamp(m_camera.fast, 1.0, 30.0); + } + else if (key == "camera_zoomed") + m_camera.zoomed = (value == "1"); else if (key.rfind(origin_prefix, 0) == 0) { // northing;easting @@ -269,6 +281,9 @@ bool editorSettings::save() stream << "laying_heights " << (m_heights == lay_heights::points ? "points" : m_heights == lay_heights::level ? "level" : "fitted") << "\n"; for (auto const &layer : m_wms_layers) stream << "wms_layer " << (layer.visible ? 1 : 0) << ";" << layer.opacity << ";" << encoded(layer.url) << ";" << encoded(layer.layers) << ";" << encoded(layer.title) << ";" << encoded(layer.terms) << "\n"; + stream << "camera_speed " << m_camera.speed << "\n"; + stream << "camera_fast " << m_camera.fast << "\n"; + stream << "camera_zoomed " << (m_camera.zoomed ? 1 : 0) << "\n"; stream << std::fixed << std::setprecision(3); for (auto const &origin : m_orthophoto_origins) stream << origin.first << " " << origin.second.first << ";" << origin.second.second << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index 548f12b61..5223fca51 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -119,10 +119,19 @@ public: }; lay_heights heights() const { return m_heights; } void heights(lay_heights Heights) { m_heights = Heights; } + // the free camera: its speed, how many times faster Ctrl makes it, and in the top view as fast as the view is zoomed + struct camera_settings + { + double speed{1.0}; + double fast{30.0}; + bool zoomed{false}; // off as the editor was before: "As it was" means it + }; + camera_settings &camera() { return m_camera; } private: movement_scheme m_movement{movement_scheme::wsad}; orthophoto_settings m_orthophoto; + camera_settings m_camera; std::map> m_orthophoto_origins; std::vector m_wms_layers; double m_platform_edge{1.725}; diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a681b1a9e..9c00017de 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include terrain_streamer EditorTerrain; @@ -907,6 +908,44 @@ bool terrain_streamer::owns(gfx::geometry_handle const &Geometry) const return false; } +bool terrain_streamer::in_walk(chunk_key const &Key) const +{ + // the circle update() walks around the camera and around where it's heading + auto const within = [this, &Key](chunk_key const &Centre) { + auto const dx{Key.first - Centre.first}; + auto const dz{Key.second - Centre.second}; + return std::abs(dx) <= m_walkradius && std::abs(dz) <= m_walkradius && dx * dx + dz * dz <= (m_walkradius + 1) * (m_walkradius + 1); + }; + return within(m_walkhere) || within(m_walkthere); +} + +bool terrain_streamer::chunk_coming(chunk_key const &Key) const +{ + if (m_chunks.contains(Key) || m_removed.contains(Key)) + return false; + if (m_loading.contains(Key)) + return true; + // a chunk the walk doesn't reach at this distance isn't loaded, so it isn't waited for: it's taken in when the camera comes near + if (false == in_walk(Key)) + return false; + // still to come while its pack isn't read yet, or it's in its pack; not there where the pack is read without it + auto const pack{m_packs.find(heightmap::pack_of(Key))}; + if (pack == m_packs.end() || pack->second.status == pack_state::state::unknown || pack->second.status == pack_state::state::loading) + return true; + return pack->second.status == pack_state::state::ready && pack->second.file->has(Key); +} + +bool terrain_streamer::ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const first{heightmap::chunk_at(Low.x, Low.y)}; + auto const last{heightmap::chunk_at(High.x, High.y)}; + for (auto z{std::min(first.second, last.second)}; z <= std::max(first.second, last.second); ++z) + for (auto x{std::min(first.first, last.first)}; x <= std::max(first.first, last.first); ++x) + if (chunk_coming(chunk_key{x, z})) + return true; + return false; +} + bool terrain_streamer::exists(chunk_key const &Key) const { if (m_chunks.count(Key) > 0) diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index cf8407ac1..760335a75 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -81,6 +81,10 @@ class terrain_streamer std::string stats() const; // chunks in the pack files and in memory, less the removed ones; the files known so far bool exists(chunk_key const &Key) const; + // true while a chunk over an XZ rectangle (Low/High are x,z) is still to come at this distance of the camera: being loaded, or + // within the walk around the camera and in its pack or with its pack not read yet. False where all of them are in memory, where + // none is nor will be, and where the walk doesn't reach + bool ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const; // editing; the chunks changed are written to the files by save() heightmap::manifest const &manifest() const { return m_manifest; } @@ -235,6 +239,11 @@ class terrain_streamer scene::basic_cell *cell{nullptr}; }; + // within the circle of chunks the last walk of update() asked for + bool in_walk(chunk_key const &Key) const; + // the chunk is still to come at this distance of the camera (see ground_coming) + bool chunk_coming(chunk_key const &Key) const; + void start_workers(); void stop_workers(); void worker(); diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index ce123829f..f5b4d29a5 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -21,6 +21,19 @@ struct ITexture virtual void set_components_hint(int hint) = 0; virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) = 0; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; + // uploads an image from a thread with a gl context of its own, sharing the objects with the drawing one. a texture that + // can keeps the image apart until commit_thread_upload(), called on the drawing thread, puts it in place + virtual void upload_from_thread(size_t width, size_t height, const uint8_t *data) + { + update_from_memory(width, height, data); + } + // puts in place the image of the last upload_from_thread() once the gpu has it, without waiting for it. called on the + // drawing thread; false while the upload isn't done yet, to be asked again later + virtual bool commit_thread_upload() + { + // the image went in place right away + return true; + } static ITexture *null_texture() { struct NullTexture : public ITexture diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4a5bc4759..6484fdd75 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14023,6 +14023,36 @@ msgstr "PPM wciśnięty, W / S" msgid "RMB held, A / D" msgstr "PPM wciśnięty, A / D" +msgid "%zu drive with no switch" +msgid_plural "%zu drives with no switch" +msgstr[0] "%zu napęd bez zwrotnicy" +msgstr[1] "%zu napędy bez zwrotnicy" +msgstr[2] "%zu napędów bez zwrotnicy" + +msgid "Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name" +msgstr "Napędy ustawione na zwrotnicę, której w scenerii nie ma: zostały po zwrotnicy usuniętej lub przemianowanej ręcznie albo we wcześniejszym edytorze, ich eventy niczego nie przestawiają.\nKliknięcie przenosi do napędu i go zaznacza, Delete go usuwa; można też nadać jakiejś zwrotnicy jego nazwę" + +msgid "%s: no switch of this name" +msgstr "%s: brak zwrotnicy o tej nazwie" + +msgid "%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view" +msgid_plural "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view" +msgstr[0] "%zu napęd nie ma zwrotnicy o swojej nazwie: jest na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[1] "%zu napędy nie mają zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[2] "%zu napędów nie ma zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" + +msgid "The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is" +msgstr "Napęd %s nie ma opisu dla edytora: może też ustawiać prędkość albo nieść podsypkę zwrotnicy, więc zostaje bez zmian" + +msgid "The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew" +msgstr "Rozjazd krzyżowy ma napęd %s bez opisu dla edytora, który może też ustawiać prędkość albo nieść jego podsypkę: nie zostanie ułożony od nowa" + +msgid "Switch %s keeps its drive %s, which isn't described for the editor" +msgstr "Zwrotnica %s zostaje przy swoim napędzie %s, który nie ma opisu dla edytora" + +msgid "A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted" +msgstr "Napęd bez opisu dla edytora, np. rozjazdu krzyżowego, który może też ustawiać prędkość albo nieść podsypkę zwrotnicy: edytor go nie zmienia, zostaje na miejscu, gdy zwrotnica się przesuwa, i znika razem z ostatnią zwrotnicą, którą przestawia" + # the wizard of a new scenery: the range of the aerial photos, given on the map and changed in the editor msgid "A fictional scenery needs no place on the map" @@ -14236,3 +14266,39 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" + +msgid "Camera speed" +msgstr "Prędkość kamery" + +msgid "Speed of the camera" +msgstr "Prędkość kamery" + +msgid "How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was" +msgstr "Jak szybko strzałki albo WSAD przesuwają kamerę, z Shiftem trochę szybciej; 1 = jak dotąd" + +msgid "Ctrl speeds it up" +msgstr "Przyspieszenie z Ctrl" + +msgid "How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was" +msgstr "Ile razy szybciej jedzie kamera z wciśniętym Ctrl, także Ctrl+Shift; 30 = jak dotąd" + +msgid "In the top view as fast as the view is zoomed" +msgstr "W widoku z góry prędkość zależna od powiększenia" + +msgid "Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom" +msgstr "Przybliżona mapa jedzie wolno, oddalona szybko: po ekranie zawsze w tym samym tempie" + +msgid "As it was" +msgstr "Przywróć domyślne" + +msgid "Orthophoto on (~)" +msgstr "Ortofoto włączone (~)" + +msgid "Orthophoto off (~)" +msgstr "Ortofoto wyłączone (~)" + +msgid "Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)" +msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" + +msgid "Orthophoto: the view is all shown already (Ctrl+~)" +msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 23af295e4..757ccd2b8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -597,6 +597,10 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { if( Framestamp == m_framestamp ) { return; } auto const timedelta { Timer::GetDeltaTime() }; + // the opacities change step by step from where they are, and they start at 1. the first time the instance is + // drawn its lights take their current state at once, whether it came from the definition or from an event since: + // a fade from 1 showed a light that is off as lit for a moment, the first time it came into view + bool const transition { m_transition && m_lightsanimated }; // interpretacja ułamka zależnie od typu // case ls_Off: ustalenie czasu migotania, t<1s (f>1Hz), np. 0.1 => t=0.1 (f=10Hz) @@ -637,12 +641,13 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { const float transitionontime = std::min(0.25f, std::min(ontime, offtime) * 0.95f); const float transitionofftime = std::min(0.45f, std::min(ontime, offtime) * 0.95f); if (on) - opacity += m_transition ? timedelta / transitionontime : 1.f; // increase to max value + opacity = static_cast( opacity + ( transition ? timedelta / transitionontime : 1.0 ) ); // increase to max value else - opacity -= m_transition ? timedelta / transitionofftime : 1.f; // reduce to zero + opacity = static_cast( opacity - ( transition ? timedelta / transitionofftime : 1.0 ) ); // reduce to zero // Clamp the opacity opacity = std::clamp(opacity, 0.f, 1.f); } + m_lightsanimated = true; // Ra 2F1I: to by można pomijać dla modeli bez animacji, których jest większość for (const auto entry : m_animlist) { diff --git a/model/AnimModel.h b/model/AnimModel.h index e5a6841b6..7cf50fa44 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -225,6 +225,7 @@ public: float fOffTime { 1.f / 2 };// { 60.f / 45.f / 2 }; // były stałymi, teraz mogą być zmienne dla każdego egzemplarza // float fTransitionTime { fOnTime * 0.9f }; // time bool m_transition { true }; // smooth transition between light states + bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame // true if this instance is eligible for the batched/instanced render path: diff --git a/model/Texture.cpp b/model/Texture.cpp index 9b428202b..bba3ba763 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -323,6 +324,7 @@ GLint readback_format( GLint const Internalformat ) { std::array opengl_texture::units = { 0 }; GLint opengl_texture::m_activeunit = -1; +std::atomic opengl_texture::m_unitcachestale { false }; std::unordered_map opengl_texture::precompressed_formats = { @@ -729,9 +731,104 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 is_static = true; is_ready = true; } - // the name may be a new one, and the unit active took the texture past the unit cache + // the name may be a new one, and the unit active took the texture past the unit cache. this runs on the python upload + // thread too (python.threadedupload), so the cache is only marked here: clearing it outright raced the drawing thread + // filling it for a multi-bind, and an object got the texture of the one drawn before it for a frame + invalidate_unit_cache(); +} + +namespace +{ +// gl objects of an image uploaded by another thread that was never put in place +void delete_thread_upload(GLuint const Texture, GLsync const Fence) +{ + if (Fence != nullptr) + glDeleteSync(Fence); + glDeleteTextures(1, &Texture); +} +} // namespace + +void opengl_texture::upload_from_thread(size_t width, size_t height, const uint8_t *raw) +{ + // a texture of its own each time: the one drawn from may be in use by the gpu for the drawing context, and writing it from + // here, with nothing to order the two contexts, could leave it incomplete or half written for a frame + texture_thread_upload upload; + upload.width = width; + upload.height = height; + glGenTextures(1, &upload.id); + glBindTexture(target, upload.id); + set_filtering(); + glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap_mode_s); + glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap_mode_t); + if (!glGenerateMipmap) + glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); + glTexImage2D(target, 0, GL_SRGB8_ALPHA8, static_cast(width), static_cast(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, raw); + if (glGenerateMipmap) + glGenerateMipmap(target); + glBindTexture(target, 0); + if (glFenceSync) + { + upload.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + } + if (upload.fence == nullptr) + { + // no sync objects, or no fence made: the drawing context can only be sure of the image once the upload is done + glFinish(); + } + else + { + // the drawing context asks for the fence, which signals only once it is on its way to the gpu + glFlush(); + } + + std::optional superseded; + { + std::scoped_lock lock{m_threaduploadmutex}; + superseded = std::exchange(m_threadupload, upload); + } + if (superseded.has_value()) + { + // the drawing thread didn't take it, so nothing drew from it + delete_thread_upload(superseded->id, superseded->fence); + } +} + +bool opengl_texture::commit_thread_upload() +{ + texture_thread_upload upload; + { + std::scoped_lock lock{m_threaduploadmutex}; + if (false == m_threadupload.has_value()) + return true; + // asked without waiting. the image goes in place only once the upload is done, so every context binding it after + // has it whole: the extra viewports and the windows of python.displaywindows draw in contexts of their own + if (m_threadupload->fence != nullptr) + { + // a failed query (GL_WAIT_FAILED) isn't asked again: the image would never go in place + if (glClientWaitSync(m_threadupload->fence, 0, 0) == GL_TIMEOUT_EXPIRED) + return false; + glDeleteSync(m_threadupload->fence); + } + upload = *m_threadupload; + m_threadupload.reset(); + } + + if (id != invalid_id) + glDeleteTextures(1, &id); + id = upload.id; + data_width = static_cast(upload.width); + data_height = static_cast(upload.height); + data_format = GL_SRGB8_ALPHA8; + data_components = GL_RGBA; + if (type == "internalsrc:") + { + is_static = true; + is_ready = true; + } + // the name deleted may come back for another texture, and a deleted texture isn't bound any more for (auto &unit : units) unit = -1; + return true; } void @@ -1263,6 +1360,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; if (GLAD_GL_ARB_direct_state_access) @@ -1630,6 +1728,25 @@ opengl_texture::reset_unit_cache() { m_activeunit = -1; } +void +opengl_texture::invalidate_unit_cache() { + + m_unitcachestale.store( true ); +} + +void +opengl_texture::sync_unit_cache() { + + // a plain load first: bind() calls this for every texture, and a read-modify-write each time would cost more + if( ( false == m_unitcachestale.load() ) + || ( false == m_unitcachestale.exchange( false ) ) ) { + return; + } + for( auto &unit : units ) { + unit = -1; + } +} + void opengl_texture::set_filtering() const { diff --git a/model/Texture.h b/model/Texture.h index 20221fcea..3934565a5 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,8 +9,11 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include +#include +#include #include "winheaders.h" #include #include "model/ResourceManager.h" @@ -19,6 +22,14 @@ http://mozilla.org/MPL/2.0/. struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming +// an image uploaded by another thread into a texture of its own, waiting for the drawing thread to put it in place +struct texture_thread_upload { + GLuint id { 0 }; + GLsync fence { nullptr }; // set after the upload in the uploading context; none where the driver has no sync objects + size_t width { 0 }; + size_t height { 0 }; +}; + struct opengl_texture : public ITexture { static DDSURFACEDESC2 deserialize_ddsd(std::istream&); static DDCOLORKEY deserialize_ddck(std::istream&); @@ -47,6 +58,13 @@ struct opengl_texture : public ITexture { set_components_hint( GLint hint ) override; static void reset_unit_cache(); + // marks the unit cache as not to be trusted. safe to call from any thread: the cache itself is + // cleared by the thread drawing with it, the next time it binds textures (sync_unit_cache) + static void + invalidate_unit_cache(); + // clears the unit cache if a thread marked it as not to be trusted since. called before the cache is read + static void + sync_unit_cache(); virtual int get_width() const override { return data_width; } @@ -85,6 +103,10 @@ struct opengl_texture : public ITexture { virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override; + // the image goes into a texture of its own, and the drawing thread swaps it in after the gpu has it (commit_thread_upload). + // the texture drawn from is never written by the uploading thread + void upload_from_thread(size_t width, size_t height, const uint8_t *data) override; + bool commit_thread_upload() override; // members static constexpr GLuint invalid_id { std::numeric_limits::max() }; // id value of texture without GL resource @@ -100,6 +122,11 @@ struct opengl_texture : public ITexture { GLenum target = GL_TEXTURE_2D; static std::array units; static GLint m_activeunit; + // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread + static std::atomic m_unitcachestale; + + std::mutex m_threaduploadmutex; + std::optional m_threadupload; // guarded by m_threaduploadmutex public: // methods diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..3a3008a44 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2457,6 +2457,8 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel if (GLAD_GL_ARB_multi_bind) { + // the cache may have been marked stale by the python upload thread + opengl_texture::sync_unit_cache(); GLuint lastdiff = 0; size_t i; for (i = 0; i < gl::MAX_TEXTURES; i++) @@ -4338,7 +4340,7 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) }; if( Lightlevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place - light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * std::clamp( 1.25f - (float)luminance, 0.f, 1.f ) ); + light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ); light_ubo->update( light_ubs ); } diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 3b8de9469..706e5d871 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -65,7 +65,9 @@ opengl_particles::update( opengl_camera const &Camera ) { vertex.color[ 0 ] = static_cast( particlecolor.r ); vertex.color[ 1 ] = static_cast( particlecolor.g ); vertex.color[ 2 ] = static_cast( particlecolor.b ); - vertex.color[ 3 ] = static_cast( std::clamp( particle.opacity * 255, 0.f, 255.f ) ); + // as up to 26.05.1, when clamp made the alpha a byte before clamping it: an opacity over 1 wraps + // round. through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion + vertex.color[ 3 ] = static_cast( static_cast( particle.opacity * 255 ) ); auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 5083c6f2f..8bef3352d 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -4370,8 +4370,8 @@ glm::dvec3 opengl_renderer::Update_Mouse_Position() { glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size; - mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 ); - mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); + mousepos.x = safe_clamp( mousepos.x, 0, Global.fb_size.x - 1 ); + mousepos.y = safe_clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); GLfloat pointdepth; ::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth ); diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 8ccb728dd..517fec751 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -168,9 +168,9 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { if( m_ownertype == owner_type::vehicle ) { auto const &mover { *m_owner.vehicle->MoverParameters }; - if( Global.AirTemperature <= 5.f || mover.dizel_heat.Ts < 45.f ) { - m_emitter.color = glm::vec3{ 128, 128, 128 }; - } + // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant + // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the + // emitter colour, so the smoke turned pure white, glowing at night, and never changed back // a vehicle taken off the tracks (gone through a portal, or waiting in the pool of the road traffic) puffs no more, // the particles it already let out fade away as usual m_spawncount = ( diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fac540019..b95b310d8 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -142,18 +142,24 @@ void render_task::run() } else { - std::lock_guard guard(m_target->mutex); + // the lock may be held by the drawing thread for a whole upload: waited for without the gil. the bytes stay + // valid without it, the object is immutable and held by its reference here + Py_BEGIN_ALLOW_THREADS + { + std::scoped_lock guard(m_target->mutex); - if (m_target->image.size() != expectedBytes) - m_target->image.resize(expectedBytes); + if (m_target->image.size() != expectedBytes) + m_target->image.resize(expectedBytes); - std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); + std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); - m_target->width = screenWidth; - m_target->height = screenHeight; - m_target->components = glComponents; - m_target->format = glFormat; - m_target->timestamp = std::chrono::high_resolution_clock::now(); + m_target->width = screenWidth; + m_target->height = screenHeight; + m_target->components = glComponents; + m_target->format = glFormat; + m_target->timestamp = std::chrono::high_resolution_clock::now(); + } + Py_END_ALLOW_THREADS } } @@ -232,6 +238,35 @@ void render_task::upload() const } } +void render_task::upload_from_thread() +{ + m_uploadedbyworker = true; + if (Global.python_uploadmain && m_target && m_target->shared_tex) + { + m_target->shared_tex->upload_from_thread(m_target->width, m_target->height, reinterpret_cast(m_target->image.data())); + } +} + +bool render_task::finish_upload() const +{ + if (false == Global.python_uploadmain || nullptr == m_target || nullptr == m_target->shared_tex) + return true; + // the old texture is deleted and the new name published under the lock the windows of python.displaywindows bind under, + // so none of them binds the old name once it is gone: a name bound before stays alive in its context while bound there + std::scoped_lock lock(m_target->mutex); + if (m_uploadedbyworker) + { + if (false == m_target->shared_tex->commit_thread_upload()) + return false; + } + else + { + upload(); + } + m_target->texture_id = m_target->shared_tex->get_id(); + return true; +} + void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success @@ -569,9 +604,11 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo // execute python code task->run(); if (Context) - task->upload(); - else { + task->upload_from_thread(); + } + { + // the drawing thread uploads the image, or puts in place the one uploaded here std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } @@ -609,10 +646,8 @@ void python_taskqueue::update() { std::scoped_lock lock(m_uploadtasks.mutex); - for (auto const &task : m_uploadtasks.data) - task->upload(); - - m_uploadtasks.data.clear(); + // a task whose image a worker uploaded stays until the gpu has the image + std::erase_if(m_uploadtasks.data, [](std::shared_ptr const &Task) { return Task->finish_upload(); }); } void python_taskqueue::error() diff --git a/scripting/PyInt.h b/scripting/PyInt.h index c8c410397..3259b418a 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -67,6 +67,9 @@ struct python_rt int width; int height; std::string image; + // gl name of the texture with the last image put in place, for the windows of python.displaywindows (0: none yet). the image + // uploaded by a worker gets a texture of its own, so the name changes with each one + size_t texture_id{0}; std::chrono::high_resolution_clock::time_point timestamp; }; @@ -80,7 +83,13 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); + // uploads the image on the drawing thread void upload() const; + // uploads the image on a worker with a gl context of its own (python.threadedupload); finish_upload() puts it in place + void upload_from_thread(); + // on the drawing thread: uploads the image, or puts in place the one a worker uploaded. false while the gpu hasn't got + // the latter yet, to be called again + bool finish_upload() const; void cancel() const; auto target() const -> std::shared_ptr { @@ -92,6 +101,8 @@ class render_task PyObject *m_renderer{nullptr}; std::shared_ptr m_input{nullptr}; std::shared_ptr m_target{nullptr}; + // set by upload_from_thread(); read by the drawing thread after the task was handed over under the lock of the queue + bool m_uploadedbyworker{false}; }; class python_taskqueue diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4da50151e..5a3491af7 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -30,7 +30,7 @@ void texture_window_cursor_pos(GLFWwindow *win, double x, double y) } python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) - : m_rt(rt), m_touchlist(touchlist) + : m_rt(rt), m_touchlist(touchlist), m_initialtexture(rt->shared_tex->get_id()) { for (const auto &viewport : Global.python_viewports) { @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); + bind_shared_texture(); } else { GLuint tex; @@ -146,6 +146,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -188,6 +190,16 @@ void python_screen_viewer::threadfunc() } } +void python_screen_viewer::bind_shared_texture() const +{ + // bound each frame: each image uploaded by a worker comes in a texture of its own, and a name deleted comes back for + // a later one, so a name seen before may be another texture already. bound under the lock the drawing thread deletes + // the old texture under, so the name read here is never one already gone + std::scoped_lock guard(m_rt->mutex); + size_t const texture = m_rt->texture_id; + glBindTexture(GL_TEXTURE_2D, static_cast(texture != 0 ? texture : m_initialtexture)); +} + void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { for (auto const &conf : m_windows) { diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index ccd78f0ef..41b52a7e2 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -31,8 +31,12 @@ class python_screen_viewer gl::scene_ubs m_ubs; std::atomic_bool m_exit = false; + // the texture of the screen when the viewer was made, read on the drawing thread: shown until an image is put in place + size_t m_initialtexture{0}; void threadfunc(); + // with python.sharectx, binds the texture with the last image of the screen, in the context of the window made current + void bind_shared_texture() const; public: python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 9e979e2ca..5b224b666 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -247,10 +247,9 @@ void blackbox_recorder::update(double const Deltatime) { std::scoped_lock lock{m_mutex}; m_time += Deltatime; - // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a - // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with - // a recording which couldn't be made - if (m_time >= m_tapedue) { + // with the physics logs on, each driver writes its own all the time. the tapes are files of their own: they go on + // after the recording ends in the editor, and with a recording which couldn't be made + if (false == WriteLogFlag && m_time >= m_tapedue) { keep_tape_line(); m_tapedue = std::max(m_tapedue + tapeinterval, m_time); } @@ -510,13 +509,10 @@ void blackbox_recorder::keep_tape_line() { auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; if (driver == nullptr) return; - auto const &name{driver->physicslog_name()}; - // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has - // no time for, on a hard disk with hundreds of them - PhysicsLogs.put_first(name); // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice if (driver->writes_physicslog()) return; + auto const &name{driver->physicslog_name()}; if (m_tapes.insert(name).second) { PhysicsLogs.begin(name, TController::physicslog_header()); WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 18ee052c4..a3aaf5d0f 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -88,9 +88,8 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); - // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road - // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would - // have it. a driver's log is begun at the first line given for that driver, and goes on + // with the physics logs off, the line of the log of the driver the user is with, to its log, physicslog/.dat, + // as the physics logs would have it. a driver's log is begun at the first line given for that driver, and goes on // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..4e8c0e5f7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -26,11 +26,12 @@ namespace { float turbidity_of( float const Overcast ) { + if( Overcast <= 0.10 ) { return 3.f; } if( Overcast <= 0.20 ) { return 4.f; } - if( Overcast <= 0.40 ) { return 5.f; } - if( Overcast <= 0.60 ) { return 6.f; } - if( Overcast <= 0.70 ) { return 7.f; } - if( Overcast <= 0.80 ) { return 8.f; } + if( Overcast <= 0.60 ) { return 5.f; } + if( Overcast <= 0.70 ) { return 6.f; } + if( Overcast <= 0.80 ) { return 7.f; } + if( Overcast <= 0.90 ) { return 8.f; } return 9.f; } diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 2efa57291..d32fd0e72 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -17,7 +17,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "utilities/utilities.h" -#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -46,15 +45,6 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } -// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of -// the other drivers: the closing at the end of the run drops those it has no time for -void put_physicslog_first(TDynamicObject const &Vehicle) -{ - auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; - if (driver != nullptr) - PhysicsLogs.put_first(driver->physicslog_name()); -} - } // namespace namespace simulation { @@ -135,13 +125,11 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - auto const *vehicle { simulation::Vehicles.find(name) }; - if (vehicle == nullptr) + if (simulation::Vehicles.find(name) == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } - put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index e24db024f..d06c83445 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -32,6 +32,8 @@ add_executable(${UNIT_TESTS_NAME} # and the fouling points of the switches, widened in the curves as the gauge is "${CMAKE_SOURCE_DIR}/editor/editorGauge.cpp" "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" + # and the http client the editor fetches its aids with + "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp new file mode 100644 index 000000000..7102d06e0 --- /dev/null +++ b/tests/unit/test_braking_curve.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakingcurve.h" + +#include +#include + +// the deceleration the AI asks for on its way down to a stop or a lower speed ahead, outside of the final approach +// (TController::adjust_desired_speed_for_braking_curve). in shunting the brake table of the consist isn't worked out +// and stays at zero; planned from it, the curve asked for next to no braking, and shunting engines ran through the +// signals they were to stop at. + +namespace { + +auto constexpr tablesize{20}; +using brake_values = std::array; + +// what the AI holds in shunting: nothing worked out +struct zeroed_table { + brake_values a0{}; + brake_values a1{}; + + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 100.0}; } +}; + +// a train brake that gives the same deceleration at every speed, full service 0.05 + 12 * 0.1 = 1.25 m/s2 +struct flat_table { + brake_values a0{}; + brake_values a1{}; + + flat_table() { + a0.fill(0.05); + a1.fill(0.1); + } + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 120.0}; } +}; + +braking_curve::approach stop_at(double const Speed, double const Distance) { + braking_curve::approach approach{}; + approach.speed = Speed; + approach.target = 0.0; + approach.distance = Distance; + approach.offset = 0.0; // the braking point of a stop, outside of a train, is the stop itself (VelNext * multiplier) + approach.speedup_horizon = 30.0 / 3.6; + approach.fill_horizon = 30.0 / 3.6; + return approach; +} + +// the AI in shunting leaves the brake alone for a demand weaker than this (TController::fAccThreshold) +auto constexpr shunting_brake_threshold{-0.2}; + +struct shunting_run { + double speed; // [km/h] + double left; // to the stop point [m] + bool braked_at_once; +}; + +// a shunting engine braking to a stop point the way the AI drives it: the brake follows the demand once it is past +// the threshold, the engine coasts otherwise. the braking curve gives way near the point to the final approach, at +// walking pace (10 km/h, 5 km/h in the last 10 m) +shunting_run brake_to_point(double const Speed, double const Distance, zeroed_table const &Table) { + auto const table{Table.table()}; + auto const timestep{0.1}; + shunting_run run{Speed, Distance, false}; + run.braked_at_once = braking_curve::demand(stop_at(run.speed, run.left), &table) < shunting_brake_threshold; + while ((run.speed > (run.left > 10.0 ? 10.0 : 5.0)) && (run.left > -50.0)) { + auto const demand{braking_curve::demand(stop_at(run.speed, run.left), &table)}; + auto const acceleration{demand < shunting_brake_threshold ? demand : 0.0}; + run.speed = std::max(0.0, run.speed + 3.6 * acceleration * timestep); + run.left -= run.speed / 3.6 * timestep; + } + return run; +} + +} // namespace + +TEST_CASE("braking curve: a brake table left at zero isn't known, one worked out is") { + CHECK_FALSE(zeroed_table{}.table().known()); + CHECK(flat_table{}.table().known()); +} + +TEST_CASE("braking curve: shunting to a point asks for the constant deceleration over the distance left") { + zeroed_table const shunting; + auto const table{shunting.table()}; + auto approach{stop_at(33.0, 186.0)}; + SUBCASE("coasting") { approach.acceleration = 0.0; } + SUBCASE("still speeding up") { approach.acceleration = 0.2; } + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(-33.0 * 33.0 / (25.92 * 186.0 + 0.1))); + CHECK(demand == doctest::Approx(braking_curve::demand(approach, nullptr))); + // enough for the AI to put the brake on + CHECK(demand < shunting_brake_threshold); +} + +TEST_CASE("braking curve: a shunting engine braking to a point gets down to walking pace short of it") { + zeroed_table const shunting; + auto speed{0.0}; + auto distance{0.0}; + SUBCASE("33 km/h, 186 m") { + speed = 33.0; + distance = 186.0; + } + SUBCASE("40 km/h, 186 m") { + speed = 40.0; + distance = 186.0; + } + SUBCASE("33 km/h, 120 m") { + speed = 33.0; + distance = 120.0; + } + SUBCASE("25 km/h, 60 m") { + speed = 25.0; + distance = 60.0; + } + CAPTURE(speed); + CAPTURE(distance); + + auto const run{brake_to_point(speed, distance, shunting)}; + + CHECK(run.braked_at_once); + CHECK(run.left > 0.0); + CHECK(run.speed <= 10.0); +} + +TEST_CASE("braking curve: a train with a worked out brake table plans along the shape of its brake") { + flat_table const train; + auto const table{train.table()}; + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.fill_horizon = 6.0; + approach.speedup_horizon = 5.0; + + SUBCASE("before the brake is applied, the room it takes to fill is kept") { + auto const room{580.0 - 80.0 / 3.6 * 6.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, room + 0.1 / 25.92, 0.0, table))); + // with the same deceleration at every speed the shape is the constant deceleration over that room + CHECK(demand == doctest::Approx(-(80.0 / 3.6) * (80.0 / 3.6) / (2.0 * room)).epsilon(0.01)); + } + SUBCASE("once the brake is applied, the whole distance is used") { + approach.brake_applied = true; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, 580.0 + 0.1 / 25.92, 0.0, table))); + } + SUBCASE("still speeding up, it plans from the speed reached once the brake acts") { + approach.acceleration = 0.3; + auto const reached{80.0 + 3.6 * 5.0 * 0.3}; + auto const distance{600.0 - (80.0 + reached) * 0.5 / 3.6 * 5.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(reached, 0.0, distance - 20.0 + 0.1 / 25.92, 0.0, table))); + } +} + +TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { + // a table that grips harder as the train slows, on a gradient; the demands were worked out with the + // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) + brake_values a0{}; + brake_values a1{}; + for (auto i{1}; i <= tablesize; ++i) { + a0[i] = 0.12 - 0.003 * i; + a1[i] = 0.06 - 0.001 * i; + } + braking_curve::brake_table const table{a0.data(), a1.data(), tablesize, 120.0}; + REQUIRE(table.full_braking(80.0) == doctest::Approx(0.645)); + REQUIRE(table.full_braking(10.0) == doctest::Approx(0.825)); + + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.gravity = 0.1; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + auto expected{0.0}; + SUBCASE("downhill, coasting, the brake still to be applied") { expected = -0.4926656801067293; } + SUBCASE("downhill, the brake applied") { + approach.brake_applied = true; + expected = -0.37739905908238147; + } + SUBCASE("downhill, still speeding up") { + approach.acceleration = 0.3; + expected = -0.5330117415264249; + } + SUBCASE("uphill, down to 40 km/h") { + approach = stop_at(100.0, 900.0); + approach.target = 40.0; + approach.gravity = -0.08; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + expected = -0.40930710539221765; + } + + CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); +} diff --git a/tests/unit/test_crashsignals.cpp b/tests/unit/test_crashsignals.cpp new file mode 100644 index 000000000..4c4dd1e86 --- /dev/null +++ b/tests/unit/test_crashsignals.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/crashsignals.h" + +// the stack of a crash on Linux (utilities/crashsignals.h): written to the log and to the standard error, after which +// the signal ends the process as it always did. the crash happens in a child process, which the test watches +#if defined(__linux__) + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +std::string read_all(int const File) { + std::string text; + std::array buffer{}; + for (auto count{::read(File, buffer.data(), buffer.size())}; count > 0; count = ::read(File, buffer.data(), buffer.size())) + text.append(buffer.data(), static_cast(count)); + return text; +} + +std::string read_file(std::string const &Path) { + std::ifstream file{Path, std::ios::binary}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +// the child: the report goes to the pipe in place of the standard error, no core dump is left behind +[[noreturn]] void crash_in_child(std::array const &Pipe, std::string const &Log) { + // a child stuck before the crash (a lock some other thread held at the fork) ends anyway, and the test with it + alarm(10); + dup2(Pipe[1], STDERR_FILENO); + close(Pipe[0]); + close(Pipe[1]); + rlimit const nocore{0, 0}; + setrlimit(RLIMIT_CORE, &nocore); + + crash_signals::install("test version 1.2"); + crash_signals::set_log_path(Log); + raise(SIGSEGV); + _exit(0); // not reached: the signal ends the child +} + +} // namespace + +TEST_CASE("crash signals: a crash writes its stack to the log and to the standard error, and still ends by its signal") { + test::scratch_folder const folder{"crash_signals"}; + auto const log{folder.write("log.txt", "the last line of the log\n")}; + + std::array pipe_ends{}; + REQUIRE(pipe(pipe_ends.data()) == 0); + auto const child{fork()}; + REQUIRE(child >= 0); + if (child == 0) + crash_in_child(pipe_ends, log); + + close(pipe_ends[1]); + auto const errors{read_all(pipe_ends[0])}; + close(pipe_ends[0]); + int status{0}; + REQUIRE(waitpid(child, &status, 0) == child); + + CAPTURE(errors); + // the process ends as it would without the handler + CHECK(WIFSIGNALED(status)); + CHECK(WTERMSIG(status) == SIGSEGV); + // the report on the standard error, which the starter shows + CHECK(errors.find("Crash: signal 11 (SIGSEGV) at address 0x") != std::string::npos); + CHECK(errors.find("Version: test version 1.2") != std::string::npos); + CHECK(errors.find("Stack (addr2line") != std::string::npos); + // with the frames of the program that crashed + CHECK(errors.find("eu07_unit_tests") != std::string::npos); + // and the same at the end of the log, after what it held + auto const logtext{read_file(log)}; + CAPTURE(logtext); + CHECK(logtext.starts_with("the last line of the log\n")); + CHECK(logtext.find("Crash: signal 11 (SIGSEGV)") != std::string::npos); + CHECK(logtext.find("eu07_unit_tests") != std::string::npos); +} + +#endif diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp new file mode 100644 index 000000000..ffdfe9959 --- /dev/null +++ b/tests/unit/test_editor_http.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorHttp.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// a service on this machine. with no reply it takes the connection and the request and never answers, as geoportal.gov.pl +// does now and then +class local_server { + public: + explicit local_server(std::string Reply = {}) : + m_reply(std::move(Reply)) { + m_acceptor.open(asio::ip::tcp::v4()); + m_acceptor.bind({asio::ip::address_v4::loopback(), 0}); + m_acceptor.listen(); + m_port = m_acceptor.local_endpoint().port(); + m_thread = std::jthread{[this]() { serve(); }}; + } + ~local_server() { + m_done = true; + // a connection of its own wakes the server waiting for one + asio::ip::tcp::socket wake{m_context}; + asio::error_code ignored; + wake.connect({asio::ip::address_v4::loopback(), m_port}, ignored); + wake.close(ignored); + m_thread.join(); + } + local_server(local_server const &) = delete; + local_server &operator=(local_server const &) = delete; + + std::string url() const { + return std::format("http://127.0.0.1:{}/wcs?REQUEST=GetCapabilities", m_port); + } + + private: + void serve() { + while (false == m_done) { + asio::ip::tcp::socket socket{m_context}; + asio::error_code error; + m_acceptor.accept(socket, error); + if (error) + return; + if (false == m_reply.empty()) { + answer(socket); + continue; + } + // the request is left without an answer, the connection open, until the server goes + while (false == m_done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + // the reply once the whole request is read, then the connection closed + void answer(asio::ip::tcp::socket &Socket) const { + asio::error_code error; + asio::streambuf request; + asio::read_until(Socket, request, "\r\n\r\n", error); + if (!error) + asio::write(Socket, asio::buffer(m_reply), error); + Socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); + } + + std::string const m_reply; + asio::io_context m_context; + asio::ip::tcp::acceptor m_acceptor{m_context}; + unsigned short m_port{0}; + std::atomic m_done{false}; + std::jthread m_thread; +}; + +// the requests to the local server would go to a proxy named in the environment, which can't reach it +bool proxied() { + for (char const *variable : {"http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"}) { + if (char const *value{std::getenv(variable)}; value != nullptr && *value != '\0') + return true; + } + return false; +} + +} // namespace + +TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { + if (false == editor_http::available() || proxied()) + return; // a build with no http client, or a proxy in the way + local_server server; + auto const start{std::chrono::steady_clock::now()}; + auto const elapsed = [start]() { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); }; + editor_http::client client; + std::vector data; + std::string error; + // the stop comes while the client waits for the answer, long before any of its timeouts + auto const got{client.get(server.url(), data, error, [&elapsed]() { return elapsed() > 0.3; })}; + CHECK_FALSE(got); + CHECK_FALSE(error.empty()); + // the receive timeout is 20 s; the transfer ends within a moment of the stop (libcurl looks at it about once a second) + CHECK(elapsed() < 5.0); +} + +TEST_CASE("editor http: the whole body of a response is read") { + if (false == editor_http::available() || proxied()) + return; + std::string body(100000, '\0'); + for (std::size_t i = 0; i < body.size(); ++i) + body[i] = static_cast('a' + i % 26); + local_server server{std::format("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK(client.get(server.url(), data, error, []() { return false; })); + CHECK(error.empty()); + CHECK(std::string(data.begin(), data.end()) == body); +} + +TEST_CASE("editor http: the body of an error is kept with the status in the error") { + if (false == editor_http::available() || proxied()) + return; + // the terrain model service tells a place outside of its coverage in the body of an error + std::string const body{"outside requested coverage"}; + local_server server{std::format("HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get(server.url(), data, error, []() { return false; })); + CHECK(error == "HTTP 400"); + CHECK(std::string(data.begin(), data.end()) == body); +} diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index 32fadec03..7a341b4f1 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -7,14 +7,10 @@ #include #include #include -#include -#include #include #include #include #include -#include -#include // the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to @@ -126,18 +122,6 @@ TEST_CASE("physicslog: stopping writes what is kept at once, and what comes afte CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); } -TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { - log_folder folder{"closingwait"}; - { - physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.stop(); - // the writing of the stop, left behind, is waited for by the writer going - } - CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); -} - TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { log_folder folder{"failed"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -157,63 +141,6 @@ TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); } -TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { - log_folder folder{"failedvalues"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values second; - second.time = 0.10; - physicslog_values last; - last.time = 0.20; - std::filesystem::create_directories(folder.path() / "EU07-008.dat"); - logs.begin("EU07-008", header); - logs.append("EU07-008", first); - logs.flush(); - // given while the file can't be written: after the lines kept, as text and as values - logs.append("EU07-008", second); - logs.append("EU07-008", "text\r\n"); - logs.append("EU07-008", last); - logs.flush(); - CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); - - std::filesystem::remove(folder.path() / "EU07-008.dat"); - logs.flush(); - auto const text{folder.read("EU07-008")}; - CHECK(text.starts_with(std::string{header} + "0.0500 ")); - CHECK(text.find("\r\n0.1000 ") != std::string::npos); - CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); - CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); -} - -TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { - // the logs of a writing as the writer has them, by their names - std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; - std::vector *> order; - for (auto &log : taken) - order.push_back(&log); - physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); - std::vector names; - for (auto const *log : order) - names.push_back(log->first); - CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); -} - -TEST_CASE("physicslog: a log put first is written as the others are") { - log_folder folder{"first"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.put_first("SM42-002"); - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.begin("SM42-002", header); - logs.append("SM42-002", "0.0500 1.0000\r\n"); - logs.flush(); - CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); - CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); -} - TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { log_folder folder{"failedbegun"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -311,75 +238,3 @@ TEST_CASE("physicslog: what is kept is written when the writer goes") { } CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); } - -TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { - log_folder folder{"after"}; - std::filesystem::create_directories(folder.path()); - { - std::ofstream before{folder.path() / "SU45-001.dat"}; - before << "earlier run\n"; - } - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.append("SU45-001", "0.0500 0.0000\r\n"); - logs.flush(); - logs.append("SU45-001", "0.1000 0.0000\r\n"); - logs.flush(); - CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); -} - -TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { - using namespace std::chrono_literals; - using duration = std::chrono::steady_clock::duration; - // quick: the interval - CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); - CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); - // a third of the interval: still the interval - CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); - // longer: three times the writing, the disk busy with the logs a quarter of the time - CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); - // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still - CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); -} - -TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { - log_folder folder{"values"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values line; - line.time = 0.05; - line.wheelspeed = 1.23456; - line.acceleration = -0.5; - line.mainctrl = 3; - line.direction = 1; - line.command = "ShuntVelocity"; - line.value1 = 40.0; - // a float of the vehicle, widened as the stream widened it - line.enginetemperature = 50.1f; - line.vehiclespeed = 36.0; - logs.begin("SM31-001", header); - logs.append("SM31-001", line); - logs.flush(); - CHECK(folder.read("SM31-001") == std::string{header} + - "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " - "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); -} - -TEST_CASE("physicslog: lines given as values and as text are written in the order given") { - log_folder folder{"order"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values last; - last.time = 0.15; - logs.append("EP09-001", first); - logs.append("EP09-001", "text\r\n"); - logs.append("EP09-001", last); - logs.flush(); - auto const text{folder.read("EP09-001")}; - CHECK(text.starts_with("0.0500 ")); - CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); -} diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp index b55de1644..a97791a32 100644 --- a/tests/unit/test_track_uneven.cpp +++ b/tests/unit/test_track_uneven.cpp @@ -63,7 +63,8 @@ TEST_CASE("uneven track: the cab keeps what the ride on the track doesn't stand TEST_CASE("uneven track: measures as the Id-14 limits for its value") { // appendix 1, class C at 80 km/h: 18 mm vertically, 17 mm sideways, 16 mm of twist on 5 m, gauge +10/-8 mm, 20 mm of cross level, J = 5.3 - auto const amplitude{track_uneven::stray_per_mm * 18.0 * 1000.0}; // mm + auto const amplitude{track_uneven::stray_up_per_mm * 18.0 * 1000.0}; // mm + auto const sideways{track_uneven::stray_side_per_mm * 18.0 * 1000.0}; // mm double const gauge{1.435}; double const step{0.5}; int const steps{4000}; @@ -76,6 +77,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") double level{0.0}; double j{0.0}; double away{0.0}; + double aside{0.0}; for (int line = 0; line < lines; ++line) { auto const heading{glm::pi() * (line + 0.37) / lines}; @@ -85,6 +87,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") std::array, 2> up; std::array, 2> side; std::vector middle; + std::vector across_middle; for (int i = 0; i < steps; ++i) { auto const point{start + along * (i * step)}; @@ -93,9 +96,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") auto const sign{rail == 0 ? 1.0 : -1.0}; auto const stray{track_uneven::field(point + across * (sign * 0.5 * gauge))}; up[rail].push_back((stray.y - sign * 0.5 * track_uneven::level(point, across)) * amplitude); - side[rail].push_back(glm::dot(stray, across) * amplitude); + side[rail].push_back(glm::dot(stray, across) * sideways); } - middle.push_back(track_uneven::field(point).y * amplitude); + auto const centre{track_uneven::field(point)}; + middle.push_back(centre.y * amplitude); + across_middle.push_back(glm::dot(centre, across) * sideways); } std::vector verticals; std::vector horizontals; @@ -120,6 +125,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") wander += peak(gauges) / lines; level += peak(levels) / lines; away += peak(middle) / lines; + aside += peak(across_middle) / lines; j += (deviation(verticals) + deviation(horizontals) + deviation(twists) + 0.5 * deviation(gauges)) / 3.5 / lines; } CHECK(vertical == doctest::Approx(18.0).epsilon(0.1)); @@ -128,7 +134,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") CHECK(wander == doctest::Approx(10.0).epsilon(0.2)); CHECK(level == doctest::Approx(20.0).epsilon(0.1)); CHECK(j == doctest::Approx(5.3).epsilon(0.2)); - CHECK(away < 40.0); // the long waves go past the 15 mm off the survey marks of appendix 1a + // the long waves go past the 15 mm off the survey marks of appendix 1a: most of the height of a track spectrum is in them, the 10 m chord + // hardly sees them + CHECK(away < 60.0); + // and sideways: about 4.5 cm, which a platform edge or the panels of a level crossing laid on the design are off the rails by + CHECK(aside < 50.0); } TEST_CASE("uneven track: a place strays the same every time") @@ -136,11 +146,11 @@ TEST_CASE("uneven track: a place strays the same every time") // no random numbers: changing these changes how every uneven track in every scenery looks glm::dvec3 const place{1234.5, 0.0, -678.9}; auto const stray{track_uneven::field(place)}; - CHECK(stray.x == doctest::Approx(0.309777548158).epsilon(1e-9)); - CHECK(stray.y == doctest::Approx(0.311350299745).epsilon(1e-9)); - CHECK(stray.z == doctest::Approx(-0.328429734019).epsilon(1e-9)); - CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.53 * -0.178598957983).epsilon(1e-9)); - CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.53 * -0.868291889902).epsilon(1e-9)); + CHECK(stray.x == doctest::Approx(0.158385385505).epsilon(1e-9)); + CHECK(stray.y == doctest::Approx(0.356190053667).epsilon(1e-9)); + CHECK(stray.z == doctest::Approx(0.200372098150).epsilon(1e-9)); + CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.35 * -0.178598957983).epsilon(1e-9)); + CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.35 * -0.868291889902).epsilon(1e-9)); } TEST_CASE("uneven track: tracks laid towards each other meet at one cant") diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 48d10e8b1..458b79eed 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -2,9 +2,15 @@ #include "doctest.h" #include "scratch.h" +#include +#include + #include "utilities/Globals.h" #include "utilities/utilities.h" +#include +#include + // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their // oddities included. the ones which look like mistakes are listed in COVERAGE.md. the helpers which read from a // parser (LoadPoint, the sets, the map) are in test_parser.cpp @@ -112,16 +118,31 @@ TEST_CASE("utilities: clearing a flag needs all of its bits set") { TEST_CASE("utilities: random whole numbers are within the bounds, both included, given in any order") { std::set seen; for (auto draw{0}; draw < 200; ++draw) { - auto const value{Random(3, 7)}; + auto const value{RandomInt(3, 7)}; CHECK(value >= 3); CHECK(value <= 7); seen.insert(value); - auto const swapped{Random(7, 3)}; + auto const swapped{RandomInt(7, 3)}; CHECK(swapped >= 3); CHECK(swapped <= 7); } CHECK(seen.size() == 5); - CHECK(Random(5, 5) == 5); + CHECK(RandomInt(5, 5) == 5); +} + +TEST_CASE("utilities: whole-number bounds still give a real number in between") { + // the wind, the wheel flats, the truck hunting and the tachometer draw with whole-number bounds + static_assert(std::is_same_v); + auto fractions{0}; + for (auto draw{0}; draw < 50; ++draw) { + auto const value{Random(0, 4)}; + CHECK(value >= 0.0); + CHECK(value <= 4.0); + if (value != std::floor(value)) { + ++fractions; + } + } + CHECK(fractions > 0); } TEST_CASE("utilities: random numbers are within the bounds given in any order") { @@ -154,17 +175,37 @@ TEST_CASE("utilities: random numbers are within the bounds given in any order") } TEST_CASE("utilities: the same seed gives the same random numbers") { - std::vector first; + std::vector first; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - first.push_back(Random(0, 1000000)); + first.push_back(Random(0.0, 1000000.0)); } - std::vector second; + std::vector second; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - second.push_back(Random(0, 1000000)); + second.push_back(Random(0.0, 1000000.0)); } CHECK(first == second); + std::vector localfirst; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localfirst.push_back(RandomInt(0, 1000000)); + } + std::vector localsecond; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localsecond.push_back(RandomInt(0, 1000000)); + } + CHECK(localfirst == localsecond); +} + +TEST_CASE("utilities: the whole numbers are drawn from the local engine, not from that of the run's seed") { + // the trivia of the loading screen is drawn before a network client gets the seed of the session + Global.random_engine.seed(5); + auto const first{Random()}; + Global.random_engine.seed(5); + RandomInt(0, 9); + CHECK(Random() == first); } TEST_CASE("utilities: the local random numbers have an engine of their own") { @@ -681,12 +722,30 @@ TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one" CHECK(Round(-2.5) == -2); } -TEST_CASE("utilities: a value is kept within bounds, given in any order") { +TEST_CASE("utilities: a value is kept within bounds; inverted bounds give the upper one, as the old clamp did") { CHECK(safe_clamp(5, 0, 3) == 3); - CHECK(safe_clamp(5, 3, 0) == 3); - CHECK(safe_clamp(-1, 3, 0) == 0); - CHECK(safe_clamp(2.0, 3.0, 1.0) == 2.0); + CHECK(safe_clamp(-1, 0, 3) == 0); + CHECK(safe_clamp(2, 0, 3) == 2); CHECK(safe_clamp(2.0, 2.0, 2.0) == 2.0); + // inverted bounds: always the upper bound, whatever the value + CHECK(safe_clamp(5, 3, 0) == 0); + CHECK(safe_clamp(-1, 3, 0) == 0); + CHECK(safe_clamp(2.0, 3.0, 1.0) == 1.0); + // NaN as the old clamp had it: a NaN value stays NaN, a NaN bound doesn't clamp + auto const notanumber{std::numeric_limits::quiet_NaN()}; + CHECK(std::isnan(safe_clamp(notanumber, 0.0, 1.0))); + CHECK(safe_clamp(2.0, 0.0, notanumber) == 2.0); + CHECK(safe_clamp(-1.0, notanumber, 1.0) == -1.0); + // what the helper gives for arguments in the order and of the signs of two calls (these checks don't call + // them): the AI braking test, whose demand is the stronger of the two (negative) bounds, as up to 26.05.1 + double const threshold{-0.45}; + CHECK(safe_clamp(0.3, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + CHECK(safe_clamp(-0.6, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + // and the bump at a rail joint, 0 in place of the value as up to 26.05.1: the figure is capped from above + // only, and above 68% of the top speed it is negative + CHECK(safe_clamp(0.0, 160.0, 160.0 - (150.0 + 160.0 * 0.32)) == doctest::Approx(-41.2)); + CHECK(safe_clamp(0.0, 4.0, -0.5) == -0.5); + CHECK(safe_clamp(0.0, 4.0, 5.0) == 4.0); } TEST_CASE("utilities: a value is wrapped into a range, as an angle into the full circle") { diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index 81df2ce2a..ba60be900 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -38,10 +38,10 @@ CURVE_STEP = 1.0 / 2500.0 # a difference of curvature that counts as a change, RISE = 0.0273 * 4.5 # how fast pressure lifts a pantograph, m/s, by TDynamicObject::Update GAP_MOST = 0.006 # the gap to the wire allowed; at 0.01 m the voltage goes and the main breaker trips OVERSPEED = 1.1 # a driver can go this much over the speed of the track -# as up_waves and the dip of the joints in world/TrackUneven.h -STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0 +# as up_waves, stray_up_per_mm and the dip of the joints in world/TrackUneven.h +STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00229, 0.4, 3.0 GOLDEN = math.pi * (3.0 - math.sqrt(5.0)) -UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))] +UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0), (.0761, .1058, .1393, .176, .2175, .2651, .3215, .3887)))] TOKEN = re.compile(r"//[^\n]*|\S+") NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$") diff --git a/track_uneven_doc.md b/track_uneven_doc.md index e4822b971..1899abdc3 100644 --- a/track_uneven_doc.md +++ b/track_uneven_doc.md @@ -46,15 +46,17 @@ A track with `uneven 18` measures as follows (`tests/unit/test_track_uneven.cpp` | parameter | result | Id-14 | |--------------------------|--------|-----------| | vertical irregularities | 18 mm | 18 mm | -| horizontal irregularities | 19 mm | 17 mm | +| horizontal irregularities | 17 mm | 17 mm | | twist on a 5 m base | 15 mm | 16 mm | | gauge | ±10 mm | +10/-8 mm | -| cross level | 20 mm | 20 mm | -| J index | 6.1 | 5.3 | +| cross level | 21 mm | 20 mm | +| J index | 5.7 | 5.3 | + +Id-14 only gives the scale of the value: how a track at that value measures. What the waves look like follows the track spectra of the literature, see "How it works". ## How it works -Unevenness is a displacement field that depends on the position on the map, made of waves 5-42 m long. Vertically there are fewer short waves, so the rails come near the peak value more often, and there are also waves of 47-83 m: they hardly count on the 10 m chord, the body rises and falls on them, and a pantograph keeps up with them. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. +Unevenness is a displacement field that depends on the position on the map, made of waves 7-90 m long sideways and 8-110 m long vertically, about the bands D1-D3 of EN 13848. Their heights follow the shape of the track spectra of the US FRA and of ORE B176 (the German spectrum): a power spectral density of `Wc² / (W² (W² + Wc²))`, `Wc = 0.8245 rad/m`, so the longer a wave, the higher it is. Most of the height is in the long waves: they hardly count on the 10 m chord, the body rises and falls on them slowly, and the cab hardly feels them. At `uneven 18` a track goes up to about 5 cm up or down and about 4.5 cm sideways off its design over the long waves, and the short ones of 7-10 m, the ones the cab shakes on, are a few millimetres. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. Each component joins separately: @@ -67,7 +69,7 @@ The ends of joined paths meet in the middle between them, with one vector across The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the body and the cab shake follow the unevenness. The slope of the ballast takes up the difference, and its foot stays as designed, on the ground. -Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres. +Models from includes (e.g. switch drives and timbers), platform edges, level crossing panels, the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres, sideways up to about 4.5 cm at `uneven 18`. On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before, as far as it has something to put in their place. It goes by the track under the vehicle, and on a switch by the path set and what its joined tracks allow. Dips at the joints and cross level replace nothing, as they don't shake the cab all the way along or sideways. On tracks with no unevenness everything works as before. @@ -83,7 +85,7 @@ On a track with unevenness the track itself shakes the cab, in place of two of t This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration. -A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. +A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 1150, for example 9.6 mm at 120 km/h, 16 mm at 70 km/h and 29 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. The physics takes the curve radius and the grade from the design, so unevenness doesn't change them. It adds only the cross level towards derailment, about 0.06 m/s² at `uneven 18` against a threshold of about 3.2 m/s². diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 90c206dfa..e920849b2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1410,6 +1410,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "crashdump.full") + { + ParseOne(Parser, CrashDumpFull); + return true; + } + if (token == "showsystemconsole") { ParseOne(Parser, ShowSystemConsole); @@ -1890,6 +1896,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); + export_as_text( Output, "crashdump.full", CrashDumpFull ); export_as_text( Output, "showsystemconsole", ShowSystemConsole ); export_as_text( Output, "logs.filter", DisabledLogTypes ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index ceb9948c4..3b1441240 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,6 +119,10 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; + // the dump written when the simulator crashes (Windows): a small one by default, with the stacks, the threads, the + // modules, the memory the stacks point to and the modules' data. "crashdump.full yes" writes all the memory of the + // simulator instead, as large as the memory it took + bool CrashDumpFull{ false }; // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" // never, and with no entry it is written along with the physics logs std::optional BlackBox; @@ -201,6 +205,12 @@ struct global_settings { bool EditorOrtho{ false }; float EditorOrthoExtent{ 150.f }; int EditorOrthoTracks{ 0 }; // the railway in the top view of the editor: 0 whole, 1 without the ballast, 2 the rails alone + // the free camera of the editor: its speed set in the View menu, the Ctrl multiplier of it, and in the top view whether it goes as far + // as the view reaches, so the map moves across the screen as fast zoomed in as out + bool EditorCameraOn{ false }; // the editor is on: its camera goes by the settings below + double EditorCameraSpeed{ 1.0 }; + double EditorCameraFast{ 30.0 }; + bool EditorCameraZoomed{ false }; GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury GLint iMaxCabTextureSize{ 4096 }; // largest allowed texture in vehicle cab int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index e0949aba6..f4032d808 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include @@ -115,6 +116,8 @@ void LogService() { std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); + // the stack of a crash on Linux goes to the end of this file + crash_signals::set_log_path(filename); } output << msg << "\n"; output.flush(); diff --git a/utilities/crashsignals.cpp b/utilities/crashsignals.cpp new file mode 100644 index 000000000..fa62e8955 --- /dev/null +++ b/utilities/crashsignals.cpp @@ -0,0 +1,234 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/crashsignals.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// the handler may only call what is safe in a signal: no allocation, no locks, no streams. so what it needs is +// kept in fixed buffers, filled in beforehand, and written with write() + +constexpr std::array crash_signal_list{SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT}; +// a handler that hangs (a crash inside the allocator or the loader, which backtrace() may need) ends this long after +constexpr unsigned int crash_report_timeout_seconds{5}; + +// a text of fixed size, filled outside the handler and read in it +template struct fixed_text { + std::array text{}; + std::atomic ready{false}; + + void set(std::string_view const Text) { + ready = false; + auto const length{std::min(Text.size(), text.size() - 1)}; + std::copy_n(Text.data(), length, text.data()); + text[length] = '\0'; + ready = true; + } + char const *get() const { return ready ? text.data() : nullptr; } +}; + +fixed_text<1024> &log_path() { + static fixed_text<1024> path; + return path; +} + +fixed_text<256> &version_text() { + static fixed_text<256> version; + return version; +} + +// the stack the handler runs on, so an overflow of the main thread's own stack is reported too +std::array &alternate_stack() { + static std::array stack{}; + return stack; +} + +void write_all(int const File, std::string_view Text) { + while (false == Text.empty()) { + auto const written{::write(File, Text.data(), Text.size())}; + if (written <= 0) + return; + Text.remove_prefix(static_cast(written)); + } +} + +void write_hex(int const File, std::uintptr_t const Value) { + constexpr std::size_t digits{sizeof(Value) * 2}; + constexpr std::string_view hexdigits{"0123456789abcdef"}; + std::array text{'0', 'x'}; + for (std::size_t digit = 0; digit < digits; ++digit) + text[2 + digit] = hexdigits[(Value >> (4 * (digits - 1 - digit))) & 0xF]; + write_all(File, {text.data(), text.size()}); +} + +void write_decimal(int const File, int const Value) { + std::array text{}; + auto position{text.size()}; + auto rest{static_cast(Value < 0 ? -Value : Value)}; + do { + text[--position] = static_cast('0' + rest % 10); + rest /= 10; + } while (rest != 0 && position > 1); + if (Value < 0) + text[--position] = '-'; + write_all(File, {text.data() + position, text.size() - position}); +} + +std::string_view signal_name(int const Signal) { + switch (Signal) { + case SIGSEGV: + return "SIGSEGV"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGABRT: + return "SIGABRT"; + default: + return "?"; + } +} + +// the signal being reported, for a report that hangs +std::atomic &crash_signal() { + static std::atomic signal{0}; + return signal; +} + +// a report that hangs is given up: the process ends by the signal of the crash, as it would have without the handler +void handle_report_timeout(int) { + auto const crashsignal{crash_signal().load()}; + raise(crashsignal); + // it is blocked while its own handler runs, which this one interrupted + sigset_t unblocked; + sigemptyset(&unblocked); + sigaddset(&unblocked, crashsignal); + sigprocmask(SIG_UNBLOCK, &unblocked, nullptr); +} + +struct crash_stack { + std::array frames{}; + int count{0}; +}; + +void write_report(int const File, int const Signal, siginfo_t const *Info, crash_stack const &Stack) { + write_all(File, "\nCrash: signal "); + write_decimal(File, Signal); + write_all(File, " ("); + write_all(File, signal_name(Signal)); + write_all(File, ")"); + // the address of the fault; an abort has none + if (Signal != SIGABRT && Info != nullptr) { + write_all(File, " at address "); + write_hex(File, reinterpret_cast(Info->si_addr)); + } + write_all(File, "\n"); + if (auto const *version{version_text().get()}) { + write_all(File, "Version: "); + write_all(File, version); + write_all(File, "\n"); + } + write_all(File, "Stack (addr2line -f -C -e ):\n"); + backtrace_symbols_fd(Stack.frames.data(), Stack.count, File); +} + +void handle_crash_signal(int const Signal, siginfo_t *Info, void *) { + crash_signal() = Signal; + struct sigaction timeout{}; + timeout.sa_handler = handle_report_timeout; + sigemptyset(&timeout.sa_mask); + sigaction(SIGALRM, &timeout, nullptr); + alarm(crash_report_timeout_seconds); + + crash_stack stack; + stack.count = backtrace(stack.frames.data(), static_cast(stack.frames.size())); + + if (auto const *path{log_path().get()}) { + if (auto const log{::open(path, O_WRONLY | O_APPEND | O_CLOEXEC)}; log >= 0) { + write_report(log, Signal, Info, stack); + ::close(log); + } + } + write_report(STDERR_FILENO, Signal, Info, stack); + + // the handler was taken off as it was called (SA_RESETHAND): the signal does what it always did + raise(Signal); +} + +} // namespace + +namespace crash_signals { + +void install(std::string_view const Version) { + static std::atomic installed{false}; + if (installed.exchange(true)) + return; + + version_text().set(Version); + + // backtrace() loads what it needs on its first call, which allocates: done here, not in the handler + std::array warmup{}; + backtrace(warmup.data(), static_cast(warmup.size())); + + stack_t alternate{}; + alternate.ss_sp = alternate_stack().data(); + alternate.ss_size = alternate_stack().size(); + sigaltstack(&alternate, nullptr); + + struct sigaction action{}; + action.sa_sigaction = handle_crash_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESETHAND; + // another crash signal of the same thread waits until the report is written, rather than starting a second one in + // its middle (a fault that comes while it is blocked still ends the process). a crash of another thread at the + // same moment may still write its report alongside + sigemptyset(&action.sa_mask); + for (auto const crashsignal : crash_signal_list) + sigaddset(&action.sa_mask, crashsignal); + for (auto const crashsignal : crash_signal_list) + sigaction(crashsignal, &action, nullptr); +} + +void set_log_path(std::string_view const Path) { + // whole, so the report finds the file wherever the simulator stands then + std::error_code error; + auto const path{std::filesystem::absolute(std::filesystem::path{Path}, error)}; + log_path().set(error ? std::string{Path} : path.string()); +} + +} // namespace crash_signals + +#else + +namespace crash_signals { + +void install(std::string_view) {} +void set_log_path(std::string_view) {} + +} // namespace crash_signals + +#endif diff --git a/utilities/crashsignals.h b/utilities/crashsignals.h new file mode 100644 index 000000000..feb526869 --- /dev/null +++ b/utilities/crashsignals.h @@ -0,0 +1,25 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the stack of a crash on Linux, where no dump is written: a signal of a fault (SIGSEGV, SIGBUS, SIGFPE, SIGILL) or +// SIGABRT writes the stack of the thread that took it to the log and to the standard error, which the starter shows, +// and then ends the simulator as the signal always did (a core dump where the system makes one). the addresses are +// read with addr2line on the eu07 file of the same version, which carries its symbols. elsewhere it does nothing +namespace crash_signals { + +// sets the handlers up, once. Version goes into the report, to tell which eu07 file the addresses belong to +void install(std::string_view Version); +// the log file the report is added to, once the log has opened it +void set_log_path(std::string_view Path); + +} // namespace crash_signals diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index d37ea69e7..208fc7b01 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -14,22 +14,13 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include #include -#include -#include #include -#include #include #include #include -#if defined(__linux__) -#include -#include -#endif - physicslog_writer PhysicsLogs; namespace { @@ -76,64 +67,14 @@ void tell(std::string const &Text) noexcept { } } -// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the -// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking -// when there are hundreds of them -void lower_disk_priority() noexcept { -#ifdef _WIN32 - // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of - // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a - // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without - // end. a thread which can't have it writes as it did before - static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); -#elif defined(__linux__) && defined(SYS_ioprio_set) - // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the - // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has - constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 - constexpr int classbesteffort{2}; - constexpr int classshift{13}; - constexpr int lowest{7}; - static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); -#endif -} - } // namespace -void physicslog_values::append_to(std::string &Text) const { - std::ostringstream line; - line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " - << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " - << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " - << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " - << wateraux << " " << vehiclespeed << "\r\n"; - Text.append(line.str()); -} - -void physicslog_writer::pending::to_text() { - if (values.empty()) - return; - // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was - std::string lines; - for (auto const &line : values) - line.append_to(lines); - text.append(lines); - values.clear(); -} - -physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : - m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { try { stop(); - // the writings left behind by the stops use the object, which goes - std::vector> closings; - { - std::scoped_lock lock{m_mutex}; - closings.swap(m_closings); - } - for (auto const &closing : closings) - closing.wait(); } catch (...) { // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse } @@ -145,33 +86,18 @@ void physicslog_writer::begin(std::string const &Name, std::string_view const He lines.fresh = true; lines.header.assign(Header); lines.text.clear(); - lines.values.clear(); start(); } void physicslog_writer::append(std::string const &Name, std::string_view const Line) { std::scoped_lock lock{m_mutex}; - auto &lines{m_pending[Name]}; - // after the lines given as values before it - lines.to_text(); - lines.text.append(Line); + m_pending[Name].text.append(Line); start(); } -void physicslog_writer::append(std::string const &Name, physicslog_values Values) { - std::scoped_lock lock{m_mutex}; - m_pending[Name].values.push_back(std::move(Values)); - start(); -} - -void physicslog_writer::put_first(std::string const &Name) { - std::scoped_lock lock{m_mutex}; - m_first.insert(Name); -} - void physicslog_writer::flush() { std::scoped_lock files{m_filemutex}; - write(writing::flush); + write(); } bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { @@ -180,7 +106,7 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { auto done{std::make_shared>()}; auto ended{done->get_future()}; std::thread([this, done] { - flush_safely(writing::flush); + flush_safely(); done->set_value(); }).detach(); return ended.wait_for(Timeout) == std::future_status::ready; @@ -189,16 +115,12 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { void physicslog_writer::stop() { std::jthread thread; bool itself; - closing_time closeby; { std::scoped_lock lock{m_mutex}; m_stopped = true; // taken by the first to stop, so it's joined once thread = std::move(m_thread); itself = m_writer == std::this_thread::get_id(); - // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun - // ends at the log at hand, leaving the others to it - closeby = closing_begun(); } // the stop asked outside the lock, which waking the writer takes if (thread.joinable()) @@ -209,55 +131,9 @@ void physicslog_writer::stop() { thread.detach(); return; } - if (close_aside(thread, closeby)) - return; - // no thread for it, out of memory say: written here, the logs past the time dropped all the same if (thread.joinable()) thread.join(); - flush_safely(writing::closing); -} - -physicslog_writer::closing_time physicslog_writer::closing_begun() { - std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); - // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the - // longer, nor give the writing of the first more of it - if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) - return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; - auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; - m_closeby = closeby.time_since_epoch().count(); - return {closeby, true}; -} - -bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { - // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which - // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, - // the writing with it - auto started{false}; - try { - auto done{std::make_shared>()}; - std::shared_future const closing{done->get_future()}; - { - std::scoped_lock lock{m_mutex}; - m_closings.push_back(closing); - } - // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it - std::thread([this, done, writer = std::move(Thread)]() mutable { - if (writer.joinable()) - writer.join(); - flush_safely(writing::closing); - done->set_value(); - }).detach(); - started = true; - // told by the stop which gave the time, not again by one after it - if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) - tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", - std::chrono::duration{m_closingwait}.count())); - return true; - } catch (...) { - // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun - // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it - return started; - } + flush_safely(); } std::filesystem::path physicslog_writer::file(std::string const &Name) const { @@ -279,12 +155,6 @@ std::string physicslog_writer::shown(std::string const &Name) const { return m_shownfolder + '/' + file_name(Name); } -std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { - // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the - // waits growing with no end, and a crash would lose more of them - return std::clamp(Took * 3, Interval, Interval * 5); -} - void physicslog_writer::start() { if (m_stopped || m_thread.joinable()) return; @@ -293,199 +163,101 @@ void physicslog_writer::start() { } void physicslog_writer::run(std::stop_token const &Stop) { - lower_disk_priority(); // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is // either about to wait, and sees the stop, or waiting already std::stop_callback const wake{Stop, [this] { { std::scoped_lock lock{m_mutex}; } m_wake.notify_all(); }}; - std::chrono::steady_clock::duration wait{m_interval}; while (false == Stop.stop_requested()) { { std::unique_lock lock{m_mutex}; // woken early only to stop, which writes the rest itself - if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + if (m_wake.wait_for(lock, m_interval, [&Stop] { return Stop.stop_requested(); })) return; } - auto const start{std::chrono::steady_clock::now()}; - // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's - auto const logs{flush_safely(writing::thread)}; - auto const took{std::chrono::steady_clock::now() - start}; - wait = wait_after(m_interval, took); - if (wait > m_interval && false == m_slowtold) { - m_slowtold = true; - using seconds = std::chrono::duration; - try { - WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " - "written less often from now on, every {:.1f} s at most", - logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); - } catch (...) { - // out of memory for a line of the log: the logs are written all the same - } - } + flush_safely(); } } -std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { +void physicslog_writer::flush_safely() noexcept { try { - std::scoped_lock files{m_filemutex}; - return write(Mode); + flush(); } catch (std::exception const &Error) { tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); } catch (...) { tell("Bad physics log: the writing failed, the lines taken for it are lost"); } - return 0; } -bool physicslog_writer::past_closing() const { - auto const closeby{m_closeby.load()}; - return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; -} - -void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { - // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it - auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; - for (auto &[name, lines] : Failed) { - // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as - // text they go before what came since - try { - lines.to_text(); - } catch (std::exception const &) { - // kept as values, below - } - keep_last(lines.text, most); - } - // tried again the next time, before what came since; a file held by another program for a while doesn't lose - // them, nor its header - std::scoped_lock lock{m_mutex}; - for (auto &[name, lines] : Failed) - put_back(name, lines); - for (auto *log : Left) - put_back(log->first, log->second); -} - -void physicslog_writer::put_back(std::string const &Name, pending &Lines) { - auto &now{m_pending[Name]}; - // a log begun anew since drops them - if (now.fresh) - return; - // the lines in the order given: those kept, then those come since, as text and as values. values kept before text - // come since are made into text first, as those before a line given as text are; values which can't be, out of - // memory, are dropped then, as the order can't be kept otherwise - if (false == now.text.empty() && false == Lines.values.empty()) { - try { - Lines.to_text(); - } catch (std::exception const &) { - Lines.values.clear(); - } - } - Lines.text.append(now.text); - // added at once, allocated first: one failing moves none of them - if (Lines.values.empty()) - Lines.values = std::move(now.values); - else - Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); - now = std::move(Lines); -} - -std::size_t physicslog_writer::write(writing const Mode) { +void physicslog_writer::write() { std::map taken; - std::set first; - std::vector *> order; { std::scoped_lock lock{m_mutex}; - if (m_pending.empty()) - return 0; - // a stop come before the thread's writing: the lines are all the closing's, left as they are - if (Mode == writing::thread && m_closeby.load() != 0) - return 0; - // had before the lines are taken: without the memory for it they're left for the next writing - first = m_first; - order.reserve(m_pending.size()); taken.swap(m_pending); } - auto const logs{taken.size()}; + if (taken.empty()) + return; std::error_code error; std::filesystem::create_directories(m_folder, error); - std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); - writing_order(order, first); std::map failed; - std::size_t dropped{0}; - std::size_t reached{0}; - for (auto *log : order) { - // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has - // them with the lines given since, those put first first - if (Mode == writing::thread && m_closeby.load() != 0) - break; - ++reached; - auto &[name, lines]{*log}; - // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer - if (Mode == writing::closing && past_closing()) { - ++dropped; + for (auto &[name, lines] : taken) { + if (lines.text.empty() && false == lines.fresh) + continue; + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + written = write_log(name, lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(name) > 0) + WriteLog("Physics log: " + shown(name) + " written again"); continue; } - if (false == write_taken(name, lines)) - failed.emplace(name, std::move(lines)); + if (m_failed.insert(name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(name) + ", its last lines are kept for the next try"); + failed.emplace(name, std::move(lines)); } - if (dropped > 0) - tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, - std::chrono::duration{m_closingwait}.count())); - // what is left of the order: the logs the thread hasn't come to - order.erase(order.begin(), order.begin() + static_cast(reached)); - if (false == failed.empty() || false == order.empty()) - keep(failed, order); - return logs; -} - -bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { - // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: - // the others are written still, and the writer goes on - auto written{false}; - std::string problem{"can't write"}; - try { - // the text of the lines given as values, here on the writer's thread rather than the simulation's - Lines.to_text(); - if (Lines.text.empty() && false == Lines.fresh) - return true; - written = write_log(Name, Lines); - } catch (std::exception const &Error) { - problem = std::string{"failed ("} + Error.what() + ") to write"; + if (failed.empty()) + return; + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / failed.size())}; + for (auto &[name, lines] : failed) + keep_last(lines.text, most); + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header. a log begun anew since drops them + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : failed) { + auto &now{m_pending[name]}; + if (now.fresh) + continue; + lines.text.append(now.text); + now = std::move(lines); } - if (written) { - if (m_failed.erase(Name) > 0) - WriteLog("Physics log: " + shown(Name) + " written again"); - return true; - } - if (m_failed.insert(Name).second) - ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); - return false; } bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { auto const path{file(Name)}; - // one write to the file: the header of a log begun with its lines, not the one after the other - std::string begun; - if (Lines.fresh) - begun = Lines.header + Lines.text; - std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; - // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". - // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines - // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't - // asked for the length before, one access less of hundreds of logs - std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; - if (false == stream.is_open()) - return false; - auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; - stream.write(text.data(), static_cast(text.size())); + std::error_code error; + // how long it was, to be cut back to if the lines are written in part only, a disk filling up say: else they'd be + // written twice, the next time + auto const before{Lines.fresh ? 0 : std::filesystem::file_size(path, error)}; + auto const existed{false == Lines.fresh && false == static_cast(error)}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; + if (stream.is_open()) { + if (Lines.fresh) + stream << Lines.header; + stream << Lines.text; + } stream.close(); if (false == stream.fail()) return true; - // a log begun is written anew from its header the next time anyway - if (false == Lines.fresh && before >= 0) { - std::error_code error; - std::filesystem::resize_file(path, static_cast(before), error); - } + if (existed) + std::filesystem::resize_file(path, before, error); return false; } diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 286df7e87..0f397d27c 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -9,12 +9,9 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include -#include #include #include #include -#include #include #include #include @@ -22,60 +19,18 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include - -// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which -// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty -// lines a second each. the columns as physicslog_header of the driver names them -struct physicslog_values { - double time{0.0}; - double wheelspeed{0.0}; - double acceleration{0.0}; - double couplerdistance{0.0}; - double couplerforce{0.0}; - double tractionforce{0.0}; - double frictionforce{0.0}; - double brakeforce{0.0}; - double brakepressure{0.0}; - double pipepressure{0.0}; - double motorcurrent{0.0}; - int mainctrl{0}; - int scndctrl{0}; - double brakectrl{0.0}; - double localbrake{0.0}; - int direction{0}; - std::string command; - double value1{0.0}; - double value2{0.0}; - int security{0}; - int wheelslip{0}; - double enginetemperature{0.0}; - double oiltemperature{0.0}; - double watertemperature{0.0}; - double wateraux{0.0}; - double vehiclespeed{0.0}; - - // the line, as the logs always had it, at the end of Text - void append_to(std::string &Text) const; -}; // the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's // has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, // each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the -// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk -// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next -// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the -// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind -// them. the closing waits for the writing a second at most (below) +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them. lines whose file can't +// be written, held by another program say, are kept for the next try: the last 64 MB of them all at most class physicslog_writer { public: - explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, - std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); physicslog_writer(physicslog_writer const &) = delete; physicslog_writer &operator=(physicslog_writer const &) = delete; - // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, - // global, never goes this way: the process ends with _Exit + // stops, writing what is kept ~physicslog_writer(); // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. @@ -83,20 +38,12 @@ public: void begin(std::string const &Name, std::string_view Header); // Line at the end of the log Name. a log not begun is added to as its file stands void append(std::string const &Name, std::string_view Line); - // the same, a line of the values, made into text by the writer's thread when it writes the log - void append(std::string const &Name, physicslog_values Values); - // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the - // tested trains, which a closing short of time would otherwise drop by the order of their names - void put_first(std::string const &Name); // writes what is kept, now void flush(); // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left // behind. for the end of the process, the files held up or the disk not answering bool flush_for(std::chrono::milliseconds Timeout); - // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by - // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a - // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with - // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a @@ -105,84 +52,36 @@ public: std::filesystem::path file(std::string const &Name) const; // the same, for the log of the simulator std::string shown(std::string const &Name) const; - // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long - // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the - // logs a quarter of the time rather than all of it, and their lines wait in memory the longer - static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); - // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: - // those put first (First) before the others, each in the order they were - template static void writing_order(std::vector &Logs, std::set const &First) { - std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); - } private: - // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the - // closing's, which drops the logs past the time the stop gives it - enum class writing { flush, thread, closing }; - - // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way - struct closing_time { - std::chrono::steady_clock::time_point by; - bool fresh{true}; - }; - struct pending { bool fresh{false}; // its file is to be emptied first, and the header written into it std::string header; std::string text; - // the lines given as values since, after the text: made into text when written - std::vector values; - - // the lines of the values at the end of the text - void to_text(); }; - // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held - closing_time closing_begun(); - // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no - // thread could be had for it, out of memory say; Thread may be the writer still then - bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; // the thread, on the first line given, unless stopped. called with m_mutex held void start(); void run(std::stop_token const &Stop); // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the - // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. - // returns: the number of logs there were to write - std::size_t flush_safely(writing Mode) noexcept; - // called with m_filemutex held. returns: the number of logs there were to write - std::size_t write(writing Mode); - // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if - // it wasn't, its lines to be kept for the next try - bool write_taken(std::string const &Name, pending &Lines); - // whether the time a stop gave the writing is over - bool past_closing() const; - // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, - // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as - // they were taken: their values are made into text by that writing, which drops them past its time, not on the way - // unless text was given since - void keep(std::map &Failed, std::vector *> const &Left); - // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held - void put_back(std::string const &Name, pending &Lines); + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since + void flush_safely() noexcept; + // called with m_filemutex held + void write(); // the lines of the log Name written into its file. returns: true if they all were bool write_log(std::string const &Name, pending const &Lines) const; std::filesystem::path const m_folder; std::string const m_shownfolder; std::chrono::milliseconds const m_interval; - std::chrono::milliseconds const m_closingwait; - // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop - std::atomic m_closeby{0}; std::mutex m_mutex; // the lines kept and the thread std::map m_pending; - std::set m_first; // the logs put first bool m_stopped{false}; std::condition_variable m_wake; std::jthread m_thread; std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it - std::vector> m_closings; // the writings of the stops, which may outlast them std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order std::set m_failed; // the logs whose file couldn't be written, told once - bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own }; // the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index edc694852..61a059e35 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -150,11 +150,11 @@ double Random(double min, double max) return dist(Global.random_engine); } -int Random(int min, int max) +int RandomInt(int min, int max) { if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB) std::uniform_int_distribution dist(min, max); - return dist(Global.random_engine); + return dist(Global.local_random_engine); } std::uint64_t true_random_seed() diff --git a/utilities/utilities.h b/utilities/utilities.h index 25ee3882c..0cefb6c11 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -64,7 +64,12 @@ inline long Round(double const f) } double Random(double a, double b); -int Random(int min, int max); +// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number +// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the +// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it +// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would +// put that engine out of step with the other machines of a network session +int RandomInt(int min, int max); /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. @@ -293,17 +298,18 @@ template bool is_equal(T const &Left, T const &Right, T const Epsil return Left == Right; } -// Tolerant clamp. Unlike std::clamp, this does NOT invoke undefined behaviour when -// the bounds are inverted (Lo > Hi) - it normalizes them instead. This restores the -// pre-refactor behaviour of the old custom clamp() for code paths where the bounds are -// computed at runtime and can legitimately cross (e.g. AI acceleration/braking limits, -// physics jolt calculations), where std::clamp's UB produced wrong results. +// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike +// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted +// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted +// bounds give the upper bound, as the old clamp() did. Every call of the old clamp() +// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are +// computed from such values) uses it, so it gives what it gave before the move to +// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same. +// New code uses std::clamp. template constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi ) { - return ( Hi < Lo ) - ? std::clamp( Value, Hi, Lo ) - : std::clamp( Value, Lo, Hi ); + return std::min( std::max( Value, Lo ), Hi ); } // keeps the provided value in specified range 0-Range, as if the range was circular buffer diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index e2fe58464..fe1a85c9a 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -62,6 +62,30 @@ TCamera::OnCommand( command_data const &Command ) { // threshold position on stick between walk lerp and walk/run lerp auto const stickthreshold = 2.0 / 3.0; + // the free camera of the editor as fast as its View menu sets it, Ctrl by the multiplier set there, in the top view by how far it reaches + auto editorscale { 1.0 }; + auto editorfast { -1.0 }; + if( Global.EditorCameraOn && m_owner == nullptr ) { + editorscale = Global.EditorCameraSpeed; + if( Global.EditorOrtho && Global.EditorCameraZoomed ) { + editorscale *= std::clamp( static_cast( Global.EditorOrthoExtent ) / 150.0, 0.02, 200.0 ); + } + editorfast = Global.EditorCameraFast; + } + // how many times faster the fast command of a move makes it: the editor's own, or the free fly's (Default) and the cab's (Cab) + auto const fastness = [&]( bool const Fast, double const Editor, double const Default, double const Cab ) { + if( false == Fast ) { + return 1.0; + } + if( editorfast > 0.0 ) { + return Editor; + } + if( false == FreeFlyModeFlag ) { + return 1.0; + } + return m_owner == nullptr ? Default : Cab; + }; + bool iscameracommand { true }; switch( Command.command ) { @@ -82,7 +106,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::movehorizontalfast ? m_owner == nullptr ? 30.0 : 5.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::movehorizontalfast, editorfast, 30.0, 5.0 ); // left-right m_moverate.x = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -101,7 +125,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::moveverticalfast ? m_owner == nullptr ? 10.0 : 3.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::moveverticalfast, std::max( 1.0, editorfast / 3.0 ), 10.0, 3.0 ); // up-down m_moverate.y = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -192,9 +216,12 @@ void TCamera::Update() bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { + // the roll (z) is multiplied in first, so it acts last, about the line of sight: the sway of the cab tilts the view + // the same way wherever the head is turned, as it did in 26.05. the order matters only with a roll (the cab shake, + // or the angles of a camera entry of the scenery) + Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia - Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie if( m_owner != nullptr && false == DebugCameraFlag ) { diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 2b3633433..99c6a951e 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" @@ -212,6 +213,7 @@ void TSpeedPos::Clear() fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; fDist = 0.0; + bSeenAhead = false; vPos = glm::dvec3(0, 0, 0); trTrack = nullptr; // brak wskaźnika }; @@ -328,6 +330,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -413,9 +418,18 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } +// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] +constexpr double SeenAheadTolerance { 5.0 }; + bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) { // zapamiętanie zdarzenia fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the + // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head + // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than + // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't + // be told from one stopped just short of it, which really passes the signal if it goes on + bSeenAhead = ( dist >= -SeenAheadTolerance ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -910,6 +924,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { if( Passedbefore || false == TestFlag( Point.iFlags, spElapsed ) + || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -2346,10 +2361,10 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, } TableClear(); - // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line - // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles - // are made passive before it starts, so they get no file with only the header - if( WriteLogFlag && false == drives_road_vehicle() ) { + // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every + // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive + // before it starts, so they get no file with only the header + if( WriteLogFlag ) { begin_physicslog(); } @@ -5387,38 +5402,38 @@ std::string_view TController::physicslog_header() { "\r\n"; } -physicslog_values TController::physicslog_line() const { - // the values only: the writer of the logs makes them into text on its own thread - physicslog_values line; - line.time = ElapsedTime; - line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); - line.acceleration = mvControlling->AccS; - line.couplerdistance = mvOccupied->Couplers[1].Dist; - line.couplerforce = mvOccupied->Couplers[1].CForce; - line.tractionforce = mvOccupied->Ft; - line.frictionforce = mvOccupied->Ff; - line.brakeforce = mvOccupied->Fb; - line.brakepressure = mvOccupied->BrakePress; - line.pipepressure = mvOccupied->PipePress; - line.motorcurrent = mvControlling->Im; - line.mainctrl = static_cast(mvControlling->MainCtrlPos); - line.scndctrl = static_cast(mvControlling->ScndCtrlPos); - line.brakectrl = mvOccupied->fBrakeCtrlPos; - line.localbrake = mvOccupied->LocalBrakePosA; - line.direction = static_cast(mvControlling->DirActive); - line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); - line.value1 = mvOccupied->CommandIn.Value1; - line.value2 = mvOccupied->CommandIn.Value2; - line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); - line.wheelslip = static_cast(mvControlling->SlippingWheels); - // floats, as the stream wrote them: widened to double - line.enginetemperature = mvControlling->dizel_heat.Ts; - line.oiltemperature = mvControlling->dizel_heat.To; - line.watertemperature = mvControlling->dizel_heat.temperatura1; - line.wateraux = mvControlling->dizel_heat.temperatura2; - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - line.vehiclespeed = mvOccupied->V * 3.6; - return line; +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << ElapsedTime << " " + << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " + << mvControlling->AccS << " " + << mvOccupied->Couplers[1].Dist << " " + << mvOccupied->Couplers[1].CForce << " " + << mvOccupied->Ft << " " + << mvOccupied->Ff << " " + << mvOccupied->Fb << " " + << mvOccupied->BrakePress << " " + << mvOccupied->PipePress << " " + << mvControlling->Im << " " + << int(mvControlling->MainCtrlPos) << " " + << int(mvControlling->ScndCtrlPos) << " " + << mvOccupied->fBrakeCtrlPos << " " + << mvOccupied->LocalBrakePosA << " " + << int(mvControlling->DirActive) << " " + << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " + << mvOccupied->CommandIn.Value1 << " " + << mvOccupied->CommandIn.Value2 << " " + << int(mvControlling->SecuritySystem.is_blinking()) << " " + << int(mvControlling->SlippingWheels) << " " + << mvControlling->dizel_heat.Ts << " " + << mvControlling->dizel_heat.To << " " + << mvControlling->dizel_heat.temperatura1 << " " + << mvControlling->dizel_heat.temperatura2 << " " + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + << mvOccupied->V * 3.6 + << "\r\n"; + return line.str(); } void TController::begin_physicslog() @@ -8213,54 +8228,6 @@ uphill_coasting_speed( double const Distance, double const Gravity ) { return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); } -// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train -// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the -// consist brake table says it does (cast iron blocks grip harder as the train slows) -struct consist_brake_table { - double const *a0; // deceleration at handle position 1, by speed - double const *a1; // deceleration added by each quarter of a position, by speed - int size; // entries, up to the vehicle's top speed - double vmax; // the vehicle's top speed [km/h] - - // deceleration [m/s2] of a full service application at Kmh - double full_braking( double const Kmh ) const { - auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) }; - return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); } -}; - -static double -shaped_braking_demand( - double const Velocity, double const Target, double const Distance, double const Gravity, - consist_brake_table const &Table ) { - - auto const fullbraking = [&Table]( double const Kmh ) { - return Table.full_braking( Kmh ); }; - auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) { - auto const steps { 24 }; - auto const step { ( Velocity - Target ) / steps }; - auto distance { 0.0 }; - for( auto i { 0 }; i < steps; ++i ) { - auto const kmh { Target + ( i + 0.5 ) * step }; - auto const deceleration { Ratio * fullbraking( kmh ) - Gravity }; - if( deceleration <= 0.001 ) { - return std::numeric_limits::max(); - } - distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration; - } - return distance; }; - - auto low { 0.0 }; - auto high { 3.0 }; - if( travel( high ) > Distance ) { - return Gravity - high * fullbraking( Velocity ); - } - for( auto i { 0 }; i < 30; ++i ) { - auto const middle { 0.5 * ( low + high ) }; - ( travel( middle ) > Distance ? low : high ) = middle; - } - return Gravity - high * fullbraking( Velocity ); -} - // outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the // direction of travel void @@ -8287,43 +8254,19 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? stopping_margin() : // the same stopping point as the final approach VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // a pneumatic brake acts on the state the train will be in once it has responded; while the - // train is still speeding up, plan the deceleration from there, so more is asked for at once - auto velocity { Vel }; - auto distance { ActualProximityDist }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AbsAccS > 0.0 ) ) { - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - velocity = Vel + 3.6 * horizon * AbsAccS; - distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon ); - } - auto const brakingroom { - std::max( - distance - brakingpointoffset, - std::min( - distance, - brakingpointoffset ) ) }; - auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) { - // follow the shape of the consist brake force over speed rather than assume a constant - // deceleration, over the distance left once the brake has had time to fill (while the - // train is still speeding up, the prediction above has taken that off already) - auto room { brakingroom }; - if( ( AbsAccS <= 0.0 ) - && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const brakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - room = std::max( - 0.5 * brakingroom, - brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, brakea0 ) ); - } - deceleration = shaped_braking_demand( - velocity, VelNext, room + 0.1 / 25.92, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ); - } + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { return; @@ -8374,7 +8317,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { AccDesired = ( BrakeSystem == TBrakeSystem::Pneumatic ? // cast iron blocks grip harder as the train comes to a stand - shaped_braking_demand( + braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 113be3b94..0aaf70707 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,7 +20,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" -#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -165,6 +164,7 @@ class TSpeedPos int iFlags{ spNone }; // flagi typu wpisu do tabelki bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) + bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train glm::dvec3 vPos; // współrzędne XYZ do liczenia odległości struct { @@ -739,22 +739,17 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } - // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with - // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. - // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + // the physics log (physicslog/.dat): the name of its file without the extension, its first line and + // a line of it as the vehicle is now, each with its line end. the black box keeps the lines of the vehicle the + // user is in, to write its log at the end when the logs of all the vehicles are off std::string const &physicslog_name() const { return VehicleName; } - // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with - // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of - // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes - // the log of one the user is in + // whether it writes its physics log itself: all with "physicslog yes", with "physicslog.trains yes" one who drives + // rail vehicles. a driver made primary later begins its log then bool writes_physicslog() const { - return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } - // a driver of a road vehicle; not one of no vehicle - bool drives_road_vehicle() const { - return mvOccupied != nullptr && is_car(); } + return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); - physicslog_values physicslog_line() const; + std::string physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index ce94a0609..7a301930a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -1162,7 +1163,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) continue; } - auto const dist { std::clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -2446,6 +2447,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ShakeSpring.Init( 125.0 ); BaseShake = baseshake_config {}; ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; // McZapkie-250202 /* @@ -2604,7 +2606,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = std::clamp( + fAxleDist = safe_clamp( std::max( MoverParameters->BDist, MoverParameters->ADist ), 0.2, //żeby się dało wektory policzyć MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" @@ -3202,7 +3204,7 @@ TDynamicObject::update_load_offset() { 0.0 : 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, loadpercentage * 0.01, 1.0 ) ); + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void @@ -3849,20 +3851,21 @@ bool TDynamicObject::Update(double dt, double dt1) // crude bump simulation, drop down on even axles, move back up on // the odd ones // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - double const headroom = std::clamp( - MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ), - 0.0, MoverParameters->Vmax ); + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { - double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1); + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); MoverParameters->AccS += accHorizontal; MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } ++axleindex; @@ -8337,6 +8340,8 @@ void TDynamicObject::OverheadTrack(float o) void TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu @@ -8461,9 +8466,32 @@ TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int con std::pair TDynamicObject::shake_angles() const { + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + return { - std::atan( ShakeState.velocity.x * BaseShake.angle_scale.x ), - std::atan( ShakeState.velocity.z * BaseShake.angle_scale.z ) }; + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } void diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index db427e34d..4db7d32c3 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -925,6 +925,11 @@ public: glm::dvec3 velocity{}; // current shaking vector glm::dvec3 offset{}; // overall shake-driven offset from base position } ShakeState; + shake_state ShakeStateBefore; // the state before the last step of update_shake + // the shake between the last two steps of update_shake: 0 the state before the last step, 1 the state after it. + // the steps are fixed and the frames aren't, so the camera takes the state at its own moment between the two + shake_state shake_between( double const Fraction ) const; + std::pair shake_angles( shake_state const &State ) const; glm::dvec3 modelShake; }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 24d3132f6..8bf948096 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9828,7 +9828,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = std::clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9836,7 +9836,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = std::clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9844,7 +9844,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = std::clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -11463,8 +11463,11 @@ glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const return Point; } - return {std::clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), std::clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - std::clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; } const TTrain::screenentry_sequence &TTrain::get_screens() diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp new file mode 100644 index 000000000..d39ee2868 --- /dev/null +++ b/vehicle/brakingcurve.cpp @@ -0,0 +1,86 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakingcurve.h" + +#include +#include + +namespace braking_curve { + +double brake_table::full_braking(double const Kmh) const { + auto const index{std::clamp(static_cast(size * Kmh / std::max(1.0, vmax)), 1, size)}; + return std::max(0.01, a0[index] + 12.0 * a1[index]); +} + +bool brake_table::known() const { + // a worked out table holds at least the rolling resistance term at every speed + return a0[size] > 0.0; +} + +double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { + + auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { + auto const steps{24}; + auto const step{(Velocity - Target) / steps}; + auto distance{0.0}; + for (auto i{0}; i < steps; ++i) { + auto const kmh{Target + (i + 0.5) * step}; + auto const deceleration{Ratio * Table.full_braking(kmh) - Gravity}; + if (deceleration <= 0.001) { + return std::numeric_limits::max(); + } + distance += (kmh / 3.6) * (step / 3.6) / deceleration; + } + return distance; + }; + + auto low{0.0}; + auto high{3.0}; + if (travel(high) > Distance) { + return Gravity - high * Table.full_braking(Velocity); + } + for (auto i{0}; i < 30; ++i) { + auto const middle{0.5 * (low + high)}; + (travel(middle) > Distance ? low : high) = middle; + } + return Gravity - high * Table.full_braking(Velocity); +} + +double demand(approach const &Approach, brake_table const *Pneumatictable) { + + // a pneumatic brake acts on the state the train will be in once it has responded; while the + // train is still speeding up, plan the deceleration from there, so more is asked for at once + // both plans are made from the brake table of the consist; with none (in shunting it isn't worked out, and planning + // from its zeroes would ask for no braking at all) the braking curve is the constant deceleration over the distance left + auto const *table{(Pneumatictable != nullptr) && Pneumatictable->known() ? Pneumatictable : nullptr}; + auto velocity{Approach.speed}; + auto distance{Approach.distance}; + if ((table != nullptr) && (Approach.acceleration > 0.0)) { + auto const horizon{Approach.speedup_horizon}; + velocity = Approach.speed + 3.6 * horizon * Approach.acceleration; + distance = std::max(0.5 * Approach.distance, Approach.distance - (Approach.speed + velocity) * 0.5 / 3.6 * horizon); + } + auto const brakingroom{std::max(distance - Approach.offset, std::min(distance, Approach.offset))}; + if ((table == nullptr) || (velocity <= Approach.target)) { + return (Approach.target * Approach.target - velocity * velocity) / (25.92 * brakingroom + 0.1); + } + // follow the shape of the consist brake force over speed rather than assume a constant + // deceleration, over the distance left once the brake has had time to fill (while the + // train is still speeding up, the prediction above has taken that off already) + auto room{brakingroom}; + if ((Approach.acceleration <= 0.0) && (false == Approach.brake_applied)) { + // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + room = std::max(0.5 * brakingroom, brakingroom - Approach.speed / 3.6 * Approach.fill_horizon); + } + return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); +} + +} // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h new file mode 100644 index 000000000..6ed40d9bb --- /dev/null +++ b/vehicle/brakingcurve.h @@ -0,0 +1,54 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the deceleration the AI asks for on its way down to a lower speed or a stop ahead, outside of the final +// approach (TController::adjust_desired_speed_for_braking_curve) +namespace braking_curve { + +// the deceleration table of the consist brake, by speed (TController::fBrake_a0, fBrake_a1). it is worked out +// for a train only (Obey_train, Bank); in shunting it stays at zero +struct brake_table { + double const *a0; // deceleration at handle position 1, by speed; a0[1..size] + double const *a1; // deceleration added by each quarter of a position, by speed + int size; // entries, up to the vehicle's top speed + double vmax; // the vehicle's top speed [km/h] + + // deceleration [m/s2] of a full service application at Kmh + double full_braking(double Kmh) const; + // whether the table is worked out + bool known() const; +}; + +// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train +// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the +// table says it does (cast iron blocks grip harder as the train slows) +double shaped_demand(double Velocity, double Target, double Distance, double Gravity, brake_table const &Table); + +// where the train is on its way down to Target +struct approach { + double speed; // present speed in the direction of travel [km/h] + double target; // speed to get down to [km/h] + double distance; // to where the speed is to be down [m] + double offset; // the braking point that far short of it [m] + double gravity; // tangential acceleration of the gradient [m/s2], negative uphill + double acceleration; // present acceleration of the train [m/s2] + bool brake_applied; // the train brake handle is past running + double speedup_horizon; // how long the present acceleration lasts while speeding up [s] + double fill_horizon; // how long the brake takes to fill once applied [s] +}; + +// acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake +// (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has +// responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at +// zero, as in shunting) it is the constant deceleration over the distance left +double demand(approach const &Approach, brake_table const *Pneumatictable); + +} // namespace braking_curve diff --git a/world/Segment.cpp b/world/Segment.cpp index 5e0f47116..1398b3347 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -439,7 +439,10 @@ glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const glm::dvec3 result { 0.0 }; if( m_setting.uneven ) { auto const field { track_uneven::field( Point ) }; - result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result = glm::dvec3 { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); } if( m_setting.buckled && m_pieces.empty() ) { @@ -493,7 +496,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } @@ -532,7 +535,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist