diff --git a/CMakeLists.txt b/CMakeLists.txt index c4e41eb78..7c9540572 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -714,6 +714,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" @@ -723,7 +724,9 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" +"vehicle/uphillstart.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" diff --git a/EU07.cpp b/EU07.cpp index 8255c6907..19703dbe1 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -23,9 +23,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/crashdump.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -51,15 +55,6 @@ int generate_nodebank_previews(int Argc, char *Argv[]); #include #include -// lets the log service write what is still queued and stops it; does nothing once Application.exit() has done that -static void stop_log_service() -{ - Global.applicationQuitOrder = true; - auto const it = Global.threads.find("LogService"); - if (it != Global.threads.end() && it->second.joinable()) - it->second.join(); -} - namespace { @@ -133,9 +128,13 @@ int main(int argc, char *argv[]) { raise_open_files_limit(); crashdump_install(); + // 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 @@ -184,36 +183,51 @@ 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(); } - else - { - exitcode = result; - } } + // 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 the crash report (utilities/crashdump.cpp), whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } - stop_log_service(); #ifndef _WIN32 fflush(stdout); fflush(stderr); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index ed8275bc9..d74aee11f 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -901,7 +901,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 @@ -913,7 +913,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 @@ -3952,7 +3952,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) { @@ -5625,7 +5625,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; @@ -5923,7 +5923,7 @@ double TMoverParameters::TractionForce(double dt) if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -7778,7 +7778,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 @@ -7862,18 +7864,18 @@ void TMoverParameters::CheckEIMIC(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -7980,7 +7982,7 @@ void TMoverParameters::CheckEIMIC(double dt) eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } void TMoverParameters::CheckSpeedCtrl(double dt) @@ -8038,7 +8040,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -8968,7 +8970,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; } @@ -9013,7 +9015,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) { @@ -12891,7 +12893,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; } @@ -13293,7 +13295,7 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "DoorPermit") diff --git a/application/application.cpp b/application/application.cpp index bed4bf3ae..145106b62 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -38,6 +38,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -55,6 +58,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__ @@ -66,6 +70,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" { @@ -141,6 +175,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() @@ -233,7 +289,8 @@ int eu07_application::run_crashgui() } } m_crashui = nullptr; - 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() @@ -363,6 +420,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 @@ -422,7 +481,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible: it's drawn by the renderer 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; } } @@ -471,6 +534,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; } @@ -695,6 +763,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); } } @@ -791,6 +861,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"); @@ -1360,6 +1431,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); + if (glfwInit() == GLFW_FALSE) { ErrorLog("Bad init: failed to initialize glfw"); diff --git a/application/application.h b/application/application.h index 9f947fe79..e9c825d9d 100644 --- a/application/application.h +++ b/application/application.h @@ -35,6 +35,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 efaba691b..aeb4a5635 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 { @@ -656,6 +659,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) { @@ -799,7 +808,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 /* @@ -820,8 +830,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)); @@ -829,7 +840,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index e0406043d..06ce32ee4 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -91,6 +91,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/application/editormode.cpp b/application/editormode.cpp index c2568ae93..42d6ea00f 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" @@ -604,6 +605,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)) @@ -618,6 +622,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 @@ -1415,6 +1421,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 @@ -1660,6 +1675,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"); @@ -3445,7 +3461,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())); } @@ -3482,7 +3498,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); @@ -3527,7 +3543,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 && @@ -4341,7 +4357,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()) { @@ -4502,6 +4518,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")); @@ -7536,6 +7557,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) { @@ -7637,6 +7660,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; @@ -8052,6 +8076,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) @@ -8673,3 +8713,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 09bc5b0c4..900d84383 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -57,6 +57,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -968,6 +969,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}; @@ -1006,6 +1013,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 @@ -2767,8 +2776,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 @@ -2788,10 +2797,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 c39ff671f..95f3062b2 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1182,22 +1182,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 119da9c5d..75a8af3cb 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -89,7 +89,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/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index 96de4a084..ebf29fa5c 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 e7f868c8f..a8f569aaa 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; @@ -1038,6 +1039,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 b93273a8d..70bf9907c 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -89,6 +89,10 @@ class terrain_streamer bool removed(chunk_key const &Key) const { return m_removed.count(Key) > 0; } // the chunk in memory, or nullptr; Load: read from its pack file if it isn't in memory yet editor_terrain *chunk(chunk_key const &Key, bool const Load = false); + // 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; } @@ -269,6 +273,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 1dce2d21b..e7332801e 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14062,6 +14062,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" @@ -16220,3 +16250,38 @@ msgstr "%s obrysowane na nowo, Ctrl+Z cofa" msgid "Puts the outline of the field back as the outline being drawn; cut out again, it changes this field" msgstr "Wstawia obrys pola z powrotem jako rysowany obrys; wycięcie go zmienia to pole" +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 febf018f8..8553d63e5 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -609,6 +609,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) @@ -649,12 +653,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 b1ff94f1a..a66def742 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 e04d45e19..3f5fd9b2b 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -356,6 +357,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 texture_source::precompressed_formats = { @@ -655,9 +657,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 @@ -1190,6 +1287,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; glBindTextureUnit(unit, id); @@ -1552,6 +1650,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 54ba6f753..0e47d4676 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,9 +9,11 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include +#include #include #include "winheaders.h" #include "utilities/memorystats.h" @@ -162,6 +164,14 @@ protected: on_failed() {} }; +// 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 }; +}; + // a texture of the opengl renderer struct opengl_texture : public texture_source { // constructors @@ -180,6 +190,13 @@ struct opengl_texture : public texture_source { alloc_rendertarget( GLint format, GLint components, int width, int height, int layers = 1, int samples = 1, GLint wrap = GL_CLAMP_TO_EDGE ); 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(); // with gfx.resource.move, copies the gl texture back into the data before it's released. requires the texture bound bool read_back_compressed(); void read_back_uncompressed(); @@ -188,6 +205,10 @@ struct opengl_texture : public texture_source { get_id() const override { return id; } 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; bool resident() const override { return id != invalid_id; } @@ -203,6 +224,11 @@ struct opengl_texture : public texture_source { 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/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index b34d4d0bd..656425fa0 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -3395,6 +3395,8 @@ void opengl46_renderer::Bind_Material( material_handle const Material, TSubModel return; } + // 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++) diff --git a/rendering/particles.cpp b/rendering/particles.cpp index c80a52a6a..87fc7c0b5 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -175,9 +175,9 @@ smoke_source::accumulate_spawns( 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 8bab3113e..693aa7cea 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 f7a0633ef..81efa66f9 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) { @@ -96,7 +96,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; @@ -152,6 +152,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -194,6 +196,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 185afe920..7d9e7592a 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -33,8 +33,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/shaders/ogl46/postfx_motionblur.frag b/shaders/ogl46/postfx_motionblur.frag index c5f516576..e28953ebb 100644 --- a/shaders/ogl46/postfx_motionblur.frag +++ b/shaders/ogl46/postfx_motionblur.frag @@ -34,6 +34,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) diff --git a/shaders/vk14/postfx_motionblur.frag b/shaders/vk14/postfx_motionblur.frag index 557df5478..12d788008 100644 --- a/shaders/vk14/postfx_motionblur.frag +++ b/shaders/vk14/postfx_motionblur.frag @@ -36,6 +36,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index f8d7b2972..ba12ee4f7 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/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 25758a1fc..fcf8fb111 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # which textures the shadow maps draw without the alpha test "${CMAKE_SOURCE_DIR}/rendering/common/texturealpha.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_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_uphill_start.cpp b/tests/unit/test_uphill_start.cpp new file mode 100644 index 000000000..d450af68b --- /dev/null +++ b/tests/unit/test_uphill_start.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/uphillstart.h" + +// starting uphill, the train brake is applied further, a step at a time, until the brake of the unpowered vehicles +// holds the train without the locomotive brake (eu07/maszyna#396). the numbers are those of an ST43 with 37 empty +// wagons on 12.5 per mille: 1040 t, 128.6 kN of grade force, the wagons on G with about 22 s to apply + +using uphill_start::brake_top_up; +using uphill_start::top_up; +using uphill_start::top_up_action; + +namespace { + +double const grade{128600.0}; // [N] +double const application{22.0}; // [s] + +// the train standing with the brake handle at Position, held there long enough for the cylinders to fill, while +// each step adds Gain of brake force (as a multiple of the grade force) to the Start it had. runs the top-up until it +// lets the locomotive brake off, and returns the handle position it stopped at and the number of steps +struct outcome { + double position; + int steps; +}; +outcome run_top_up(double Start, double Gain, double Position = 1.25) { + top_up state; + auto force{Start * grade}; + auto steps{0}; + for (auto guard{0}; guard < 100; ++guard) { + auto const action{brake_top_up(state, force, grade, Position, application, application)}; + if (action == top_up_action::none) { + break; + } + REQUIRE(action == top_up_action::step); + Position += 0.25; + force += Gain * grade; + ++steps; + } + return {Position, steps}; +} + +} // namespace + +TEST_CASE("uphill start: a brake that holds the train isn't applied further") { + top_up state; + CHECK(brake_top_up(state, 1.1 * grade, grade, 1.25, application, application) == top_up_action::none); + CHECK(state.last_force < 0.0); +} + +TEST_CASE("uphill start: each step waits the full application time of the brake") { + top_up state; + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, 0.5 * application, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, application, application) == top_up_action::step); + // the handle has just moved + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, 0.0, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, application - 0.1, application) == top_up_action::wait); +} + +TEST_CASE("uphill start: a light application is topped up until the brake holds the train") { + // before Nowy Zagorz on linia_107_objazdy: 0.64 bar in the wagons, 128 kN against 129 kN + auto const result{run_top_up(0.995, 0.15)}; + CHECK(result.steps == 1); + CHECK(result.position == doctest::Approx(1.5)); +} + +TEST_CASE("uphill start: a brake that doesn't get stronger ends the top-up after one more step") { + // all the wagon brakes cut out: no step adds anything + auto const result{run_top_up(0.0, 0.0)}; + CHECK(result.steps == 1); + CHECK(result.position < uphill_start::top_up_position); +} + +TEST_CASE("uphill start: a brake that gets stronger by too little ends the top-up") { + // a step adds 1% of the grade force, below the 2% that counts + auto const result{run_top_up(0.3, 0.01)}; + CHECK(result.steps == 1); + SUBCASE("and one that gets stronger by enough goes on") { + auto const going{run_top_up(0.3, 0.05)}; + CHECK(going.steps > 1); + } +} + +TEST_CASE("uphill start: the top-up goes no further than full service") { + // every step adds enough to go on, but never enough to hold the train + auto const result{run_top_up(0.0, 0.03)}; + CHECK(result.position == doctest::Approx(uphill_start::top_up_position)); + CHECK(result.steps == 11); + top_up state; + CHECK(brake_top_up(state, 0.0, grade, uphill_start::top_up_position, application, application) == top_up_action::none); +} + +TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { + top_up state; + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.25, application, application) == top_up_action::step); + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.5, application, application) == top_up_action::none); + CHECK(state.done); + // the brake gets stronger later all the same: the start has gone on without the top-up + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::none); + // a new start begins with a new top-up + state = {}; + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); +} diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index f8cd9a290..3bcb565a8 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.h b/utilities/Globals.h index a05e364da..2998ca813 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -201,6 +201,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 958a3662c..7eb99ad7c 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 @@ -117,6 +118,8 @@ void LogService() std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); crashdump_set_log_file(crashdump_log_file::log, filename); + // 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/utilities.cpp b/utilities/utilities.cpp index f3a9f7390..9d5c614d7 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -165,11 +165,11 @@ double Random(double min, double max) return dist(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(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 7ea38be45..aa457b3d3 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); // the engine Random() draws from in the calling thread, in place of Global.random_engine, or none for that one again. the threads // of worker_pool have engines of their own: the one of the simulation can't be shared between threads void set_thread_random_engine(std::mt19937 *Engine); // NOSONAR: randomness of the simulation, not of anything security-relevant @@ -285,17 +290,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 2fdc3fd55..de012f039 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "world/mtable.h" #include "vehicle/DynObj.h" @@ -211,6 +212,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 }; @@ -327,6 +329,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -412,9 +417,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?) @@ -915,6 +929,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; } @@ -3749,7 +3764,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart ) { + if( bUphillStart && ( false == bUphillRelease ) ) { // starting uphill the train brake holds the train until the power does break; } @@ -6547,24 +6562,35 @@ TController::determine_consist_state() { ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - // starting uphill the power is applied against the train brake on purpose, until the power holds the train - auto const heldforstart { bUphillStart }; - if (Ready) { + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + auto const wasready { Ready }; + if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - vehicle->Vel < 1.0 ? + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - // ready all the same only at a standstill with the power going on against the brake on purpose; - // in motion a braking force left anywhere in the train (a hand brake) stops it as before - Ready = heldforstart && ( vehicle->Vel < 1.0 ); + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); } + } + if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken @@ -6581,7 +6607,8 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -6677,6 +6704,10 @@ TController::determine_consist_state() { && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony Ready = true; //żeby uznać za odhamowany } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8202,54 +8233,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 @@ -8276,43 +8259,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; @@ -8363,7 +8322,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 ) ); @@ -8787,6 +8746,12 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -8843,15 +8808,19 @@ void TController::control_uphill_start() { && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; false == uphill ) { - bUphillStart = false; + end_uphill_start(); return; } if( false == bUphillStart ) { if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; fUphillStartTime = ElapsedTime; } else { @@ -8860,31 +8829,86 @@ void TController::control_uphill_start() { } if( AccDesired <= EU07_AI_NOACCELERATION ) { // no longer to start: the standing rules take over - bUphillStart = false; + end_uphill_start(); return; } - if( velocity < -0.5 ) { - // rolling back all the same: the rules for a train slipping back take over and apply the brakes - bUphillStart = false; + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - auto tractiveforce { 0.0 }; + fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame - tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - auto const holdingforce { fMass * -fAccGravity }; - if( ( velocity > 1.0 ) - || ( tractiveforce > 1.1 * holdingforce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillStart = false; + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; } void TController::increase_tractive_force() { @@ -8958,10 +8982,17 @@ void TController::control_braking_force() { if( TestFlag( iDrivigFlags, movePress ) ) { return; } auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) ) { + && false == TestFlag(iDrivigFlags, movePress) + && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -9016,7 +9047,7 @@ void TController::control_braking_force() { else { // a stara wersja w miarę dobrze działa na składy wagonowe if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + || slippingbackuphill) && // also brake if uphill and slipping back (fBrakeTime < 0.0 // the size of the brake demand decides whether to skip the reaction time, so the brake-only part // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) diff --git a/vehicle/Driver.h b/vehicle/Driver.h index bfeeb1b16..62b326696 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "utilities/translation.h" #include "application/driverhints.h" +#include "vehicle/uphillstart.h" #include "vehicle/blackbox.h" auto const EU07_AI_ACCELERATION = 0.05; @@ -27,6 +28,7 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back +auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; enum TOrders @@ -164,6 +166,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 { @@ -336,6 +339,8 @@ private: bool uphill_stop_hold() const; bool uphill_brake_committed( double const Velocity ) const; void control_uphill_start(); + void end_uphill_start(); + bool uphill_brake_top_up(); std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -440,6 +445,14 @@ private: int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does double fUphillStartTime = 0.0; // when the uphill start began + bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released + bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off + uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further + double fUphillReleaseTime = 0.0; // when the release began + double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] + double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 2594b3c66..e5e387198 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -1114,7 +1115,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; } @@ -2382,6 +2383,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 /* @@ -2540,7 +2542,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" @@ -3138,7 +3140,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 @@ -3779,20 +3781,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; @@ -8251,6 +8254,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 @@ -8375,9 +8380,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 0e4d5000a..41601d3dc 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -919,6 +919,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 0644f1c30..ee1b07038 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9819,7 +9819,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); } @@ -9827,7 +9827,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); } @@ -9835,7 +9835,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); } @@ -11541,8 +11541,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/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp new file mode 100644 index 000000000..dd1895b11 --- /dev/null +++ b/vehicle/uphillstart.cpp @@ -0,0 +1,36 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/uphillstart.h" + +namespace uphill_start { + +top_up_action brake_top_up( + top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, + double const Applicationtime) { + + if (State.done || (Brakeforce >= holding_force * Holdingforce) || (Brakeposition >= top_up_position)) { + return top_up_action::none; + } + // each step is given the full application time of the train brake, for the cylinders along the train to fill + if (Heldtime < Applicationtime) { + return top_up_action::wait; + } + if ((State.last_force >= 0.0) && (Brakeforce - State.last_force < top_up_gain * Holdingforce)) { + // the last step added next to nothing: the brake of this train can't hold it (brakes cut out, a load setting + // too low), and the start goes on without + State.done = true; + return top_up_action::none; + } + State.last_force = Brakeforce; + return top_up_action::step; +} + +} // namespace uphill_start diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h new file mode 100644 index 000000000..108662cbe --- /dev/null +++ b/vehicle/uphillstart.h @@ -0,0 +1,41 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// starting uphill (TController::control_uphill_start()), the AI's driver lets the locomotive brake off only once +// the brake of the rest of the train holds the train on its own: a train stopped on a light application stands on +// the locomotive brake too, and rolls back as soon as it is off. until then the train brake is applied further, a +// step at a time +namespace uphill_start { + +auto const holding_force{1.1}; // a force that holds a train uphill, as a multiple of the grade force +auto const top_up_position{4.0}; // full service: the furthest the train brake is applied to hold the train +// a step that adds less brake force than this, as a multiple of the grade force, is the last one +auto const top_up_gain{0.02}; + +// what has been done to apply the train brake further, in one start +struct top_up { + double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] + bool done{false}; // a step added next to nothing: no more of them in this start +}; + +enum class top_up_action { + none, // the brake holds the train, or can't be made to: the start goes on + wait, // the cylinders are still filling after the last step + step // apply the train brake one step further +}; + +// Brakeforce: the brake force of the unpowered vehicles [N]; Holdingforce: the grade force on the train [N]; +// Brakeposition: the train brake handle, as BrakeCtrlPosition; Heldtime: how long the handle has been where it +// is [s]; Applicationtime: the time the train brake takes to apply, for the cylinders along the train to fill [s] +top_up_action brake_top_up( + top_up &State, double Brakeforce, double Holdingforce, double Brakeposition, double Heldtime, double Applicationtime); + +} // namespace uphill_start diff --git a/world/Segment.cpp b/world/Segment.cpp index 6be3f0a46..5da1d0ad7 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -435,8 +435,10 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; + glm::dvec3 result { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); return result; } @@ -471,7 +473,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; } @@ -510,7 +512,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist