From 267d5b3a8f5c01dbe77f25255c4237665f8e6efe Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:55:33 +0100 Subject: [PATCH 01/18] AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table since ce87aa0e (#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was before ce87aa0e and as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r --- CMakeLists.txt | 1 + tests/unit/test_braking_curve.cpp | 195 ++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 115 +++++------------- vehicle/Driver.h | 1 + vehicle/brakingcurve.cpp | 86 +++++++++++++ vehicle/brakingcurve.h | 54 +++++++++ 6 files changed, 366 insertions(+), 86 deletions(-) create mode 100644 tests/unit/test_braking_curve.cpp create mode 100644 vehicle/brakingcurve.cpp create mode 100644 vehicle/brakingcurve.h diff --git a/CMakeLists.txt b/CMakeLists.txt index f80a93d21..1d5c0ad33 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -554,6 +554,7 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp new file mode 100644 index 000000000..7102d06e0 --- /dev/null +++ b/tests/unit/test_braking_curve.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakingcurve.h" + +#include +#include + +// the deceleration the AI asks for on its way down to a stop or a lower speed ahead, outside of the final approach +// (TController::adjust_desired_speed_for_braking_curve). in shunting the brake table of the consist isn't worked out +// and stays at zero; planned from it, the curve asked for next to no braking, and shunting engines ran through the +// signals they were to stop at. + +namespace { + +auto constexpr tablesize{20}; +using brake_values = std::array; + +// what the AI holds in shunting: nothing worked out +struct zeroed_table { + brake_values a0{}; + brake_values a1{}; + + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 100.0}; } +}; + +// a train brake that gives the same deceleration at every speed, full service 0.05 + 12 * 0.1 = 1.25 m/s2 +struct flat_table { + brake_values a0{}; + brake_values a1{}; + + flat_table() { + a0.fill(0.05); + a1.fill(0.1); + } + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 120.0}; } +}; + +braking_curve::approach stop_at(double const Speed, double const Distance) { + braking_curve::approach approach{}; + approach.speed = Speed; + approach.target = 0.0; + approach.distance = Distance; + approach.offset = 0.0; // the braking point of a stop, outside of a train, is the stop itself (VelNext * multiplier) + approach.speedup_horizon = 30.0 / 3.6; + approach.fill_horizon = 30.0 / 3.6; + return approach; +} + +// the AI in shunting leaves the brake alone for a demand weaker than this (TController::fAccThreshold) +auto constexpr shunting_brake_threshold{-0.2}; + +struct shunting_run { + double speed; // [km/h] + double left; // to the stop point [m] + bool braked_at_once; +}; + +// a shunting engine braking to a stop point the way the AI drives it: the brake follows the demand once it is past +// the threshold, the engine coasts otherwise. the braking curve gives way near the point to the final approach, at +// walking pace (10 km/h, 5 km/h in the last 10 m) +shunting_run brake_to_point(double const Speed, double const Distance, zeroed_table const &Table) { + auto const table{Table.table()}; + auto const timestep{0.1}; + shunting_run run{Speed, Distance, false}; + run.braked_at_once = braking_curve::demand(stop_at(run.speed, run.left), &table) < shunting_brake_threshold; + while ((run.speed > (run.left > 10.0 ? 10.0 : 5.0)) && (run.left > -50.0)) { + auto const demand{braking_curve::demand(stop_at(run.speed, run.left), &table)}; + auto const acceleration{demand < shunting_brake_threshold ? demand : 0.0}; + run.speed = std::max(0.0, run.speed + 3.6 * acceleration * timestep); + run.left -= run.speed / 3.6 * timestep; + } + return run; +} + +} // namespace + +TEST_CASE("braking curve: a brake table left at zero isn't known, one worked out is") { + CHECK_FALSE(zeroed_table{}.table().known()); + CHECK(flat_table{}.table().known()); +} + +TEST_CASE("braking curve: shunting to a point asks for the constant deceleration over the distance left") { + zeroed_table const shunting; + auto const table{shunting.table()}; + auto approach{stop_at(33.0, 186.0)}; + SUBCASE("coasting") { approach.acceleration = 0.0; } + SUBCASE("still speeding up") { approach.acceleration = 0.2; } + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(-33.0 * 33.0 / (25.92 * 186.0 + 0.1))); + CHECK(demand == doctest::Approx(braking_curve::demand(approach, nullptr))); + // enough for the AI to put the brake on + CHECK(demand < shunting_brake_threshold); +} + +TEST_CASE("braking curve: a shunting engine braking to a point gets down to walking pace short of it") { + zeroed_table const shunting; + auto speed{0.0}; + auto distance{0.0}; + SUBCASE("33 km/h, 186 m") { + speed = 33.0; + distance = 186.0; + } + SUBCASE("40 km/h, 186 m") { + speed = 40.0; + distance = 186.0; + } + SUBCASE("33 km/h, 120 m") { + speed = 33.0; + distance = 120.0; + } + SUBCASE("25 km/h, 60 m") { + speed = 25.0; + distance = 60.0; + } + CAPTURE(speed); + CAPTURE(distance); + + auto const run{brake_to_point(speed, distance, shunting)}; + + CHECK(run.braked_at_once); + CHECK(run.left > 0.0); + CHECK(run.speed <= 10.0); +} + +TEST_CASE("braking curve: a train with a worked out brake table plans along the shape of its brake") { + flat_table const train; + auto const table{train.table()}; + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.fill_horizon = 6.0; + approach.speedup_horizon = 5.0; + + SUBCASE("before the brake is applied, the room it takes to fill is kept") { + auto const room{580.0 - 80.0 / 3.6 * 6.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, room + 0.1 / 25.92, 0.0, table))); + // with the same deceleration at every speed the shape is the constant deceleration over that room + CHECK(demand == doctest::Approx(-(80.0 / 3.6) * (80.0 / 3.6) / (2.0 * room)).epsilon(0.01)); + } + SUBCASE("once the brake is applied, the whole distance is used") { + approach.brake_applied = true; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, 580.0 + 0.1 / 25.92, 0.0, table))); + } + SUBCASE("still speeding up, it plans from the speed reached once the brake acts") { + approach.acceleration = 0.3; + auto const reached{80.0 + 3.6 * 5.0 * 0.3}; + auto const distance{600.0 - (80.0 + reached) * 0.5 / 3.6 * 5.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(reached, 0.0, distance - 20.0 + 0.1 / 25.92, 0.0, table))); + } +} + +TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { + // a table that grips harder as the train slows, on a gradient; the demands were worked out with the + // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) + brake_values a0{}; + brake_values a1{}; + for (auto i{1}; i <= tablesize; ++i) { + a0[i] = 0.12 - 0.003 * i; + a1[i] = 0.06 - 0.001 * i; + } + braking_curve::brake_table const table{a0.data(), a1.data(), tablesize, 120.0}; + REQUIRE(table.full_braking(80.0) == doctest::Approx(0.645)); + REQUIRE(table.full_braking(10.0) == doctest::Approx(0.825)); + + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.gravity = 0.1; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + auto expected{0.0}; + SUBCASE("downhill, coasting, the brake still to be applied") { expected = -0.4926656801067293; } + SUBCASE("downhill, the brake applied") { + approach.brake_applied = true; + expected = -0.37739905908238147; + } + SUBCASE("downhill, still speeding up") { + approach.acceleration = 0.3; + expected = -0.5330117415264249; + } + SUBCASE("uphill, down to 40 km/h") { + approach = stop_at(100.0, 900.0); + approach.target = 40.0; + approach.gravity = -0.08; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + expected = -0.40930710539221765; + } + + CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 07eaf4575..0d80e105f 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "world/mtable.h" #include "vehicle/DynObj.h" @@ -210,6 +211,7 @@ void TSpeedPos::Clear() fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; fDist = 0.0; + bSeenAhead = false; vPos = glm::dvec3(0, 0, 0); trTrack = nullptr; // brak wskaźnika }; @@ -326,6 +328,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -411,9 +416,18 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } +// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] +constexpr double SeenAheadTolerance { 5.0 }; + bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) { // zapamiętanie zdarzenia fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the + // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head + // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than + // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't + // be told from one stopped just short of it, which really passes the signal if it goes on + bSeenAhead = ( dist >= -SeenAheadTolerance ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -908,6 +922,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { if( Passedbefore || false == TestFlag( Point.iFlags, spElapsed ) + || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -8189,54 +8204,6 @@ uphill_coasting_speed( double const Distance, double const Gravity ) { return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); } -// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train -// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the -// consist brake table says it does (cast iron blocks grip harder as the train slows) -struct consist_brake_table { - double const *a0; // deceleration at handle position 1, by speed - double const *a1; // deceleration added by each quarter of a position, by speed - int size; // entries, up to the vehicle's top speed - double vmax; // the vehicle's top speed [km/h] - - // deceleration [m/s2] of a full service application at Kmh - double full_braking( double const Kmh ) const { - auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) }; - return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); } -}; - -static double -shaped_braking_demand( - double const Velocity, double const Target, double const Distance, double const Gravity, - consist_brake_table const &Table ) { - - auto const fullbraking = [&Table]( double const Kmh ) { - return Table.full_braking( Kmh ); }; - auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) { - auto const steps { 24 }; - auto const step { ( Velocity - Target ) / steps }; - auto distance { 0.0 }; - for( auto i { 0 }; i < steps; ++i ) { - auto const kmh { Target + ( i + 0.5 ) * step }; - auto const deceleration { Ratio * fullbraking( kmh ) - Gravity }; - if( deceleration <= 0.001 ) { - return std::numeric_limits::max(); - } - distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration; - } - return distance; }; - - auto low { 0.0 }; - auto high { 3.0 }; - if( travel( high ) > Distance ) { - return Gravity - high * fullbraking( Velocity ); - } - for( auto i { 0 }; i < 30; ++i ) { - auto const middle { 0.5 * ( low + high ) }; - ( travel( middle ) > Distance ? low : high ) = middle; - } - return Gravity - high * fullbraking( Velocity ); -} - // outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the // direction of travel void @@ -8263,43 +8230,19 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? stopping_margin() : // the same stopping point as the final approach VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // a pneumatic brake acts on the state the train will be in once it has responded; while the - // train is still speeding up, plan the deceleration from there, so more is asked for at once - auto velocity { Vel }; - auto distance { ActualProximityDist }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AbsAccS > 0.0 ) ) { - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - velocity = Vel + 3.6 * horizon * AbsAccS; - distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon ); - } - auto const brakingroom { - std::max( - distance - brakingpointoffset, - std::min( - distance, - brakingpointoffset ) ) }; - auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) { - // follow the shape of the consist brake force over speed rather than assume a constant - // deceleration, over the distance left once the brake has had time to fill (while the - // train is still speeding up, the prediction above has taken that off already) - auto room { brakingroom }; - if( ( AbsAccS <= 0.0 ) - && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const brakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - room = std::max( - 0.5 * brakingroom, - brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, brakea0 ) ); - } - deceleration = shaped_braking_demand( - velocity, VelNext, room + 0.1 / 25.92, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ); - } + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { return; @@ -8350,7 +8293,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { AccDesired = ( BrakeSystem == TBrakeSystem::Pneumatic ? // cast iron blocks grip harder as the train comes to a stand - shaped_braking_demand( + braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index bfeeb1b16..0794799dc 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -164,6 +164,7 @@ class TSpeedPos int iFlags{ spNone }; // flagi typu wpisu do tabelki bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) + bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train glm::dvec3 vPos; // współrzędne XYZ do liczenia odległości struct { diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp new file mode 100644 index 000000000..d39ee2868 --- /dev/null +++ b/vehicle/brakingcurve.cpp @@ -0,0 +1,86 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakingcurve.h" + +#include +#include + +namespace braking_curve { + +double brake_table::full_braking(double const Kmh) const { + auto const index{std::clamp(static_cast(size * Kmh / std::max(1.0, vmax)), 1, size)}; + return std::max(0.01, a0[index] + 12.0 * a1[index]); +} + +bool brake_table::known() const { + // a worked out table holds at least the rolling resistance term at every speed + return a0[size] > 0.0; +} + +double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { + + auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { + auto const steps{24}; + auto const step{(Velocity - Target) / steps}; + auto distance{0.0}; + for (auto i{0}; i < steps; ++i) { + auto const kmh{Target + (i + 0.5) * step}; + auto const deceleration{Ratio * Table.full_braking(kmh) - Gravity}; + if (deceleration <= 0.001) { + return std::numeric_limits::max(); + } + distance += (kmh / 3.6) * (step / 3.6) / deceleration; + } + return distance; + }; + + auto low{0.0}; + auto high{3.0}; + if (travel(high) > Distance) { + return Gravity - high * Table.full_braking(Velocity); + } + for (auto i{0}; i < 30; ++i) { + auto const middle{0.5 * (low + high)}; + (travel(middle) > Distance ? low : high) = middle; + } + return Gravity - high * Table.full_braking(Velocity); +} + +double demand(approach const &Approach, brake_table const *Pneumatictable) { + + // a pneumatic brake acts on the state the train will be in once it has responded; while the + // train is still speeding up, plan the deceleration from there, so more is asked for at once + // both plans are made from the brake table of the consist; with none (in shunting it isn't worked out, and planning + // from its zeroes would ask for no braking at all) the braking curve is the constant deceleration over the distance left + auto const *table{(Pneumatictable != nullptr) && Pneumatictable->known() ? Pneumatictable : nullptr}; + auto velocity{Approach.speed}; + auto distance{Approach.distance}; + if ((table != nullptr) && (Approach.acceleration > 0.0)) { + auto const horizon{Approach.speedup_horizon}; + velocity = Approach.speed + 3.6 * horizon * Approach.acceleration; + distance = std::max(0.5 * Approach.distance, Approach.distance - (Approach.speed + velocity) * 0.5 / 3.6 * horizon); + } + auto const brakingroom{std::max(distance - Approach.offset, std::min(distance, Approach.offset))}; + if ((table == nullptr) || (velocity <= Approach.target)) { + return (Approach.target * Approach.target - velocity * velocity) / (25.92 * brakingroom + 0.1); + } + // follow the shape of the consist brake force over speed rather than assume a constant + // deceleration, over the distance left once the brake has had time to fill (while the + // train is still speeding up, the prediction above has taken that off already) + auto room{brakingroom}; + if ((Approach.acceleration <= 0.0) && (false == Approach.brake_applied)) { + // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + room = std::max(0.5 * brakingroom, brakingroom - Approach.speed / 3.6 * Approach.fill_horizon); + } + return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); +} + +} // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h new file mode 100644 index 000000000..6ed40d9bb --- /dev/null +++ b/vehicle/brakingcurve.h @@ -0,0 +1,54 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the deceleration the AI asks for on its way down to a lower speed or a stop ahead, outside of the final +// approach (TController::adjust_desired_speed_for_braking_curve) +namespace braking_curve { + +// the deceleration table of the consist brake, by speed (TController::fBrake_a0, fBrake_a1). it is worked out +// for a train only (Obey_train, Bank); in shunting it stays at zero +struct brake_table { + double const *a0; // deceleration at handle position 1, by speed; a0[1..size] + double const *a1; // deceleration added by each quarter of a position, by speed + int size; // entries, up to the vehicle's top speed + double vmax; // the vehicle's top speed [km/h] + + // deceleration [m/s2] of a full service application at Kmh + double full_braking(double Kmh) const; + // whether the table is worked out + bool known() const; +}; + +// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train +// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the +// table says it does (cast iron blocks grip harder as the train slows) +double shaped_demand(double Velocity, double Target, double Distance, double Gravity, brake_table const &Table); + +// where the train is on its way down to Target +struct approach { + double speed; // present speed in the direction of travel [km/h] + double target; // speed to get down to [km/h] + double distance; // to where the speed is to be down [m] + double offset; // the braking point that far short of it [m] + double gravity; // tangential acceleration of the gradient [m/s2], negative uphill + double acceleration; // present acceleration of the train [m/s2] + bool brake_applied; // the train brake handle is past running + double speedup_horizon; // how long the present acceleration lasts while speeding up [s] + double fill_horizon; // how long the brake takes to fill once applied [s] +}; + +// acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake +// (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has +// responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at +// zero, as in shunting) it is the constant deceleration over the distance left +double demand(approach const &Approach, brake_table const *Pneumatictable); + +} // namespace braking_curve From 8bda0275f3e8bacd66c6280848c975f874e4b7c8 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:24:28 +0100 Subject: [PATCH 02/18] fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414) 623c4f82 (#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r --- vehicle/Camera.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index e2fe58464..55d4691d1 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -192,9 +192,12 @@ void TCamera::Update() bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { + // the roll (z) is multiplied in first, so it acts last, about the line of sight: the sway of the cab tilts the view + // the same way wherever the head is turned, as it did in 26.05. the order matters only with a roll (the cab shake, + // or the angles of a camera entry of the scenery) + Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia - Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie if( m_owner != nullptr && false == DebugCameraFlag ) { From 4b80d3c4285f278d2b5f08f01e6013c0def17dc0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:24:42 +0100 Subject: [PATCH 03/18] fix(particles): the smoke of a cold diesel keeps the colour of its template (#413) bcb9e644 (#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r --- rendering/particles.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 8ccb728dd..517fec751 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -168,9 +168,9 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { if( m_ownertype == owner_type::vehicle ) { auto const &mover { *m_owner.vehicle->MoverParameters }; - if( Global.AirTemperature <= 5.f || mover.dizel_heat.Ts < 45.f ) { - m_emitter.color = glm::vec3{ 128, 128, 128 }; - } + // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant + // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the + // emitter colour, so the smoke turned pure white, glowing at night, and never changed back // a vehicle taken off the tracks (gone through a portal, or waiting in the pool of the road traffic) puffs no more, // the particles it already let out fade away as usual m_spawncount = ( From 72c69d9249cbffb09ee079522f4b9fa32cb0e5f0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:01 +0100 Subject: [PATCH 04/18] Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and since e230d7b9 it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r --- application/application.cpp | 36 ++++++++++++++++++++++++++++++++++ model/Texture.cpp | 28 +++++++++++++++++++++++--- model/Texture.h | 10 ++++++++++ rendering/opengl33renderer.cpp | 2 ++ 4 files changed, 73 insertions(+), 3 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index b8decc5f1..12bc9020a 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -54,6 +54,7 @@ http://mozilla.org/MPL/2.0/. #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "version.lib") +#include #endif #ifdef __unix__ @@ -65,6 +66,36 @@ eu07_application Application; screenshot_manager screenshot_man; ui_layer uilayerstaticinitializer; +namespace +{ +#ifdef _WIN32 +// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms. +// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up +// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or +// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the +// main loop, as it costs some power for as long as it's held +bool timer_period_set{false}; +#endif + +// asks for the finer timer once, when fpslimit is set +void begin_timer_period() +{ +#ifdef _WIN32 + if (!timer_period_set && Global.minframetime.count() > 0.f) + timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR); +#endif +} + +void end_timer_period() +{ +#ifdef _WIN32 + if (timer_period_set) + timeEndPeriod(1); + timer_period_set = false; +#endif +} +} // namespace + #ifdef _WIN32 extern "C" { @@ -352,6 +383,8 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; } + // fpslimit is known now + begin_timer_period(); // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is @@ -686,6 +719,8 @@ int eu07_application::run() // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { + // fpslimit may come from the config block of the scenery, read after the settings + begin_timer_period(); std::this_thread::sleep_until(*nextframe); } } @@ -782,6 +817,7 @@ void eu07_application::exit() if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + end_timer_period(); step("done"); StopLogService(); auto it = Global.threads.find("LogService"); diff --git a/model/Texture.cpp b/model/Texture.cpp index 9b428202b..bd13ecf2c 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -323,6 +323,7 @@ GLint readback_format( GLint const Internalformat ) { std::array opengl_texture::units = { 0 }; GLint opengl_texture::m_activeunit = -1; +std::atomic opengl_texture::m_unitcachestale { false }; std::unordered_map opengl_texture::precompressed_formats = { @@ -729,9 +730,10 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 is_static = true; is_ready = true; } - // the name may be a new one, and the unit active took the texture past the unit cache - for (auto &unit : units) - unit = -1; + // the name may be a new one, and the unit active took the texture past the unit cache. this runs on the python upload + // thread too (python.threadedupload), so the cache is only marked here: clearing it outright raced the drawing thread + // filling it for a multi-bind, and an object got the texture of the one drawn before it for a frame + invalidate_unit_cache(); } void @@ -1263,6 +1265,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; if (GLAD_GL_ARB_direct_state_access) @@ -1630,6 +1633,25 @@ opengl_texture::reset_unit_cache() { m_activeunit = -1; } +void +opengl_texture::invalidate_unit_cache() { + + m_unitcachestale.store( true ); +} + +void +opengl_texture::sync_unit_cache() { + + // a plain load first: bind() calls this for every texture, and a read-modify-write each time would cost more + if( ( false == m_unitcachestale.load() ) + || ( false == m_unitcachestale.exchange( false ) ) ) { + return; + } + for( auto &unit : units ) { + unit = -1; + } +} + void opengl_texture::set_filtering() const { diff --git a/model/Texture.h b/model/Texture.h index 20221fcea..2fbd76a4f 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include "winheaders.h" @@ -47,6 +48,13 @@ struct opengl_texture : public ITexture { set_components_hint( GLint hint ) override; static void reset_unit_cache(); + // marks the unit cache as not to be trusted. safe to call from any thread: the cache itself is + // cleared by the thread drawing with it, the next time it binds textures (sync_unit_cache) + static void + invalidate_unit_cache(); + // clears the unit cache if a thread marked it as not to be trusted since. called before the cache is read + static void + sync_unit_cache(); virtual int get_width() const override { return data_width; } @@ -100,6 +108,8 @@ struct opengl_texture : public ITexture { GLenum target = GL_TEXTURE_2D; static std::array units; static GLint m_activeunit; + // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread + static std::atomic m_unitcachestale; public: // methods diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..80ef4f670 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2457,6 +2457,8 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel if (GLAD_GL_ARB_multi_bind) { + // the cache may have been marked stale by the python upload thread + opengl_texture::sync_unit_cache(); GLuint lastdiff = 0; size_t i; for (i = 0; i < gl::MAX_TEXTURES; i++) From a1fbdf47c6c9bc1808a08ef8d52eaeeb2d7939c3 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:03 +0100 Subject: [PATCH 05/18] fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r --- application/drivermode.cpp | 19 +++++++++++++++---- application/drivermode.h | 1 + vehicle/DynObj.cpp | 31 +++++++++++++++++++++++++++++-- vehicle/DynObj.h | 5 +++++ 4 files changed, 50 insertions(+), 6 deletions(-) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index cde7e80d7..8c3b3665f 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" + +#include + /* namespace input { @@ -627,6 +630,12 @@ bool driver_mode::is_command_processor() const return true; } +double driver_mode::shake_fraction() const +{ + // how far the simulation time has got from the last step of the shake towards the next one + return std::clamp(m_secondaryupdateaccumulator / m_secondaryupdaterate, 0.0, 1.0); +} + void driver_mode::update_camera(double const Deltatime) { @@ -770,7 +779,8 @@ void driver_mode::update_camera(double const Deltatime) // ale bez odbicia Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 } - auto const shakeangles{simulation::Train->Dynamic()->shake_angles()}; + auto const *dynamic{simulation::Train->Dynamic()}; + auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* @@ -791,8 +801,9 @@ void driver_mode::update_camera(double const Deltatime) } float const shakescale{FreeFlyModeFlag ? 5.0f : 1.0f}; - auto shakencamerapos{Camera.m_owneroffset + - shakescale * glm::vec3(1.5 * Camera.m_owner->ShakeState.offset.x, 2.0 * Camera.m_owner->ShakeState.offset.y, 1.5 * Camera.m_owner->ShakeState.offset.z)}; + // the shake steps at a fixed rate, the frames come at their own: taken at the frame's moment between the steps, it moves as smoothly as the vehicle + auto const shake{Camera.m_owner->shake_between(shake_fraction())}; + auto shakencamerapos{Camera.m_owneroffset + shakescale * glm::vec3(1.5 * shake.offset.x, 2.0 * shake.offset.y, 1.5 * shake.offset.z)}; Camera.Pos = Camera.m_owner->GetWorldPosition(FreeFlyModeFlag ? glm::dvec3(shakencamerapos) : // TODO: vehicle collision box for the external vehicle camera simulation::Train->clamp_inside(shakencamerapos)); @@ -800,7 +811,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index e0406043d..06ce32ee4 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -91,6 +91,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..453dd743a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -2369,6 +2370,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ShakeSpring.Init( 125.0 ); BaseShake = baseshake_config {}; ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; // McZapkie-250202 /* @@ -8236,6 +8238,8 @@ void TDynamicObject::OverheadTrack(float o) void TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu @@ -8360,9 +8364,32 @@ TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int con std::pair TDynamicObject::shake_angles() const { + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + return { - std::atan( ShakeState.velocity.x * BaseShake.angle_scale.x ), - std::atan( ShakeState.velocity.z * BaseShake.angle_scale.z ) }; + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } void diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..3089258e6 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -918,6 +918,11 @@ public: glm::dvec3 velocity{}; // current shaking vector glm::dvec3 offset{}; // overall shake-driven offset from base position } ShakeState; + shake_state ShakeStateBefore; // the state before the last step of update_shake + // the shake between the last two steps of update_shake: 0 the state before the last step, 1 the state after it. + // the steps are fixed and the frames aren't, so the camera takes the state at its own moment between the two + shake_state shake_between( double const Fraction ) const; + std::pair shake_angles( shake_state const &State ) const; glm::dvec3 modelShake; }; From 1b26caca2455e7f106e836b89bd6183c7bd46978 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:29 +0100 Subject: [PATCH 06/18] fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1 d1f16411 (#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again; fa2ed089 swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as before d1f16411. The call added since (stepped_uc_value, 00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers and go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged is included twice, which is harmless. --------- Co-authored-by: maj00r --- McZapkie/Mover.cpp | 34 ++++++++++++++++++---------------- rendering/opengl33renderer.cpp | 2 +- rendering/openglparticles.cpp | 4 +++- rendering/openglrenderer.cpp | 4 ++-- tests/unit/test_utilities.cpp | 29 +++++++++++++++++++++++++---- utilities/utilities.h | 17 +++++++++-------- vehicle/DynObj.cpp | 19 ++++++++++--------- vehicle/Train.cpp | 13 ++++++++----- 8 files changed, 76 insertions(+), 46 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..15aa396c2 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -900,7 +900,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem PantPress = ScndPipePress; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = std::clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else @@ -912,7 +912,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } - PantPress = std::clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s @@ -3950,7 +3950,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not auto const initialstate{CompressorListPos}; - CompressorListPos = std::clamp(State, 0, CompressorListPosNo); + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); if (Notify != range_t::local) { @@ -5602,7 +5602,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; @@ -5900,7 +5900,7 @@ double TMoverParameters::TractionForce(double dt) if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -7755,7 +7755,9 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr { Progress = 0.0; } - return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); } } // namespace @@ -7839,18 +7841,18 @@ void TMoverParameters::CheckEIMIC(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -7957,7 +7959,7 @@ void TMoverParameters::CheckEIMIC(double dt) eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } void TMoverParameters::CheckSpeedCtrl(double dt) @@ -8015,7 +8017,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -8944,7 +8946,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun } LoadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); ComputeMass(); return true; } @@ -8989,7 +8991,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam { // pusto lub rozładowano żądaną ilość LoadStatus = 4; // skończony rozładunek - LoadAmount = std::clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny } if (LoadAmount == 0.f) { @@ -12853,7 +12855,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); return OK; } @@ -13255,7 +13257,7 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "DoorPermit") diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 80ef4f670..3a3008a44 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -4340,7 +4340,7 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) }; if( Lightlevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place - light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * std::clamp( 1.25f - (float)luminance, 0.f, 1.f ) ); + light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ); light_ubo->update( light_ubs ); } diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 3b8de9469..706e5d871 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -65,7 +65,9 @@ opengl_particles::update( opengl_camera const &Camera ) { vertex.color[ 0 ] = static_cast( particlecolor.r ); vertex.color[ 1 ] = static_cast( particlecolor.g ); vertex.color[ 2 ] = static_cast( particlecolor.b ); - vertex.color[ 3 ] = static_cast( std::clamp( particle.opacity * 255, 0.f, 255.f ) ); + // as up to 26.05.1, when clamp made the alpha a byte before clamping it: an opacity over 1 wraps + // round. through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion + vertex.color[ 3 ] = static_cast( static_cast( particle.opacity * 255 ) ); auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 5083c6f2f..8bef3352d 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -4370,8 +4370,8 @@ glm::dvec3 opengl_renderer::Update_Mouse_Position() { glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size; - mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 ); - mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); + mousepos.x = safe_clamp( mousepos.x, 0, Global.fb_size.x - 1 ); + mousepos.y = safe_clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); GLfloat pointdepth; ::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth ); diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index f8cd9a290..d26472248 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -2,6 +2,9 @@ #include "doctest.h" #include "scratch.h" +#include +#include + #include "utilities/Globals.h" #include "utilities/utilities.h" @@ -681,12 +684,30 @@ TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one" CHECK(Round(-2.5) == -2); } -TEST_CASE("utilities: a value is kept within bounds, given in any order") { +TEST_CASE("utilities: a value is kept within bounds; inverted bounds give the upper one, as the old clamp did") { CHECK(safe_clamp(5, 0, 3) == 3); - CHECK(safe_clamp(5, 3, 0) == 3); - CHECK(safe_clamp(-1, 3, 0) == 0); - CHECK(safe_clamp(2.0, 3.0, 1.0) == 2.0); + CHECK(safe_clamp(-1, 0, 3) == 0); + CHECK(safe_clamp(2, 0, 3) == 2); CHECK(safe_clamp(2.0, 2.0, 2.0) == 2.0); + // inverted bounds: always the upper bound, whatever the value + CHECK(safe_clamp(5, 3, 0) == 0); + CHECK(safe_clamp(-1, 3, 0) == 0); + CHECK(safe_clamp(2.0, 3.0, 1.0) == 1.0); + // NaN as the old clamp had it: a NaN value stays NaN, a NaN bound doesn't clamp + auto const notanumber{std::numeric_limits::quiet_NaN()}; + CHECK(std::isnan(safe_clamp(notanumber, 0.0, 1.0))); + CHECK(safe_clamp(2.0, 0.0, notanumber) == 2.0); + CHECK(safe_clamp(-1.0, notanumber, 1.0) == -1.0); + // what the helper gives for arguments in the order and of the signs of two calls (these checks don't call + // them): the AI braking test, whose demand is the stronger of the two (negative) bounds, as up to 26.05.1 + double const threshold{-0.45}; + CHECK(safe_clamp(0.3, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + CHECK(safe_clamp(-0.6, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + // and the bump at a rail joint, 0 in place of the value as up to 26.05.1: the figure is capped from above + // only, and above 68% of the top speed it is negative + CHECK(safe_clamp(0.0, 160.0, 160.0 - (150.0 + 160.0 * 0.32)) == doctest::Approx(-41.2)); + CHECK(safe_clamp(0.0, 4.0, -0.5) == -0.5); + CHECK(safe_clamp(0.0, 4.0, 5.0) == 4.0); } TEST_CASE("utilities: a value is wrapped into a range, as an angle into the full circle") { diff --git a/utilities/utilities.h b/utilities/utilities.h index 09c02d7fb..8c4181475 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -282,17 +282,18 @@ template bool is_equal(T const &Left, T const &Right, T const Epsil return Left == Right; } -// Tolerant clamp. Unlike std::clamp, this does NOT invoke undefined behaviour when -// the bounds are inverted (Lo > Hi) - it normalizes them instead. This restores the -// pre-refactor behaviour of the old custom clamp() for code paths where the bounds are -// computed at runtime and can legitimately cross (e.g. AI acceleration/braking limits, -// physics jolt calculations), where std::clamp's UB produced wrong results. +// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike +// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted +// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted +// bounds give the upper bound, as the old clamp() did. Every call of the old clamp() +// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are +// computed from such values) uses it, so it gives what it gave before the move to +// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same. +// New code uses std::clamp. template constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi ) { - return ( Hi < Lo ) - ? std::clamp( Value, Hi, Lo ) - : std::clamp( Value, Lo, Hi ); + return std::min( std::max( Value, Lo ), Hi ); } // keeps the provided value in specified range 0-Range, as if the range was circular buffer diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 453dd743a..757930596 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -1102,7 +1102,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) continue; } - auto const dist { std::clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -2529,7 +2529,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = std::clamp( + fAxleDist = safe_clamp( std::max( MoverParameters->BDist, MoverParameters->ADist ), 0.2, //żeby się dało wektory policzyć MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" @@ -3127,7 +3127,7 @@ TDynamicObject::update_load_offset() { 0.0 : 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, loadpercentage * 0.01, 1.0 ) ); + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void @@ -3766,20 +3766,21 @@ bool TDynamicObject::Update(double dt, double dt1) // crude bump simulation, drop down on even axles, move back up on // the odd ones // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - double const headroom = std::clamp( - MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ), - 0.0, MoverParameters->Vmax ); + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { - double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1); + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); MoverParameters->AccS += accHorizontal; MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } ++axleindex; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..41ee88ea5 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9760,7 +9760,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = std::clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9768,7 +9768,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = std::clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9776,7 +9776,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = std::clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -11390,8 +11390,11 @@ glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const return Point; } - return {std::clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), std::clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - std::clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; } const TTrain::screenentry_sequence &TTrain::get_screens() From 79c88c1793b7569132c1f55199035642f5688920 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:42 +0100 Subject: [PATCH 07/18] Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of 8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of 939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r --- global_include/interfaces/ITexture.h | 13 ++++ model/Texture.cpp | 95 ++++++++++++++++++++++++++++ model/Texture.h | 17 +++++ scripting/PyInt.cpp | 65 ++++++++++++++----- scripting/PyInt.h | 11 ++++ scripting/pythonscreenviewer.cpp | 16 ++++- scripting/pythonscreenviewer.h | 4 ++ 7 files changed, 204 insertions(+), 17 deletions(-) diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index ce123829f..f5b4d29a5 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -21,6 +21,19 @@ struct ITexture virtual void set_components_hint(int hint) = 0; virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) = 0; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; + // uploads an image from a thread with a gl context of its own, sharing the objects with the drawing one. a texture that + // can keeps the image apart until commit_thread_upload(), called on the drawing thread, puts it in place + virtual void upload_from_thread(size_t width, size_t height, const uint8_t *data) + { + update_from_memory(width, height, data); + } + // puts in place the image of the last upload_from_thread() once the gpu has it, without waiting for it. called on the + // drawing thread; false while the upload isn't done yet, to be asked again later + virtual bool commit_thread_upload() + { + // the image went in place right away + return true; + } static ITexture *null_texture() { struct NullTexture : public ITexture diff --git a/model/Texture.cpp b/model/Texture.cpp index bd13ecf2c..bba3ba763 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -736,6 +737,100 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 invalidate_unit_cache(); } +namespace +{ +// gl objects of an image uploaded by another thread that was never put in place +void delete_thread_upload(GLuint const Texture, GLsync const Fence) +{ + if (Fence != nullptr) + glDeleteSync(Fence); + glDeleteTextures(1, &Texture); +} +} // namespace + +void opengl_texture::upload_from_thread(size_t width, size_t height, const uint8_t *raw) +{ + // a texture of its own each time: the one drawn from may be in use by the gpu for the drawing context, and writing it from + // here, with nothing to order the two contexts, could leave it incomplete or half written for a frame + texture_thread_upload upload; + upload.width = width; + upload.height = height; + glGenTextures(1, &upload.id); + glBindTexture(target, upload.id); + set_filtering(); + glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap_mode_s); + glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap_mode_t); + if (!glGenerateMipmap) + glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); + glTexImage2D(target, 0, GL_SRGB8_ALPHA8, static_cast(width), static_cast(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, raw); + if (glGenerateMipmap) + glGenerateMipmap(target); + glBindTexture(target, 0); + if (glFenceSync) + { + upload.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + } + if (upload.fence == nullptr) + { + // no sync objects, or no fence made: the drawing context can only be sure of the image once the upload is done + glFinish(); + } + else + { + // the drawing context asks for the fence, which signals only once it is on its way to the gpu + glFlush(); + } + + std::optional superseded; + { + std::scoped_lock lock{m_threaduploadmutex}; + superseded = std::exchange(m_threadupload, upload); + } + if (superseded.has_value()) + { + // the drawing thread didn't take it, so nothing drew from it + delete_thread_upload(superseded->id, superseded->fence); + } +} + +bool opengl_texture::commit_thread_upload() +{ + texture_thread_upload upload; + { + std::scoped_lock lock{m_threaduploadmutex}; + if (false == m_threadupload.has_value()) + return true; + // asked without waiting. the image goes in place only once the upload is done, so every context binding it after + // has it whole: the extra viewports and the windows of python.displaywindows draw in contexts of their own + if (m_threadupload->fence != nullptr) + { + // a failed query (GL_WAIT_FAILED) isn't asked again: the image would never go in place + if (glClientWaitSync(m_threadupload->fence, 0, 0) == GL_TIMEOUT_EXPIRED) + return false; + glDeleteSync(m_threadupload->fence); + } + upload = *m_threadupload; + m_threadupload.reset(); + } + + if (id != invalid_id) + glDeleteTextures(1, &id); + id = upload.id; + data_width = static_cast(upload.width); + data_height = static_cast(upload.height); + data_format = GL_SRGB8_ALPHA8; + data_components = GL_RGBA; + if (type == "internalsrc:") + { + is_static = true; + is_ready = true; + } + // the name deleted may come back for another texture, and a deleted texture isn't bound any more + for (auto &unit : units) + unit = -1; + return true; +} + void opengl_texture::make_request() { diff --git a/model/Texture.h b/model/Texture.h index 2fbd76a4f..3934565a5 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include "winheaders.h" #include #include "model/ResourceManager.h" @@ -20,6 +22,14 @@ http://mozilla.org/MPL/2.0/. struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming +// an image uploaded by another thread into a texture of its own, waiting for the drawing thread to put it in place +struct texture_thread_upload { + GLuint id { 0 }; + GLsync fence { nullptr }; // set after the upload in the uploading context; none where the driver has no sync objects + size_t width { 0 }; + size_t height { 0 }; +}; + struct opengl_texture : public ITexture { static DDSURFACEDESC2 deserialize_ddsd(std::istream&); static DDCOLORKEY deserialize_ddck(std::istream&); @@ -93,6 +103,10 @@ struct opengl_texture : public ITexture { virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override; + // the image goes into a texture of its own, and the drawing thread swaps it in after the gpu has it (commit_thread_upload). + // the texture drawn from is never written by the uploading thread + void upload_from_thread(size_t width, size_t height, const uint8_t *data) override; + bool commit_thread_upload() override; // members static constexpr GLuint invalid_id { std::numeric_limits::max() }; // id value of texture without GL resource @@ -111,6 +125,9 @@ struct opengl_texture : public ITexture { // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread static std::atomic m_unitcachestale; + std::mutex m_threaduploadmutex; + std::optional m_threadupload; // guarded by m_threaduploadmutex + public: // methods void make_request(); diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fac540019..b95b310d8 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -142,18 +142,24 @@ void render_task::run() } else { - std::lock_guard guard(m_target->mutex); + // the lock may be held by the drawing thread for a whole upload: waited for without the gil. the bytes stay + // valid without it, the object is immutable and held by its reference here + Py_BEGIN_ALLOW_THREADS + { + std::scoped_lock guard(m_target->mutex); - if (m_target->image.size() != expectedBytes) - m_target->image.resize(expectedBytes); + if (m_target->image.size() != expectedBytes) + m_target->image.resize(expectedBytes); - std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); + std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); - m_target->width = screenWidth; - m_target->height = screenHeight; - m_target->components = glComponents; - m_target->format = glFormat; - m_target->timestamp = std::chrono::high_resolution_clock::now(); + m_target->width = screenWidth; + m_target->height = screenHeight; + m_target->components = glComponents; + m_target->format = glFormat; + m_target->timestamp = std::chrono::high_resolution_clock::now(); + } + Py_END_ALLOW_THREADS } } @@ -232,6 +238,35 @@ void render_task::upload() const } } +void render_task::upload_from_thread() +{ + m_uploadedbyworker = true; + if (Global.python_uploadmain && m_target && m_target->shared_tex) + { + m_target->shared_tex->upload_from_thread(m_target->width, m_target->height, reinterpret_cast(m_target->image.data())); + } +} + +bool render_task::finish_upload() const +{ + if (false == Global.python_uploadmain || nullptr == m_target || nullptr == m_target->shared_tex) + return true; + // the old texture is deleted and the new name published under the lock the windows of python.displaywindows bind under, + // so none of them binds the old name once it is gone: a name bound before stays alive in its context while bound there + std::scoped_lock lock(m_target->mutex); + if (m_uploadedbyworker) + { + if (false == m_target->shared_tex->commit_thread_upload()) + return false; + } + else + { + upload(); + } + m_target->texture_id = m_target->shared_tex->get_id(); + return true; +} + void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success @@ -569,9 +604,11 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo // execute python code task->run(); if (Context) - task->upload(); - else { + task->upload_from_thread(); + } + { + // the drawing thread uploads the image, or puts in place the one uploaded here std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } @@ -609,10 +646,8 @@ void python_taskqueue::update() { std::scoped_lock lock(m_uploadtasks.mutex); - for (auto const &task : m_uploadtasks.data) - task->upload(); - - m_uploadtasks.data.clear(); + // a task whose image a worker uploaded stays until the gpu has the image + std::erase_if(m_uploadtasks.data, [](std::shared_ptr const &Task) { return Task->finish_upload(); }); } void python_taskqueue::error() diff --git a/scripting/PyInt.h b/scripting/PyInt.h index c8c410397..3259b418a 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -67,6 +67,9 @@ struct python_rt int width; int height; std::string image; + // gl name of the texture with the last image put in place, for the windows of python.displaywindows (0: none yet). the image + // uploaded by a worker gets a texture of its own, so the name changes with each one + size_t texture_id{0}; std::chrono::high_resolution_clock::time_point timestamp; }; @@ -80,7 +83,13 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); + // uploads the image on the drawing thread void upload() const; + // uploads the image on a worker with a gl context of its own (python.threadedupload); finish_upload() puts it in place + void upload_from_thread(); + // on the drawing thread: uploads the image, or puts in place the one a worker uploaded. false while the gpu hasn't got + // the latter yet, to be called again + bool finish_upload() const; void cancel() const; auto target() const -> std::shared_ptr { @@ -92,6 +101,8 @@ class render_task PyObject *m_renderer{nullptr}; std::shared_ptr m_input{nullptr}; std::shared_ptr m_target{nullptr}; + // set by upload_from_thread(); read by the drawing thread after the task was handed over under the lock of the queue + bool m_uploadedbyworker{false}; }; class python_taskqueue diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4da50151e..5a3491af7 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -30,7 +30,7 @@ void texture_window_cursor_pos(GLFWwindow *win, double x, double y) } python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) - : m_rt(rt), m_touchlist(touchlist) + : m_rt(rt), m_touchlist(touchlist), m_initialtexture(rt->shared_tex->get_id()) { for (const auto &viewport : Global.python_viewports) { @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); + bind_shared_texture(); } else { GLuint tex; @@ -146,6 +146,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -188,6 +190,16 @@ void python_screen_viewer::threadfunc() } } +void python_screen_viewer::bind_shared_texture() const +{ + // bound each frame: each image uploaded by a worker comes in a texture of its own, and a name deleted comes back for + // a later one, so a name seen before may be another texture already. bound under the lock the drawing thread deletes + // the old texture under, so the name read here is never one already gone + std::scoped_lock guard(m_rt->mutex); + size_t const texture = m_rt->texture_id; + glBindTexture(GL_TEXTURE_2D, static_cast(texture != 0 ? texture : m_initialtexture)); +} + void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { for (auto const &conf : m_windows) { diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index ccd78f0ef..41b52a7e2 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -31,8 +31,12 @@ class python_screen_viewer gl::scene_ubs m_ubs; std::atomic_bool m_exit = false; + // the texture of the screen when the viewer was made, read on the drawing thread: shown until an image is put in place + size_t m_initialtexture{0}; void threadfunc(); + // with python.sharectx, binds the texture with the last image of the screen, in the context of the window made current + void bind_shared_texture() const; public: python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); From 8794c80c5896375a5e8e199ab0a964d6b206a16a Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:39:52 +0100 Subject: [PATCH 08/18] fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Since d13c27a7 (the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Before d13c27a7 the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from before d13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r --- model/AnimModel.cpp | 9 +++++++-- model/AnimModel.h | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 23af295e4..757ccd2b8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -597,6 +597,10 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { if( Framestamp == m_framestamp ) { return; } auto const timedelta { Timer::GetDeltaTime() }; + // the opacities change step by step from where they are, and they start at 1. the first time the instance is + // drawn its lights take their current state at once, whether it came from the definition or from an event since: + // a fade from 1 showed a light that is off as lit for a moment, the first time it came into view + bool const transition { m_transition && m_lightsanimated }; // interpretacja ułamka zależnie od typu // case ls_Off: ustalenie czasu migotania, t<1s (f>1Hz), np. 0.1 => t=0.1 (f=10Hz) @@ -637,12 +641,13 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { const float transitionontime = std::min(0.25f, std::min(ontime, offtime) * 0.95f); const float transitionofftime = std::min(0.45f, std::min(ontime, offtime) * 0.95f); if (on) - opacity += m_transition ? timedelta / transitionontime : 1.f; // increase to max value + opacity = static_cast( opacity + ( transition ? timedelta / transitionontime : 1.0 ) ); // increase to max value else - opacity -= m_transition ? timedelta / transitionofftime : 1.f; // reduce to zero + opacity = static_cast( opacity - ( transition ? timedelta / transitionofftime : 1.0 ) ); // reduce to zero // Clamp the opacity opacity = std::clamp(opacity, 0.f, 1.f); } + m_lightsanimated = true; // Ra 2F1I: to by można pomijać dla modeli bez animacji, których jest większość for (const auto entry : m_animlist) { diff --git a/model/AnimModel.h b/model/AnimModel.h index e5a6841b6..7cf50fa44 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -225,6 +225,7 @@ public: float fOffTime { 1.f / 2 };// { 60.f / 45.f / 2 }; // były stałymi, teraz mogą być zmienne dla każdego egzemplarza // float fTransitionTime { fOnTime * 0.9f }; // time bool m_transition { true }; // smooth transition between light states + bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame // true if this instance is eligible for the batched/instanced render path: From ba372e9830d364aed06568f6b4025c826b8a9567 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:40:21 +0100 Subject: [PATCH 09/18] Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or :event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after _.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to _dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after _.scm, any included file named *_.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. _.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial : opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here from the lineside tool, and danger_ahead finds where a train first comes to a switch: the start of one it runs onto from its start, or the fouling point of one it runs onto from behind, which may lie behind the point (a signal in the fouling zone). - The card of the selected signal: its distance from the axis of its track, and along it to the start or the fouling point of the switch ahead, in red when it stands inside the fouling zone. The overlay draws the same as a dimension line beside the track on the side of the signal, with the distance at the place. - Placed, dragged along or moved with the gizmo, a signal goes to a round distance to the switch ahead (50 m steps) when within 2.5 m of one; Alt keeps it where it is. The drag of a new one is measured from where it was pressed. - The fixes of the review of the split: the click label of the station tools in their own branch and a plain select in Signals, the card of a signal picked from the check lists shown in Station signals, and the help texts naming the Templates table and the Signals tool. - Self-tests: signalprobe logs the distance from the axis and to the switch ahead, signal snap=1 snaps as placing does. * feat(editor): the fouling point widened in the curves under 250 m, as the standard of the gauge says Standardy techniczne PKP PLK, tom II (from 2025-07-17), 6.5-6.6: the W17 marker stands where the axes of the tracks are nominally 3.50 m apart; where one of the tracks lies there in a curve under 250 m that spacing grows by the widening of the gauge from its radius (annex 1, table 1), the widenings of both summed when both lie in curves. - editor/editorFouling: the fouling point found along the axes of the main track and the branch, standing on its own: at each point of the branch the spacing wanted is the nominal one plus, for each track, the widening on the side of the other track from its radius there (taken over 5 m each way): 50000/R - 185 mm towards the centre of the curve, 60000/R - 225 mm away from it, none from 250 m up. - gauge::curve_widening gives table 1 of the gauge the editor checks already. - The W17 tool and the distance of a signal to the switch ahead both use it; the card of a signal shows how far apart the axes are at the fouling point, the help of the W17 tool says where the figures come from. - Unit tests: a straight branch at 1:9, a branch in a curve of 300 m (no widening) and of 200 m (outer widening), both tracks in curves (both widenings summed) and a straight branch off a curving track. * feat(editor): the cant leans the cars into the fouling point, and the fixes of the review of the metre - The fouling point takes the cant in, as Ie-1 wants it placed "with the gauge, the cant and the widening in the curves": the cars of a track on a cant lean towards the inside of its curve by D Hi / 1500 (bD of table 1 of the standard of the gauge), so when the other track lies on that side the spacing wanted grows by it, taken at 3.05 m over the rail top, the top of the widest part of GPL-1. The cant of each point comes from the roll of its path as the gauge tool takes it. At any radius, as the table has it; the track leaning away adds nothing. - Below 150 m, where table 1 ends, the widening from the radius is that of 150 m rather than the formula run on. - A switch run onto from behind has its fouling point looked for once its own path is walked too, so one lying on that path is found rather than skipped for a farther switch. - A point behind a signal lies on the track of the farther end of its segment, so a signal snapped back over a joint lands at the round distance rather than at the joint. - Alt keeping a signal off the round distances reads the key from ImGui, which Global.altState misses while ImGui holds the keyboard. The gizmo doesn't snap a signal: a1d10bb0 says it does, it's placing and dragging with the tool only. - The help of the distance on the card stays on the distance, the spacing of the axes under it. The unused track_trace::nearest_on is gone. - Unit tests: the cant leaning towards the other track in a curve and at 300 m, nothing when leaning away, and the table ending at 150 m. * fix(editor): the cars lean the way the cant of their track tips them, taken 3.25 m up - The cant along the trace keeps its sign: a roll above 0 lowers the left rail of the path (as the editor lifts its terrain by it), turned to the way the track is walked. A track adds the leaning of its cars to the spacing wanted at the fouling point when the other track lies on the side its lower rail is, whichever way it curves: a branch on a cant against its own curve leans towards the main track on its outer side, which d70f189c missed, and a cant on the straight counts too. - The leaning is taken 3.25 m over the rail top, the top of the widest part of the cars, rather than 3.05 m of GPL-1. - Unit tests: a cant against the curve, a cant on the straight, and the leaning away still adding nothing. * fix(editor): the station tools tell by the mouse what a button came to, and the fields of a station read as empty What a button of the Station, Station signals and Line block tools came to was written at the foot of the panel, under the lists, scrolled away: a click which refused for want of the code of the station looked as if nothing happened. It's told now by the mouse which clicked, a refusal in red as the other tools do, and in the status bar. The fields of a station still empty show their examples as such, "e.g. BPd", not as values typed in; the Station tool says above its steps that the code is to be typed first, Station signals that the code and the track circuits are wanted, the code marked there as needed. The check of a warning disc and of a block section went by the braking distance of the station, while Set the line signals places them by the one of their line: on lk357 a disc placed 700 m before Z, the line run at 100 km/h, was marked as standing nearer than the 1000 m of the station. A signal of a line out is checked by the braking distance of its line now. * feat(editor): the joints of the track circuits put, moved and taken away by hand, kept by the station The Station tool gets Edit the joints by hand: LMB on a plain track of the station puts a joint there, LMB on a joint takes it, then on a track moves it, on it again takes it away. The circuits are set again at once, one step of undo each. The joints so changed are kept in the //$s record of the station (joints +x/y/z for one put, -x/y/z for a planned one taken away), so Set the track circuits keeps them; As planned forgets them. The undo step carries the hand joints of the station with the tracks. srkjoint drives it in the self-tests. * feat(editor): the indicators under the lights reordered, a signal set from the axis and raised, standing on the ground by default The indicators under the lights of the selected signal get arrows up and down: one changes places with the indicator above or below it, a plate at the foot keeps its own. One step of undo each. The distance of the selected signal from the axis of its track is typed in the panel, it moves across as far along the track as it stands, the gauge pushing it out again where it comes too near. Its height is set the same way, raised over where it stands by default, over the rail heads on a gantry. A signal is put on the ground by default, the zero of its model 0.38 m under the rail heads: the ground lies 0.35 m under them as Ie-102 draws it (Lx), the foot of the mast stands on the foundation 3 cm over it in the models of pctga, and the sceneries made by hand (Wrzosy, Baltyk) stand their signals 0.20 m under the rail foot so. It stood on the rail heads. signalindicatorswap and signalacross drive it in the self-tests. * fix(editor): the hand joints of a station without a record, of its ends and of another station; a dragged signal keeps its place across and its height - Edit the joints by hand on a station not described yet read the record of index -1: the hand joints are shown only for a station with one. - The joint between the station and a line out of it can't be taken: taken away, the circuit of the switch ran on over the tracks of the line. - A joint held is let go when another station opens, a move by less than half a metre lets it go, and a change no step of the history takes is undone, so the undo knows every change of the joints. - A signal dragged or snapped along its track keeps its distance from the axis and its height over the default, set by hand or standing so before. * fix(editor): a dragged signal carries what it had by its own track; As planned forgets the hand joints that change nothing The distance from the axis and the height of a dragged signal were taken against the track it was dropped onto: dropped on the next piece of its line, on a grade or by a parallel track it came out too far, in the gauge or off the ground. They are taken as it stood by its own track at the start of the drag. As planned clears the hand joints even where the circuits come out the same. * fix(editor): a signal stands as high over the rail heads as its include gives, lowered only where its bottom would hang over the ground The default height of a signal was 0.38 m under the rail heads for every model. It is now read from the description of its include, `//$e signal: {..., height: , depth: }`: height is where the zero of the model stands over the rail heads (by Ie-117 § 15 the top of the foundation of a mast 0.10 m under them, of a dwarf 0.20 m), depth how far the model reaches under its zero. With a depth, a signal whose bottom would hang over the ground, down an embankment, goes down onto it, by at most 3 m (more is taken for a bridge). Without a height the zero stands at the rail heads. "Raised" in the panel, a signal moved across or dragged, all count from that default height. * fix(editor): a signal flipped, given another template or its variant for the other side stays as raised as it was The default height now depends on the template and on the ground under the signal, so keeping the height as it was no longer keeps the raise. Flipped to the other side of the track, the signal is raised over the default there as it was over the default on its own side. Given another template (Swap), or the variant of its template for the other side when moved or placed, it goes up or down by how much the default height of the new template differs from the old one. * fix(editor): As planned forgetting hand joints that change nothing is a step of undo of its own With nothing in the circuits to change no step of the history took the forgotten joints, so they went with no undo for it: Ctrl+Z took back the step before. The anchor of the station as it is now carries them in a step of their own. The signalmove selftest gets its carry indented with the block it is in. * feat(editor): an indicator under the lights goes in its place by Ie-117, from the top W21, W24, W20, W19, W26 Put on a signal, an indicator under its lights was put below the ones there. It now goes in its place by Ie-117 section 12.1 among them, under the last one it doesn't go above, the others (W18 and the rest) below these; the ones under it move a place down, in the same step of undo. * fix(editor): the signal card and the move of a signal keep no pointer across a refresh of the signals - The card of the selected signal went on after "To the other side" or "Turn around" with found pointing into the list of the signals standing, which their refresh had just replaced: the indicators and the gauge of the card read freed memory. It now ends that frame there. - signal_move_to read the mount of the template after the refresh, which may scan the templates again; it is taken before it. signal_place takes a copy of the template given for the same reason. - The fouling test counts its metres with an int, and the search of the middle point of the radius is a while loop (no floating loop counter). * fix(editor): the dimension line to the danger point counts its metres with an int (Sonar S2193) The line drawn by the track from a signal to the switch or fouling point ahead stepped a double by 1 m. It now counts the whole metres with an int from the same first one: the points are the same, since adding 1 to a whole double and adding a whole int to it give the same values. --------- Co-authored-by: maj00r * feat(editor): ride the camera along the tracks, and a minimap with stations by their W4 (#317) * feat(editor): the camera rides along the tracks, over the joints and switches and over to the tracks alongside Y puts the camera onto the track under the cursor (or the nearest one), looking along it 3 m over the rails. W/S drive it ahead and back the way the camera looks, Shift and Ctrl faster (20, 60, 250 m/s); A/D take it over to the track alongside, a click to any track; E/Q and the wheel raise and lower it; the mouse looks around as when flying. At a switch entered from its blades it goes straight on, Z picks the turnout for the camera alone: no switch is thrown, no track learns of the ride. The bar over the view shows the track, the km, the speed, the height and the switch ahead. Y or Esc ends it. Self-test commands ride, ridewalk, ridejump, rideahead, rideprobe and rideleave. * feat(editor): a minimap of the tracks with the camera on them, and the stations found by the names of their W4 View / Minimap and stations (W4), Ctrl+M: a window with the rail tracks seen from above, the camera as a triangle the way it looks, the track ridden along in orange and the stops of passenger trains as dots with the names of their stations. It follows the camera, or is dragged and zoomed apart from it; a click takes the camera there, riding along the track onto the track there. Above it the stations the PassengerStopPoint memory cells and events name, searched by a part of the name with or without the polish letters; a click (or Enter for the first found) flies the camera over to the stop looking along the track, riding it rides on from there, each click to the next W4 of the station. Self-test commands minimap, stations, station and minimapclick. * fix(editor): the ride and the minimap after the review, with fewer words on the screen - Ctrl+S, Ctrl+Z and the other shortcuts reach the editor while riding; Esc closes an open popup first - no key stays held when a window takes the keyboard, the place is kept within a path that got shorter, a release of the mouse goes where its press went - the minimap keeps under the vertex limit of a draw list, Enter in the search goes round the stops of the station, the marked station stays marked - the bar of the ride is one line: the track, km, speed and height; the switch ahead under it, the keys only while standing - the minimap in the Map menu, opening over the view, with short texts; the context menu of a track rides along it * feat(editor): the ride drives with the right button held, as the camera flies, and the editor works on along it - W/S, A/D and Q/E drive the ride only with the right button held; without it they're the editor's keys again (Q/W/E the gizmo) - the left button and Esc go to the tools while riding: tracks and objects are laid and selected from where the ride took the camera; Y leaves, a flight of the camera to a framing leaves too - after the review: the help names Ctrl+W/Ctrl+Down as the much faster drive, the stops of the minimap stay within the vertex limit, the search field lets the keys go after Enter * fix(editor): the tools keep their wheel and the menu of a track its click while riding, a pan or the view from above ends the ride --------- Co-authored-by: maj00r * feat(editor): signals placed by the editor get a name plate drawn by python (#316) * feat: Elf emergency brake position in the master controller (eu07/maszyna#413) The Elf's master controller (EIMCtrlType 2) gets an optional emergency brake position below its position 0, turned on by the new .fiz key EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it). With it the old positions move up by one (MCPN 5, neutral at 4): the emergency position brakes fully at once and vents the brake pipe, like the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a too small MCPN to 5 and logs it. The Elf code with hard-coded positions (CheckEIMIC, the MED full braking, the AI) takes the shift into account. SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe): - every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5, DirChangeMaxPos=4 where present; - the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09), sounds shifted one index up, new sound0 with 26284_elf_nastawnik_nagle_*.wav. Issue: (eu07/maszyna#413) * fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position The emergency position of the master controller vented the brake pipe from every vehicle whose controller stood there, and "MainCtrl" reached the coupled vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed by one notch (the full braking of one was the emergency brake of the other, neutral of one a power position of the other). The pipe is now vented only from the vehicle driven from (IsCabMaster()), and the position goes to the coupled vehicles in the positions without the key (MainCtrlPosForCoupled(), the emergency one as the full braking), each adding its own shift on receiving it (MainCtrlPosFromCoupled()). The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same shift, so the reverser keeps working at the new neutral. * feat(editor): the signals the editor places get a plate with their name, drawn by python A signal placed with the signal tool used to get the plate texture of textures/tabl named like it, or none at all. Now, unless a texture is picked, its plate is made by python/local/signal_plate.py: "make:signal_plate?name=", a light plate with a dark edge, four screws and the name in black, the way the plates of textures/tabl look. Renaming the signal in its properties renames a drawn plate with it; a picked texture stays. The templates put the plate after a folder, "tabl/(p6)", so material_data::assign() takes the folder off a skin which names a texture made by a script. * fix(editor): a drawn signal plate keeps following a cleared name, and isn't made for a name it can't carry Clearing the name of a signal in its properties made its plate the drawn plate of no name, which then never followed the name again. A drawn plate now follows any rename to a name, and keeps the last one while the name is cleared. A name with '|', '&' or '?', or one longer than 64 characters, gets no plate (0_nothing) instead of a broken one: '|' splits the skin, '&' and '?' the query of the script, and a very long name made a path too long for the file system when the skin was looked for on the disk. * fix(editor): a signal plate keeps its last name through a name it can't carry, and a plate named by hand stays Renaming a signal to a name its plate can't carry turned the drawn plate into 0_nothing, and it stopped following the name for good. Such a name now leaves the plate with the last usable one, like a cleared name does, and the plate follows again once a usable name is typed. A drawn plate whose name was given by hand, different from the name of the signal, is no longer replaced on a rename: only the drawn plate of the signal's own name follows it. * feat(editor): the drawn signal plates come in three looks, plain, toned and aged The plate drawn by python/local/signal_plate.py looked too clean. It now takes a look in its query, "make:signal_plate?look=toned&name=Tm12": plain is the bright plate it was, toned a greyish field with a little grain and dust towards the bottom and the sides, a thinner edge, smaller screws and graphite letters, aged a darker, grainier and dustier one. Toned is drawn when no look is given. The signal tool picks the look under the plate, kept in the settings of the editor. A rename of the signal in its properties keeps the look of its plate. * perf(editor): the grain and the dust of a drawn signal plate are made on whole images The toned and aged plates shaded their field a pixel at a time in python, about 34 ms a plate with the interpreter held, so a station of a hundred signals in view kept the python queue, and the screens of the cabs, waiting for seconds. The dust is now made once per look, and the grain from random bytes of the name, both put on the field with ImageChops: about 2 ms a plate. The mean colour of the plates stays the same; only the grain falls differently. * fix(editor): the station signalling draws the plates of its signals as their schematic names them The plates the station signalling places and renames say what its schematic shows (Tm3, F1, ToA, a block signal without the stem), and a template swapped in for a signal without a plate draws that text too rather than the small letters of the name. A signal left for removal gets a plate of no text again, not one saying "_old". No plate, 0_nothing, or the texture named like the signal, what the editor gave before the plates were drawn, become the drawn plate when the signal is renamed, in the properties panel as by the station signalling, in the look set in the editor. * fix(editor): a plate of a scenery named like the end of the name of its signal stays through a rename in the properties A texture pzs_a was given by its scenery as a, its real plate: a rename in the properties panel keeps it. Only the station signalling, which looked its plates up that way, takes such a one for its own. * feat(editor): the drawn signal plates are 256 pixels across, sharp up close The edge, the screws and the blur are drawn bigger by as much as the plate is, and the grain is as coarse as before, so the three looks stay as they were. The smallest letters tried grow with the plate too. * feat(editor): a drawn signal plate takes a speed index and the m of shunting signals, typed in the signal tool signal_plate.py draws the speed index after the name, one digit up at its right or two as a fraction across the height of the letters (index=4, index=12 for 1/2), and with m=1 an "m" on a strip of its own under the name, as Ie-1 marks a semaphore giving shunting signals and as the textures/tabl a-12m plates show it. The signal tool has a field for the index and a box for the m under the look of the plate; the hint of the plate names them (B 1/2 m). The style of a drawn plate, its look with the index and the m, stays with it through a rename, in the properties panel and by the station signalling, which sets neither. The signal selftest takes index= and m=. * fix(editor): the speed index of a plate takes only digits as they are typed The decimal field let in signs and dots, which stayed shown while the index held only the digits, and filled the two places before a second digit could go in. * fix(sonar): the remarks on the drawn signal plates, to pass the quality gate The new code of the plates was 5.2% technical debt against the 5% of the gate. Fixed the small remarks; the big functions stay as they are: - the speed index field and the plate looks are std::arrays, the index is copied without snprintf, the combo of the looks has a function of its own - ranges algorithms, a string_view for signal_plate_drawn, emplace_back - signal_plate.py: dict literals, a cache of fonts not named like FONTS, no unused local, the name and the m drawn by methods of their own; the plates drawn are byte for byte the same as before --------- Co-authored-by: jerrrrycho Co-authored-by: maj00r * feat(editor): the switch drives with no switch listed and marked, and a switch deleted takes its drives and ballast along - the switch tool lists the drives set to a switch the scenery hasn't got, a click flies to the drive and selects it; the view and the photo mark them red, and the editor tells how many there are once the scenery is open - drives not described for the editor are told by their switch events naming the first parameter: single ones, those of the double switches (thrown as a..d or _a.._d), gates and derailers; the sleepers or ballast throwing a switch on their own events, with no (p1)+ or (p1)-, aren't drives - such a drive may set the speed or carry the ballast of the switch: it's kept as it is, not replaced, turned over or moved, and the switch panel shows it by its file - a switch deleted takes each drive throwing it, also one kept beside a described drive, and the ballast and sleepers named by it, in the same undo step; those of a double switch go with the last of its switches - the selftest commands straydrives and drivewhose * fix(editor): the ballast of a single switch goes with it beside a switch named with a letter more, and a switch of a doubled name keeps its drive - a bed named by a deleted single switch is checked against that name alone, not a..d - deleting one of two tracks of the same name looks for the other before taking away the drive and the ballast - the refusal of a drive not described tells its file without the folder * fix(editor): the tutorial and the hints tell of the kilometrage, and the first lesson takes O either way The kilometrage (X) was in no hint, no shortcut list and no lesson, though the hectometre posts and the block signals are numbered after it. The row of the track tools now reads L T G N U I X B P V J, the turntable with it, and F1 lists I / X / B. The lesson of the signals and the posts says what X does and where the posts take their numbers from, the km of the line or the km typed in their panel for the place clicked, and it opens with the kilometrage tool too. The first lesson asked to switch to the view from above, which a scenery made in the wizard opens in already: O either way does it now. * fix(editor): master's road lifting texts translated, and the panning by the wheel told of in 3D too The merge of master left the status and the label of the lifting of the road points in English: both go through the translations now. Master pans the 3D view by the wheel as well, so the lesson, the hint row and its line say it works in both views. , dropped from the road tool before, came back in the merge and is gone again. * fix(editor): the tools of a plain line in sight, the km of a line set once, a lesson of a whole line and of the ride along a track What a layman building a line with signals and posts couldn't find: - The Signals, Kilometrage and Posts tools are in the main row of Tracks, after the tools of laying; the stations, their signals, the line block, the turntable, the trainset and the checks stay behind More. - "Objects" was where the hectometre posts are: the tool is Posts now (Słupki), its hints say the line the posts go along. - The km of a line could be typed in three places that didn't lead to each other. The panel of the posts and the one of a station, where the line has no km set, say the typed km is theirs alone and have Set the km of the line (X), opening the Kilometrage tool; that tool says first that one known point serves the posts, the stations and the block signals. - The hint of the Signals tool says to pick a signal in the list, then click beside a track; with no templates the panel says so in plain words. - A new lesson, A whole line, step by step: the tracks and switches, the km, the station, its signals, the line block, the posts and the drive, with a button to the station tool, and opened with the station tools. - The first lesson shows the ride of the camera along a track (Y, then W S A D and Z) and has it as a step to try. - lang/editor_pl.po: "Restore the terrain" and "Drag an end" were there twice, the second copies are gone. Checked: MSVC build, unit tests 459/459; editor run on a small scenery, screenshots of the toolbar, the new lesson, the first lesson with the ride ticked after Y, the panels of the posts, the kilometrage and the signals. The station panel with no km of the line wasn't seen, the scenery had no station. * fix(editor): the posts open expanded from the trainset, and the Polish of the whole-line lesson reads right B or the Posts button pressed while the trainset tab is shown opens the hectometre posts with their panel expanded. The Tracks area tooltip names the kilometrage and the posts. The station step names the shunting signals, the station button says Narzędzie Stacja, and the ride rows and the lesson list read smoother in Polish. * fix(editor): a bent model is lengthened along the tracks joined to its own, laid along another track after the bending, and set by fewer settings The ends of a bent model have handles in the view: dragged, the model goes on along the tracks joined there, at a switch the way it's dragged to. Its length, a drag of the whole model and a drag of an end all follow the joined tracks; before, they went on straight past the end of the track under the model. The panel of a bent model picks its track: another one picked, the model stays where it stands, a platform turns its edge to the new track and keeps its length. On top stay the track, the length, the offset and the height, bent or repeated, and the platform edge; the reference point, the position along, turned, mirrored, the cant and the gauge widening went under More settings. The buttons of the model's own length and of the whole track are gone: the length field and the handles do it. The links of a model to its tracks are counted anew when its pieces change, undo and redo included. * fix(editor): the bends of straights laid from the end of a curve begin with a straight, not a compound curve In the mode of straights the curve of a plain track's free end no longer goes on into the curve of the first bend as a compound curve. The line comes out of the end's curve by a transition onto a straight, and each bend gets a curve of its own. Only a curve traced in the mode of a curve goes on from the curve of the end, as it already did at a switch. * fix(editor): the bent model keeps its links and its line to what it reaches, and drags without rebuilding at each track - the links of a bent model are matched anew whenever any of its pieces change, not only the first - the line is lengthened by the plan lengths of the joined tracks and built once a round; a drag reuses the line made at its start while it doesn't grow - the tracks of one name are told apart in the track lists, and a deleted track leaves them - the tracks at the ends the copies no longer reach are left out of the line after an edit or a drag * fix(editor): a click on a bent model's handles changes nothing, and the track picked stays picked - the line is trimmed on a drag's release only when the drag changed the model, and an edit that trimming undoes makes no undo step - the track picked for the bending is kept by the track, not its place in the list, when the list is gathered anew * fix(editor): a double slip with a drive not described for the editor isn't laid anew Laying a double slip anew took away the drives of its switches, the ones not described for the editor too, though they may set the speed or carry the ballast of the slip and are kept as they are everywhere else. The switches laid anew get other names, so such a drive left in place would be set to no switch either: the slip is left as it is, with the reason why. * fix(editor): a slip laid anew or of another template refused for any drive of it not described for the editor The check looked at the one drive a switch is found by, which is the described one when the editor kept a drive of Rainsted beside it; laying a slip again of another template took such drives away unasked. Both ways now look at every drive throwing the switches of the slip, and refuse with a reason that says the slip isn't laid anew. * fix(lang): a stray line taken out of editor_pl.po A single "r" between two entries, left by an edit of the switch texts: msgfmt refuses the file with it. * feat(launcher): the range of the aerial photos of a new real scenery given on the map, changed later in the editor (#328) * feat(launcher): the new real scenery gets the range of its aerial photos on the map, changed later in the editor The wizard of a new scenery asked only for the centre; the editor then downloaded the photos around the camera wherever it went, and a scenery had no range of them until one was drawn in the orthophoto settings. The realistic scenery is made in three steps: the name, the place (a click on the map or the place typed, degrees or PUWG 1992), and the range of the aerial photos: a square of 1, 2, 5 or 10 km around the centre, or an area of the user's, its corners clicked on the map. The range is drawn on the map with its size and the number of the tiles, and it's written to the scenery as the download area (//$z), so the editor downloads the photos and the terrain model inside it only. What a beginner gets wrong is told before the scenery is made: the button stays off with the reason under it (no name, the name taken, no centre, the centre outside Poland, an area being drawn or crossing itself), and a warning comes with the centre outside the area, a large area and a centre clicked on the map of the whole country (the map zooms to the place after the first click). In the editor the download area says in plain words what it does, a square around the camera replaces it in one click, and with the camera outside it a note at the bottom of the view says there are no photos there, with the way to the range. * fix(launcher): the range of the photos asked for after the centre, the drawing given up as with Cancel, the square named by its sides The review of the range of the aerial photos found: - with My own area chosen before the centre, the clicks meant for the centre went to the corners of the area: step 3 waits for the centre; - switching to Fictional while drawing dropped the area there was before, and an unfinished one of three corners counted as done: it's given up as with Cancel now, also with Esc; Enter ends it, Backspace takes the last corner back, as in the editor; - the error of a place mistyped stayed after a click on the map; - the largest square was told to be large or not by the rounding: the warning comes from 50 sq km on; - "2 km" read as a radius: the squares say "2 x 2 km", the tooltip how far each edge is; - a place typed with an area of the user's fitted the map to the area, not to the place. In the editor the note of the camera outside the range says the terrain model isn't there either, its button says it opens the settings, it stands above the strip of the profile and the keys of the tools, and it can be closed until the camera is back inside. The squares around the camera want the place of the scenery on the map, and replace an area there is, or start one of 10 x 10 km, only with a yes. * fix(editor): one note of the empty scenery in the middle of the view, the warnings of an area told once it's drawn A new scenery opened in the editor showed two notes of the same over each other in the middle of the view: the panel of the track tools ("The scenery has no tracks yet") and the line of the terrain ("This scenery is still empty"). The line gives way to the panel now. In the wizard the centre outside the area and the crossing edges were told while the area was still being drawn; they're told once it's done. * fix(editor): the note of the camera outside the range of the photos hidden while the camera rides a track Its lines at the bottom of the view are where the camera riding a track writes the next switch and its keys. --------- Co-authored-by: maj00r --------- Co-authored-by: maj00r Co-authored-by: Hirek193 Co-authored-by: jerrrrycho --- application/editormode.cpp | 16 +- application/editormode.h | 39 +++- application/editormodelineside.cpp | 4 +- application/editormodeselftestswitch.cpp | 19 ++ application/editormodeswitchdrive.cpp | 261 +++++++++++++++++++++-- application/editormodeswitchplace.cpp | 7 + application/editormodeswitchtemplate.cpp | 3 + application/editormodeswitchtool.cpp | 1 + application/editormodetrack.cpp | 18 +- editor/editorIncludeInfo.cpp | 65 ++++++ editor/editorIncludeInfo.hpp | 7 + lang/editor_pl.po | 30 +++ 12 files changed, 442 insertions(+), 28 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index ab150cb7b..bb87aa5cb 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -1412,6 +1412,15 @@ bool editor_mode::update() ui()->set_status(text, false); WriteLog("Editor: " + text, logtype::generic); } + // the drives left without their switches are told once, as the scenery is opened + if (auto const stray{stray_drives().size()}; stray > 0) + { + auto const text{format(STR_P("%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view", + "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view", static_cast(stray)), + stray)}; + ui()->set_notice(text); + WriteLog("Editor: " + text, logtype::generic); + } } } // after the tool has told its own status @@ -1652,6 +1661,7 @@ bool editor_mode::update() draw_build_overlay(); steps.step("laying drawn"); draw_blade_tips(); + draw_stray_drives(); draw_track_intent(); draw_tape(); steps.step("track drawn"); @@ -3309,7 +3319,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) return; } scene::Layers.removed(Instance, false == included.removed); - m_drives_standing.reset(); + drives_changed(); ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } @@ -3346,7 +3356,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } - m_drives_standing.reset(); + drives_changed(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -3391,7 +3401,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - m_drives_standing.reset(); + drives_changed(); std::string file; std::vector values; if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && diff --git a/application/editormode.h b/application/editormode.h index 81347c950..148edb25a 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -2635,8 +2635,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri struct switch_drive { standing_template standing; - int family{-1}; - int index{0}; + int family{-1}; // -1: a drive not described for the editor, e.g. of Rainsted; it can be replaced, not turned over or moved + int index{-1}; }; std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches @@ -2656,10 +2656,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri void switch_drives_committed(std::vector const &Tracks); // the drives of the switches deleted go with them, in the step of the undo history the deletion made last void drives_deleted(std::vector const &Switches); + // the file of a drive not described for the editor throwing one of the switches, empty when there's none; also one the editor + // kept beside a drive described for it + std::string undescribed_drive(std::vector const &Switches); // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved std::size_t drives_to_blade_tips(); bool m_drives_checked{false}; + // the file of each variant of the drives scanned: its family and its index in the family + std::map, std::less<>> drive_variants() const; + // the switches a template of a drive throws, by what follows its first parameter in their names: "" for a variant described for the + // editor, and for any other template whose switch events throw the track named by its first parameter, as the drives of Rainsted do; + // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not + // described for the editor have no family (-1) + std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); + std::map, std::less<>> m_drive_templates; // read once for each file + // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events + // throw nothing + struct stray_drive + { + scene::instance_handle instance{0}; + std::vector switches; // the names of the switches it throws, as its include gives them + std::string name; // of the switches missing from them + std::string file; + glm::dvec3 location{0.0}; + }; + // all the drives standing in the scenery, read from the files once while no include comes or goes + struct drives_named + { + std::vector drives; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_named; + // the include of a drive or a template changed: what's kept of the drives standing is read again + void drives_changed(); + // the drives whose switch isn't in the scenery, checked against the tracks each time + std::vector stray_drives(bool Wait = false); + void render_stray_drives(); + void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; // places them in the active layer or the given one, as one step of the undo. returns: how many were placed std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index 1c2fc9e9c..8f4f5209c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -253,7 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) { - m_drives_standing.reset(); + drives_changed(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -341,7 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { - m_drives_standing.reset(); + drives_changed(); EditorSnapshot snap; for (auto const instance : Instances) { diff --git a/application/editormodeselftestswitch.cpp b/application/editormodeselftestswitch.cpp index 891ca6d68..b9c502d17 100644 --- a/application/editormodeselftestswitch.cpp +++ b/application/editormodeselftestswitch.cpp @@ -549,6 +549,25 @@ editor_mode::selftest_result editor_mode::selftest_switch(std::string const &com WriteLog("SELFTEST drives " + name + ": chosen " + (m_switch.drive >= 0 ? m_switch.drives[m_switch.drive].name : std::string{"none"}) + ", side " + std::to_string(m_switch.drive_side) + ", standing" + files + ", steps " + std::to_string(m_history.size())); return selftest_result::handled; } + if (command == "straydrives") + { + auto const stray{stray_drives(true)}; + std::string names; + for (auto const &drive : stray) + names += " " + drive.name + "(" + drive.file + ")"; + WriteLog(format("SELFTEST straydrives: %zu", stray.size()) + names); + return selftest_result::handled; + } + if (command == "drivewhose") + { + // the drive the editor tells for the switch: its file and family, -1 for one not described + std::string name; + words >> name; + auto *track{simulation::Paths.find(name)}; + auto const found{track != nullptr ? find_switch_drive(*track) : std::nullopt}; + WriteLog("SELFTEST drivewhose " + name + ": " + (found.has_value() ? found->standing.file + " family " + std::to_string(found->family) : std::string{"none"})); + return selftest_result::handled; + } if (command == "driveflip") { std::string name; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 3e0a67854..931350af1 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editormodeshared.h" +#include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" @@ -25,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "imgui/imgui.h" #include +#include #include #include #include @@ -44,6 +46,21 @@ std::string drive_file(std::string Text) return Text; } +// the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as +// they're written +TTrack *track_named(std::string const &Name) +{ + auto *track{simulation::Paths.find(Name)}; + return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); +} + +// a template by the name of its file, with no folder: told to the user, who picks the drives by their names +std::string file_name(std::string const &File) +{ + auto const slash{File.find_last_of('/')}; + return slash != std::string::npos ? File.substr(slash + 1) : File; +} + int drive_side(std::string const &Side) { if (Side == "left") @@ -168,7 +185,8 @@ void editor_mode::switch_drives_committed(std::vector const &Tracks) drives = switch_drives_standing(); auto const found{drives->find(drive_file(track->name()))}; auto const spot{editor_track::drive_spot_of(*track)}; - if (found == drives->end() || false == spot.has_value()) + // a drive not described for the editor has no parameters known to set it with, nor a height above the rail; it stays put + if (found == drives->end() || found->second.family < 0 || false == spot.has_value()) continue; auto const &drive{found->second.standing}; auto const &included{scene::Layers.instance(drive.instance)}; @@ -221,7 +239,15 @@ bool editor_mode::place_switch_drive(TTrack &Switch) item.track = Switch.name(); item.tilt = spot->tilt; if (auto const present{find_switch_drive(Switch)}) + { + // one not described for the editor is kept: it may set the speed over the switch or carry its ballast too + if (present->family < 0) + { + tool.status = format(STR_C("Switch %s keeps its drive %s, which isn't described for the editor"), Switch.name().c_str(), file_name(present->standing.file).c_str()); + return false; + } return replace_switch_drive(Switch, tool.drive, (present->index & 1) != (driveright ? 1 : 0)); + } std::string error; if (place_templates({item}, error) == 0) { @@ -255,22 +281,147 @@ std::map const &editor_mode::switch_driv return included.removed || included.dead; })) return kept->by_switch; + auto const variants{drive_variants()}; + kept.emplace(); + kept->frame = ImGui::GetFrameCount(); + kept->revision = tool.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + auto const variant{variants.find(standing.file)}; + auto const [family, index]{variant != variants.end() ? variant->second : std::pair{-1, -1}}; + // the drive of a double switch of Rainsted stands for each of its switches, a..d + for (auto const &suffix : drive_switches(standing.file, variants)) + { + // a drive described for the editor goes before one of Rainsted set to the same switch, which the editor kept beside it + auto const [entry, fresh]{kept->by_switch.try_emplace(drive_file(standing.values[0] + suffix), switch_drive{standing, family, index})}; + if (false == fresh && entry->second.family < 0 && family >= 0) + entry->second = switch_drive{standing, family, index}; + } + } + return kept->by_switch; +} + +std::vector const &editor_mode::drive_switches(std::string const &File, std::map, std::less<>> const &Variants) +{ + static std::vector const single{std::string{}}; + if (Variants.contains(File)) + return single; + auto const [found, fresh]{m_drive_templates.try_emplace(File)}; + if (fresh) + editor_includes::switched_tracks(File, found->second); + return found->second; +} + +std::map, std::less<>> editor_mode::drive_variants() const +{ + auto const &tool{m_switch}; std::map, std::less<>> variants; for (int family = 0; family < static_cast(tool.drives.size()); ++family) for (int index = 0; index < 4; ++index) if (false == tool.drives[family].files[index].empty()) variants[drive_file(tool.drives[family].files[index])] = {family, index}; - kept.emplace(); - kept->frame = ImGui::GetFrameCount(); - kept->revision = tool.drives_revision; - kept->instances = instances; - for (auto &standing : standing_templates([&](std::string const &File) { return variants.contains(File); })) + return variants; +} + +void editor_mode::drives_changed() +{ + m_drives_standing.reset(); + m_drives_named.reset(); +} + +std::vector editor_mode::stray_drives(bool const Wait) +{ + scan_switch_drives(Wait); + auto const instances{static_cast(scene::Layers.instance_count())}; + auto &kept{m_drives_named}; + if (false == kept.has_value() || kept->revision != m_switch.drives_revision || kept->instances != instances) { - auto const &[family, index]{variants[standing.file]}; - auto name{drive_file(standing.values[0])}; - kept->by_switch.try_emplace(std::move(name), switch_drive{std::move(standing), family, index}); + auto const variants{drive_variants()}; + kept.emplace(); + kept->revision = m_switch.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + stray_drive drive{standing.instance, {}, {}, standing.file, standing.location}; + for (auto const &suffix : drive_switches(standing.file, variants)) + drive.switches.push_back(standing.values[0] + suffix); + kept->drives.push_back(std::move(drive)); + } + } + // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its + // switches gone, while one stands it still throws it + std::vector stray; + for (auto const &drive : kept->drives) + { + auto const &included{scene::Layers.instance(drive.instance)}; + // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts + if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { + auto const *track{track_named(Name)}; + return track != nullptr && false == track->m_editorremoved; + })) + continue; + std::string missing; + for (auto const &name : drive.switches) + missing += (missing.empty() ? "" : ", ") + name; + stray.push_back(drive); + stray.back().name = std::move(missing); + } + return stray; +} + +void editor_mode::render_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + ImGui::PushID("straydrives"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.55f, 0.25f, 1.0f)); + auto const open{ImGui::TreeNode("##straydrives", STR_P("%zu drive with no switch", "%zu drives with no switch", static_cast(stray.size())), stray.size())}; + ImGui::PopStyleColor(); + item_tooltip("Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name"); + if (open) + { + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + auto const label{format("%s (%s, %.0f m)##%d", drive.name.c_str(), file_name(drive.file).c_str(), glm::length(drive.location - camera), static_cast(drive.instance))}; + if (ImGui::Selectable(label.c_str(), m_instance == drive.instance)) + { + select_include(drive.instance); + fly_to(drive.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 25.0); + } + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list +void editor_mode::draw_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + // the ones far off would only crowd the view of the whole line + auto constexpr range{3000.0}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + ImVec2 at; + if (glm::length(drive.location - camera) > range || false == projection.project(drive.location, at)) + continue; + auto const selected{m_instance == drive.instance}; + drawlist->AddCircleFilled(at, 8.0f, IM_COL32(0, 0, 0, 170)); + drawlist->AddCircle(at, 7.0f, selected ? overlay_color::selected : overlay_color::invalid, 0, 3.0f); + auto const text{format(STR_C("%s: no switch of this name"), drive.name.c_str())}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const corner{at.x + 12.0f, at.y - 0.5f * size.y}; + drawlist->AddRectFilled({corner.x - 3.0f, corner.y - 1.0f}, {corner.x + size.x + 3.0f, corner.y + size.y + 1.0f}, IM_COL32(0, 0, 0, 160), 3.0f); + drawlist->AddText(corner, selected ? overlay_color::selected : overlay_color::invalid, text.c_str()); } - return kept->by_switch; } void editor_mode::apply_switch_drive_choice(TTrack &Switch) @@ -280,7 +431,10 @@ void editor_mode::apply_switch_drive_choice(TTrack &Switch) place_switch_drive(Switch); return; } - if (auto const found{find_switch_drive(Switch)}; found.has_value() && remove_templates({found->standing.instance}) > 0) + auto const found{find_switch_drive(Switch)}; + if (found.has_value() && found->family < 0) + m_switch.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found->standing.file).c_str())); + else if (found.has_value() && remove_templates({found->standing.instance}) > 0) m_switch.status = format(STR_C("Switch %s without a drive now"), Switch.name().c_str()); } @@ -299,7 +453,15 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return false; } auto const &found{present->standing}; + // a drive not described for the editor, as one of a double switch, may set the speed over the switch or carry its ballast too: it's kept as it is + if (present->family < 0) + { + tool.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found.file).c_str())); + return false; + } auto const family{Family >= 0 ? Family : present->family}; + if (family >= static_cast(tool.drives.size())) + return false; auto const index{Flip ? present->index ^ 1 : present->index}; template_item item; item.file = tool.drives[family].files[index]; @@ -334,19 +496,82 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return true; } +std::string editor_mode::undescribed_drive(std::vector const &Switches) +{ + // the drives described for the editor read first: before they are, every drive would pass for one not described + scan_switch_drives(true); + std::vector names; + for (auto const *track : Switches) + if (track != nullptr) + names.push_back(drive_file(track->name())); + auto const variants{drive_variants()}; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == variants.contains(File) && false == drive_switches(File, variants).empty(); })) + { + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return std::find(names.begin(), names.end(), drive_file(standing.values[0] + Suffix)) != names.end(); })) + return file_name(standing.file); + } + return {}; +} + void editor_mode::drives_deleted(std::vector const &Switches) { if (m_history.empty()) return; + // the names of the switches deleted, as the game finds them; they're retired already + std::vector deleted; for (auto const *track : Switches) + if (track != nullptr && track->eType == tt_Switch) + deleted.push_back(drive_file(track->name())); + if (deleted.empty()) + return; + auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; + // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, + // still has the drive and the ballast, so it's looked for too + auto const stands = [](std::string const &Name) { + if (auto const *track{track_named(Name)}; track != nullptr) + return false == track->m_editorremoved; + auto const name{drive_file(Name)}; + auto const &tracks{simulation::Paths.sequence()}; + return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); + }; + auto const take_away = [&](scene::instance_handle const Instance) { + if (false == scene::Layers.removable(Instance)) + return; + scene::Layers.removed(Instance, true); + m_history.back().instances.push_back(Instance); + }; + auto const variants{drive_variants()}; + // each drive throwing a switch deleted, also one the editor kept beside a drive described for it; the drive of a double switch throws + // the others too, so it goes with the last of them + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) { - if (track == nullptr || track->eType != tt_Switch) + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return named(standing.values[0] + Suffix); }) && + std::none_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return stands(standing.values[0] + Suffix); })) + take_away(standing.instance); + } + // the sleepers and the ballast laid by a switch, named by it as its drive is: of a double switch by the name its switches have in + // common, a..d or _a.._d, so they go with the last of them + static std::array const parts{"", "a", "b", "c", "d", "_a", "_b", "_c", "_d"}; + std::map> beds; + for (auto const &standing : standing_templates([](std::string const &) { return true; })) + { + auto const &name{standing.values[0]}; + // named by a single switch, it's this switch's alone; a switch named a beside it may be another single one + if (named(name)) + { + if (stands(name)) + continue; + } + else if (std::none_of(parts.begin(), parts.end(), [&](char const *Part) { return named(name + Part); }) || + std::any_of(parts.begin(), parts.end(), [&](char const *Part) { return stands(name + Part); })) continue; - auto const found{find_switch_drive(*track)}; - if (false == found.has_value() || false == scene::Layers.removable(found->standing.instance) || scene::Layers.instance(found->standing.instance).removed) - continue; - scene::Layers.removed(found->standing.instance, true); - m_history.back().instances.push_back(found->standing.instance); + auto const [bed, fresh]{beds.try_emplace(standing.file)}; + if (fresh) + bed->second = drive_switches(standing.file, variants).empty() && editor_includes::switch_bed(standing.file); + if (bed->second) + take_away(standing.instance); } } @@ -359,7 +584,7 @@ std::size_t editor_mode::drives_to_blade_tips() { if (track == nullptr || track->m_editorremoved || track->eType != tt_Switch) continue; - if (auto const found{find_switch_drive(*track)}; found.has_value() && scene::Layers.removable(found->standing.instance)) + if (auto const found{find_switch_drive(*track)}; found.has_value() && found->family >= 0 && scene::Layers.removable(found->standing.instance)) { switches.push_back(track); before.emplace_back(found->standing.instance, scene::Layers.directive(found->standing.instance)); diff --git a/application/editormodeswitchplace.cpp b/application/editormodeswitchplace.cpp index b35ef8c48..82028a943 100644 --- a/application/editormodeswitchplace.cpp +++ b/application/editormodeswitchplace.cpp @@ -1609,6 +1609,13 @@ bool editor_mode::replace_double_slip(TTrack &Part, editor_track::switch_templat return false; } } + // a drive not described for the editor may set the speed or carry the ballast of the slip too: the editor can neither take it + // away nor move it to the switches laid anew, which get other names, so the slip is left as it is + if (auto const drive{undescribed_drive({switches.begin(), switches.end()})}; false == drive.empty()) + { + state.status = refused(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); + return false; + } struct end { TTrack *track; diff --git a/application/editormodeswitchtemplate.cpp b/application/editormodeswitchtemplate.cpp index e6a8496bd..6edef6a65 100644 --- a/application/editormodeswitchtemplate.cpp +++ b/application/editormodeswitchtemplate.cpp @@ -286,6 +286,9 @@ bool editor_mode::change_slip_template(TTrack &Part, int const Index) for (auto const *part : parts) if (false == part->Dynamics.empty()) return fail(STR_C("The slip can't be laid again while vehicles stand on it")); + // its drives go with it and the new one gets its own: a drive not described for the editor can't be told apart from them + if (auto const drive{slip.has_value() ? undescribed_drive(slip->switches) : std::string{}}; false == drive.empty()) + return fail(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); // a single slip laid again joins the pair of the tracks it joined: the point given by them auto const &ends{slip.has_value() ? slip->ends : std::array{}}; auto const pair{slip.has_value() && record.type == "Rkp" ? 0.5 * (ends[0] + ends[3]) : glm::dvec3{0.0}}; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index a37c98f70..878e18aa3 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -282,6 +282,7 @@ void editor_mode::render_switch_ui() ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", tool.status.c_str()); ImGui::PopTextWrapPos(); } + render_stray_drives(); if (ImGui::Button(STR_C("Template editor..."))) m_switch_designer.open = true; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 91bf9c027..6e0fe60c7 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1171,22 +1171,34 @@ void editor_mode::render_turnout_ui() { auto const family{drive->family}; auto const variant{drive->index}; + // a drive not described for the editor is shown by its file + auto const described{family >= 0 && family < static_cast(m_switch.drives.size())}; + auto const &file{drive->standing.file}; + auto const shown{described ? m_switch.drives[family].name : format("%s (%s)", file.substr(file.find_last_of('/') + 1).c_str(), STR_C("not described"))}; if (begin_fields("##standingdrive", 0.3f)) { field_row("Drive##standing"); - if (ImGui::BeginCombo("##standing", m_switch.drives[family].name.c_str())) + if (false == described) + ImGui::TextUnformatted(shown.c_str()); + else if (ImGui::BeginCombo("##standing", shown.c_str())) { for (int i = 0; i < static_cast(m_switch.drives.size()); ++i) if (ImGui::Selectable(m_switch.drives[i].name.c_str(), family == i) && i != family) replace_switch_drive(Switch, i, false); ImGui::EndCombo(); } - if (ImGui::IsItemHovered()) + if (described && ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", STR_C("Puts another drive in place of the drive of this switch, on the same side"), format(STR_C("Drive: events %s+ and %s- switch it, also in the map"), Switch.name().c_str(), Switch.name().c_str()).c_str()); ImGui::EndTable(); } int side{((variant >> 1) == (variant & 1)) ? 0 : 1}; - if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, + if (false == described) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted")); + ImGui::PopTextWrapPos(); + } + else if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, {1, STR_C("other side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}})) flip_switch_drive(Switch); } diff --git a/editor/editorIncludeInfo.cpp b/editor/editorIncludeInfo.cpp index ca532f1ce..450cde5a2 100644 --- a/editor/editorIncludeInfo.cpp +++ b/editor/editorIncludeInfo.cpp @@ -548,6 +548,71 @@ bool event_names(std::string const &File, std::vector &Names) return true; } +bool switched_tracks(std::string const &File, std::vector &Suffixes) +{ + Suffixes.clear(); + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + // event switch + auto const tokens{tokenize(text.content)}; + std::string const first{"(p1)"}; + // a drive has the events thrown by the keys and the map, (p1)+ and (p1)-, or moves a model, lights its lamps or throws a double switch at + // once; the sleepers or the ballast of a switch may throw it on their own events too, with nothing else, but they don't drive it + bool driven{false}; + for (std::size_t idx = 0; idx + 2 < tokens.size() && false == driven; ++idx) + { + if (tokens[idx] != "event") + { + continue; + } + auto const &name{tokens[idx + 1]}; + auto const &kind{tokens[idx + 2]}; + driven = (name.size() > first.size() && name.compare(0, first.size(), first) == 0 && (name.back() == '+' || name.back() == '-')) || (kind != "switch" && kind != "trackvel"); + } + if (false == driven) + { + return true; + } + for (std::size_t idx = 0; idx + 4 < tokens.size(); ++idx) + { + if (tokens[idx] != "event" || tokens[idx + 2] != "switch" || tokens[idx + 4].compare(0, first.size(), first) != 0) + { + continue; + } + auto suffix{tokens[idx + 4].substr(first.size())}; + if (std::find(Suffixes.begin(), Suffixes.end(), suffix) == Suffixes.end()) + { + Suffixes.push_back(std::move(suffix)); + } + } + return true; +} + +bool switch_bed(std::string const &File) +{ + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + auto const tokens{tokenize(text.content)}; + for (std::size_t idx = 0; idx < tokens.size(); ++idx) + { + // node track ... + if (tokens[idx] == "include" || (tokens[idx] == "node" && idx + 4 < tokens.size() && tokens[idx + 4] == "track") || + (tokens[idx] == "event" && idx + 2 < tokens.size() && tokens[idx + 2] != "switch" && tokens[idx + 2] != "trackvel")) + { + return false; + } + } + return true; +} + bool signal_speeds(std::string const &File, std::vector &Speeds) { Speeds.clear(); diff --git a/editor/editorIncludeInfo.hpp b/editor/editorIncludeInfo.hpp index 7a2da9dfa..96b84b44a 100644 --- a/editor/editorIncludeInfo.hpp +++ b/editor/editorIncludeInfo.hpp @@ -90,6 +90,13 @@ int parameter_count(std::string const &File); bool signal_speeds(std::string const &File, std::vector &Speeds); // the names of the events the template defines, as they're written after "event", lower case. returns: false if the file can't be read bool event_names(std::string const &File, std::vector &Names); +// the tracks the switch events of the template throw, named by its first parameter: what follows (p1) in their names, lower case, "" +// for the track named (p1) itself, "a" for (p1)a of a double switch; none for the sleepers or the ballast of a switch, whose events only +// throw it or set its speed, with no (p1)+ or (p1)-. returns: false if the file can't be read +bool switched_tracks(std::string const &File, std::vector &Suffixes); +// true if the template can be the sleepers or the ballast of a switch: it puts no track, includes nothing and has no events but those +// throwing a switch or setting its speed. false if the file can't be read +bool switch_bed(std::string const &File); // the aspects of a block signal of the template: 4 where its events give S3, the green light flashing with the next signal at S5, // the warning two signals ahead, else 3. returns: 0 if the file can't be read int block_aspects(std::string const &File); diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4a5bc4759..b765a98d6 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14023,6 +14023,36 @@ msgstr "PPM wciśnięty, W / S" msgid "RMB held, A / D" msgstr "PPM wciśnięty, A / D" +msgid "%zu drive with no switch" +msgid_plural "%zu drives with no switch" +msgstr[0] "%zu napęd bez zwrotnicy" +msgstr[1] "%zu napędy bez zwrotnicy" +msgstr[2] "%zu napędów bez zwrotnicy" + +msgid "Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name" +msgstr "Napędy ustawione na zwrotnicę, której w scenerii nie ma: zostały po zwrotnicy usuniętej lub przemianowanej ręcznie albo we wcześniejszym edytorze, ich eventy niczego nie przestawiają.\nKliknięcie przenosi do napędu i go zaznacza, Delete go usuwa; można też nadać jakiejś zwrotnicy jego nazwę" + +msgid "%s: no switch of this name" +msgstr "%s: brak zwrotnicy o tej nazwie" + +msgid "%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view" +msgid_plural "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view" +msgstr[0] "%zu napęd nie ma zwrotnicy o swojej nazwie: jest na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[1] "%zu napędy nie mają zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[2] "%zu napędów nie ma zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" + +msgid "The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is" +msgstr "Napęd %s nie ma opisu dla edytora: może też ustawiać prędkość albo nieść podsypkę zwrotnicy, więc zostaje bez zmian" + +msgid "The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew" +msgstr "Rozjazd krzyżowy ma napęd %s bez opisu dla edytora, który może też ustawiać prędkość albo nieść jego podsypkę: nie zostanie ułożony od nowa" + +msgid "Switch %s keeps its drive %s, which isn't described for the editor" +msgstr "Zwrotnica %s zostaje przy swoim napędzie %s, który nie ma opisu dla edytora" + +msgid "A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted" +msgstr "Napęd bez opisu dla edytora, np. rozjazdu krzyżowego, który może też ustawiać prędkość albo nieść podsypkę zwrotnicy: edytor go nie zmienia, zostaje na miejscu, gdy zwrotnica się przesuwa, i znika razem z ostatnią zwrotnicą, którą przestawia" + # the wizard of a new scenery: the range of the aerial photos, given on the map and changed in the editor msgid "A fictional scenery needs no place on the map" From 201cae07e15509dd255caf892a75a603a45649f7 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:53:42 +0100 Subject: [PATCH 10/18] fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), (...) Stack (addr2line -f -C -e ): to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r --- CMakeLists.txt | 1 + EU07.cpp | 46 +++++- application/application.cpp | 42 +++++- application/application.h | 1 + tests/unit/test_crashsignals.cpp | 89 ++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 4 + utilities/Logs.cpp | 3 + utilities/crashsignals.cpp | 234 +++++++++++++++++++++++++++++++ utilities/crashsignals.h | 25 ++++ 10 files changed, 444 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_crashsignals.cpp create mode 100644 utilities/crashsignals.cpp create mode 100644 utilities/crashsignals.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d5c0ad33..e563e587f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -545,6 +545,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" diff --git a/EU07.cpp b/EU07.cpp index 1c2c36aab..fa6bb15f2 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,9 +22,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -78,8 +82,12 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ExceptionPointers = ExceptionInfo; dumpInfo.ClientPointers = FALSE; - // Wybrana kombinacja flag - MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + // a small dump by default: the stacks with the memory they point to, the threads with their process and thread + // blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data + // (Global among them). all the memory of the simulator, as large as the memory it took, only with + // "crashdump.full yes" in eu07.ini + auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs}; + MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); // in test mode nobody is there to close the box, and the run would wait for it until killed @@ -172,9 +180,15 @@ int main(int argc, char *argv[]) SetUnhandledExceptionFilter(CrashHandler); #endif #endif + // on Linux, where no dump is written, the stack of a crash in the log and on the standard error + crash_signals::install(VERSION_INFO); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); + // a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it + // from a closing; how the simulator ends after a start that worked stays as it was + int exitcode{0}; + // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { @@ -221,34 +235,54 @@ int main(int argc, char *argv[]) } else { + // below 0 when the start failed (see eu07_application::init()) + int initresult{0}; try { - auto result{Application.init(argc, argv)}; - if (result == 0) + initresult = Application.init(argc, argv); + if (initresult == 0) { - result = Application.run(); + Application.run(); Application.exit(); } } + // an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the + // log and ends with an error code catch (std::bad_alloc const &Error) { ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what())); + exitcode = 1; } #ifdef _WIN32 catch (std::runtime_error const &Error) { + ErrorLog("Critical error: " + std::string(Error.what())); std::string msg = "Simulator crash occured :(\n"; msg += Error.what(); MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); + exitcode = 1; + } +#else + // elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on + // Windows it is left to CrashHandler, whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } #ifndef _WIN32 fflush(stdout); fflush(stderr); #endif - std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults + std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults } diff --git a/application/application.cpp b/application/application.cpp index 12bc9020a..d11ed8bbd 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -171,6 +174,28 @@ void char_callback(GLFWwindow *window, unsigned int c) Application.on_char(c); } +namespace +{ + +// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no +// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context, +// is told once. glfw may call this from any thread that uses it +void glfw_error_callback(int const Code, char const *Description) +{ + auto message{std::format("GLFW error 0x{:08X}: {}", static_cast(Code), Description != nullptr ? Description : "(no description)")}; + + static std::mutex reportedmutex; + static std::set reported; + { + std::scoped_lock lock(reportedmutex); + if (false == reported.insert(message).second) + return; + } + ErrorLog(message); +} + +} // namespace + // public: void eu07_application::queue_screenshot() @@ -253,7 +278,8 @@ int eu07_application::run_crashgui() return 0; } } - return -1; + // the player closed the window: the simulator closes with it, as it always has, but that is no failed start + return 1; } #if WITH_DISCORD_RPC void eu07_application::DiscordRPCService() @@ -436,7 +462,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { - ErrorLog("Failed to run crash gui!"); + // above 0 the player closed the window, which is no error + if (result < 0) + ErrorLog("Failed to run crash gui!"); + else + WriteLog("Crash report window closed, closing"); return result; } } @@ -503,6 +533,11 @@ int eu07_application::init(int Argc, char *Argv[]) if (!init_network()) return -1; + // glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the + // platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key + // codes of its launchers), every frame + glfwSetErrorCallback(nullptr); + return result; } @@ -1391,6 +1426,9 @@ int eu07_application::init_locale() int eu07_application::init_glfw() { + // set before glfwInit(), so a failure of the start itself is told too + glfwSetErrorCallback(glfw_error_callback); + { int glfw_major, glfw_minor, glfw_rev; glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); diff --git a/application/application.h b/application/application.h index 850b66e1e..881d4f073 100644 --- a/application/application.h +++ b/application/application.h @@ -33,6 +33,7 @@ public: // constructors eu07_application() = default; // methods + // 0 when the simulator started, below 0 when its start failed, above 0 when the player closed it before it started int init( int Argc, char *Argv[] ); int diff --git a/tests/unit/test_crashsignals.cpp b/tests/unit/test_crashsignals.cpp new file mode 100644 index 000000000..4c4dd1e86 --- /dev/null +++ b/tests/unit/test_crashsignals.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/crashsignals.h" + +// the stack of a crash on Linux (utilities/crashsignals.h): written to the log and to the standard error, after which +// the signal ends the process as it always did. the crash happens in a child process, which the test watches +#if defined(__linux__) + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +std::string read_all(int const File) { + std::string text; + std::array buffer{}; + for (auto count{::read(File, buffer.data(), buffer.size())}; count > 0; count = ::read(File, buffer.data(), buffer.size())) + text.append(buffer.data(), static_cast(count)); + return text; +} + +std::string read_file(std::string const &Path) { + std::ifstream file{Path, std::ios::binary}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +// the child: the report goes to the pipe in place of the standard error, no core dump is left behind +[[noreturn]] void crash_in_child(std::array const &Pipe, std::string const &Log) { + // a child stuck before the crash (a lock some other thread held at the fork) ends anyway, and the test with it + alarm(10); + dup2(Pipe[1], STDERR_FILENO); + close(Pipe[0]); + close(Pipe[1]); + rlimit const nocore{0, 0}; + setrlimit(RLIMIT_CORE, &nocore); + + crash_signals::install("test version 1.2"); + crash_signals::set_log_path(Log); + raise(SIGSEGV); + _exit(0); // not reached: the signal ends the child +} + +} // namespace + +TEST_CASE("crash signals: a crash writes its stack to the log and to the standard error, and still ends by its signal") { + test::scratch_folder const folder{"crash_signals"}; + auto const log{folder.write("log.txt", "the last line of the log\n")}; + + std::array pipe_ends{}; + REQUIRE(pipe(pipe_ends.data()) == 0); + auto const child{fork()}; + REQUIRE(child >= 0); + if (child == 0) + crash_in_child(pipe_ends, log); + + close(pipe_ends[1]); + auto const errors{read_all(pipe_ends[0])}; + close(pipe_ends[0]); + int status{0}; + REQUIRE(waitpid(child, &status, 0) == child); + + CAPTURE(errors); + // the process ends as it would without the handler + CHECK(WIFSIGNALED(status)); + CHECK(WTERMSIG(status) == SIGSEGV); + // the report on the standard error, which the starter shows + CHECK(errors.find("Crash: signal 11 (SIGSEGV) at address 0x") != std::string::npos); + CHECK(errors.find("Version: test version 1.2") != std::string::npos); + CHECK(errors.find("Stack (addr2line") != std::string::npos); + // with the frames of the program that crashed + CHECK(errors.find("eu07_unit_tests") != std::string::npos); + // and the same at the end of the log, after what it held + auto const logtext{read_file(log)}; + CAPTURE(logtext); + CHECK(logtext.starts_with("the last line of the log\n")); + CHECK(logtext.find("Crash: signal 11 (SIGSEGV)") != std::string::npos); + CHECK(logtext.find("eu07_unit_tests") != std::string::npos); +} + +#endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 864338442..abfa6d5e7 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1294,6 +1294,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "crashdump.full") + { + ParseOne(Parser, CrashDumpFull); + return true; + } + if (token == "showsystemconsole") { ParseOne(Parser, ShowSystemConsole); @@ -1753,6 +1759,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); + export_as_text( Output, "crashdump.full", CrashDumpFull ); export_as_text( Output, "showsystemconsole", ShowSystemConsole ); export_as_text( Output, "logs.filter", DisabledLogTypes ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index c4a9a7267..c20adc05e 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -113,6 +113,10 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; + // the dump written when the simulator crashes (Windows): a small one by default, with the stacks, the threads, the + // modules, the memory the stacks point to and the modules' data. "crashdump.full yes" writes all the memory of the + // simulator instead, as large as the memory it took + bool CrashDumpFull{ false }; // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" // never, and with no entry it is written along with the physics logs std::optional BlackBox; diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index e0949aba6..f4032d808 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include @@ -115,6 +116,8 @@ void LogService() { std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); + // the stack of a crash on Linux goes to the end of this file + crash_signals::set_log_path(filename); } output << msg << "\n"; output.flush(); diff --git a/utilities/crashsignals.cpp b/utilities/crashsignals.cpp new file mode 100644 index 000000000..fa62e8955 --- /dev/null +++ b/utilities/crashsignals.cpp @@ -0,0 +1,234 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/crashsignals.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// the handler may only call what is safe in a signal: no allocation, no locks, no streams. so what it needs is +// kept in fixed buffers, filled in beforehand, and written with write() + +constexpr std::array crash_signal_list{SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT}; +// a handler that hangs (a crash inside the allocator or the loader, which backtrace() may need) ends this long after +constexpr unsigned int crash_report_timeout_seconds{5}; + +// a text of fixed size, filled outside the handler and read in it +template struct fixed_text { + std::array text{}; + std::atomic ready{false}; + + void set(std::string_view const Text) { + ready = false; + auto const length{std::min(Text.size(), text.size() - 1)}; + std::copy_n(Text.data(), length, text.data()); + text[length] = '\0'; + ready = true; + } + char const *get() const { return ready ? text.data() : nullptr; } +}; + +fixed_text<1024> &log_path() { + static fixed_text<1024> path; + return path; +} + +fixed_text<256> &version_text() { + static fixed_text<256> version; + return version; +} + +// the stack the handler runs on, so an overflow of the main thread's own stack is reported too +std::array &alternate_stack() { + static std::array stack{}; + return stack; +} + +void write_all(int const File, std::string_view Text) { + while (false == Text.empty()) { + auto const written{::write(File, Text.data(), Text.size())}; + if (written <= 0) + return; + Text.remove_prefix(static_cast(written)); + } +} + +void write_hex(int const File, std::uintptr_t const Value) { + constexpr std::size_t digits{sizeof(Value) * 2}; + constexpr std::string_view hexdigits{"0123456789abcdef"}; + std::array text{'0', 'x'}; + for (std::size_t digit = 0; digit < digits; ++digit) + text[2 + digit] = hexdigits[(Value >> (4 * (digits - 1 - digit))) & 0xF]; + write_all(File, {text.data(), text.size()}); +} + +void write_decimal(int const File, int const Value) { + std::array text{}; + auto position{text.size()}; + auto rest{static_cast(Value < 0 ? -Value : Value)}; + do { + text[--position] = static_cast('0' + rest % 10); + rest /= 10; + } while (rest != 0 && position > 1); + if (Value < 0) + text[--position] = '-'; + write_all(File, {text.data() + position, text.size() - position}); +} + +std::string_view signal_name(int const Signal) { + switch (Signal) { + case SIGSEGV: + return "SIGSEGV"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGABRT: + return "SIGABRT"; + default: + return "?"; + } +} + +// the signal being reported, for a report that hangs +std::atomic &crash_signal() { + static std::atomic signal{0}; + return signal; +} + +// a report that hangs is given up: the process ends by the signal of the crash, as it would have without the handler +void handle_report_timeout(int) { + auto const crashsignal{crash_signal().load()}; + raise(crashsignal); + // it is blocked while its own handler runs, which this one interrupted + sigset_t unblocked; + sigemptyset(&unblocked); + sigaddset(&unblocked, crashsignal); + sigprocmask(SIG_UNBLOCK, &unblocked, nullptr); +} + +struct crash_stack { + std::array frames{}; + int count{0}; +}; + +void write_report(int const File, int const Signal, siginfo_t const *Info, crash_stack const &Stack) { + write_all(File, "\nCrash: signal "); + write_decimal(File, Signal); + write_all(File, " ("); + write_all(File, signal_name(Signal)); + write_all(File, ")"); + // the address of the fault; an abort has none + if (Signal != SIGABRT && Info != nullptr) { + write_all(File, " at address "); + write_hex(File, reinterpret_cast(Info->si_addr)); + } + write_all(File, "\n"); + if (auto const *version{version_text().get()}) { + write_all(File, "Version: "); + write_all(File, version); + write_all(File, "\n"); + } + write_all(File, "Stack (addr2line -f -C -e ):\n"); + backtrace_symbols_fd(Stack.frames.data(), Stack.count, File); +} + +void handle_crash_signal(int const Signal, siginfo_t *Info, void *) { + crash_signal() = Signal; + struct sigaction timeout{}; + timeout.sa_handler = handle_report_timeout; + sigemptyset(&timeout.sa_mask); + sigaction(SIGALRM, &timeout, nullptr); + alarm(crash_report_timeout_seconds); + + crash_stack stack; + stack.count = backtrace(stack.frames.data(), static_cast(stack.frames.size())); + + if (auto const *path{log_path().get()}) { + if (auto const log{::open(path, O_WRONLY | O_APPEND | O_CLOEXEC)}; log >= 0) { + write_report(log, Signal, Info, stack); + ::close(log); + } + } + write_report(STDERR_FILENO, Signal, Info, stack); + + // the handler was taken off as it was called (SA_RESETHAND): the signal does what it always did + raise(Signal); +} + +} // namespace + +namespace crash_signals { + +void install(std::string_view const Version) { + static std::atomic installed{false}; + if (installed.exchange(true)) + return; + + version_text().set(Version); + + // backtrace() loads what it needs on its first call, which allocates: done here, not in the handler + std::array warmup{}; + backtrace(warmup.data(), static_cast(warmup.size())); + + stack_t alternate{}; + alternate.ss_sp = alternate_stack().data(); + alternate.ss_size = alternate_stack().size(); + sigaltstack(&alternate, nullptr); + + struct sigaction action{}; + action.sa_sigaction = handle_crash_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESETHAND; + // another crash signal of the same thread waits until the report is written, rather than starting a second one in + // its middle (a fault that comes while it is blocked still ends the process). a crash of another thread at the + // same moment may still write its report alongside + sigemptyset(&action.sa_mask); + for (auto const crashsignal : crash_signal_list) + sigaddset(&action.sa_mask, crashsignal); + for (auto const crashsignal : crash_signal_list) + sigaction(crashsignal, &action, nullptr); +} + +void set_log_path(std::string_view const Path) { + // whole, so the report finds the file wherever the simulator stands then + std::error_code error; + auto const path{std::filesystem::absolute(std::filesystem::path{Path}, error)}; + log_path().set(error ? std::string{Path} : path.string()); +} + +} // namespace crash_signals + +#else + +namespace crash_signals { + +void install(std::string_view) {} +void set_log_path(std::string_view) {} + +} // namespace crash_signals + +#endif diff --git a/utilities/crashsignals.h b/utilities/crashsignals.h new file mode 100644 index 000000000..feb526869 --- /dev/null +++ b/utilities/crashsignals.h @@ -0,0 +1,25 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the stack of a crash on Linux, where no dump is written: a signal of a fault (SIGSEGV, SIGBUS, SIGFPE, SIGILL) or +// SIGABRT writes the stack of the thread that took it to the log and to the standard error, which the starter shows, +// and then ends the simulator as the signal always did (a core dump where the system makes one). the addresses are +// read with addr2line on the eu07 file of the same version, which carries its symbols. elsewhere it does nothing +namespace crash_signals { + +// sets the handlers up, once. Version goes into the report, to tell which eu07 file the addresses belong to +void install(std::string_view Version); +// the log file the report is added to, once the log has opened it +void set_log_path(std::string_view Path); + +} // namespace crash_signals From 7524cfbcc2d3aa0e34d66ac298c994f9ce2c85b3 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:54:20 +0100 Subject: [PATCH 11/18] feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r --- tests/unit/test_track_uneven.cpp | 28 +++++++++++++++++++--------- tools/track_uneven_grade.py | 6 +++--- track_uneven_doc.md | 14 ++++++++------ world/Segment.cpp | 10 ++++++---- world/TrackUneven.h | 21 ++++++++++++--------- 5 files changed, 48 insertions(+), 31 deletions(-) diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp index b55de1644..a97791a32 100644 --- a/tests/unit/test_track_uneven.cpp +++ b/tests/unit/test_track_uneven.cpp @@ -63,7 +63,8 @@ TEST_CASE("uneven track: the cab keeps what the ride on the track doesn't stand TEST_CASE("uneven track: measures as the Id-14 limits for its value") { // appendix 1, class C at 80 km/h: 18 mm vertically, 17 mm sideways, 16 mm of twist on 5 m, gauge +10/-8 mm, 20 mm of cross level, J = 5.3 - auto const amplitude{track_uneven::stray_per_mm * 18.0 * 1000.0}; // mm + auto const amplitude{track_uneven::stray_up_per_mm * 18.0 * 1000.0}; // mm + auto const sideways{track_uneven::stray_side_per_mm * 18.0 * 1000.0}; // mm double const gauge{1.435}; double const step{0.5}; int const steps{4000}; @@ -76,6 +77,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") double level{0.0}; double j{0.0}; double away{0.0}; + double aside{0.0}; for (int line = 0; line < lines; ++line) { auto const heading{glm::pi() * (line + 0.37) / lines}; @@ -85,6 +87,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") std::array, 2> up; std::array, 2> side; std::vector middle; + std::vector across_middle; for (int i = 0; i < steps; ++i) { auto const point{start + along * (i * step)}; @@ -93,9 +96,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") auto const sign{rail == 0 ? 1.0 : -1.0}; auto const stray{track_uneven::field(point + across * (sign * 0.5 * gauge))}; up[rail].push_back((stray.y - sign * 0.5 * track_uneven::level(point, across)) * amplitude); - side[rail].push_back(glm::dot(stray, across) * amplitude); + side[rail].push_back(glm::dot(stray, across) * sideways); } - middle.push_back(track_uneven::field(point).y * amplitude); + auto const centre{track_uneven::field(point)}; + middle.push_back(centre.y * amplitude); + across_middle.push_back(glm::dot(centre, across) * sideways); } std::vector verticals; std::vector horizontals; @@ -120,6 +125,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") wander += peak(gauges) / lines; level += peak(levels) / lines; away += peak(middle) / lines; + aside += peak(across_middle) / lines; j += (deviation(verticals) + deviation(horizontals) + deviation(twists) + 0.5 * deviation(gauges)) / 3.5 / lines; } CHECK(vertical == doctest::Approx(18.0).epsilon(0.1)); @@ -128,7 +134,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") CHECK(wander == doctest::Approx(10.0).epsilon(0.2)); CHECK(level == doctest::Approx(20.0).epsilon(0.1)); CHECK(j == doctest::Approx(5.3).epsilon(0.2)); - CHECK(away < 40.0); // the long waves go past the 15 mm off the survey marks of appendix 1a + // the long waves go past the 15 mm off the survey marks of appendix 1a: most of the height of a track spectrum is in them, the 10 m chord + // hardly sees them + CHECK(away < 60.0); + // and sideways: about 4.5 cm, which a platform edge or the panels of a level crossing laid on the design are off the rails by + CHECK(aside < 50.0); } TEST_CASE("uneven track: a place strays the same every time") @@ -136,11 +146,11 @@ TEST_CASE("uneven track: a place strays the same every time") // no random numbers: changing these changes how every uneven track in every scenery looks glm::dvec3 const place{1234.5, 0.0, -678.9}; auto const stray{track_uneven::field(place)}; - CHECK(stray.x == doctest::Approx(0.309777548158).epsilon(1e-9)); - CHECK(stray.y == doctest::Approx(0.311350299745).epsilon(1e-9)); - CHECK(stray.z == doctest::Approx(-0.328429734019).epsilon(1e-9)); - CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.53 * -0.178598957983).epsilon(1e-9)); - CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.53 * -0.868291889902).epsilon(1e-9)); + CHECK(stray.x == doctest::Approx(0.158385385505).epsilon(1e-9)); + CHECK(stray.y == doctest::Approx(0.356190053667).epsilon(1e-9)); + CHECK(stray.z == doctest::Approx(0.200372098150).epsilon(1e-9)); + CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.35 * -0.178598957983).epsilon(1e-9)); + CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.35 * -0.868291889902).epsilon(1e-9)); } TEST_CASE("uneven track: tracks laid towards each other meet at one cant") diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index 81df2ce2a..ba60be900 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -38,10 +38,10 @@ CURVE_STEP = 1.0 / 2500.0 # a difference of curvature that counts as a change, RISE = 0.0273 * 4.5 # how fast pressure lifts a pantograph, m/s, by TDynamicObject::Update GAP_MOST = 0.006 # the gap to the wire allowed; at 0.01 m the voltage goes and the main breaker trips OVERSPEED = 1.1 # a driver can go this much over the speed of the track -# as up_waves and the dip of the joints in world/TrackUneven.h -STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0 +# as up_waves, stray_up_per_mm and the dip of the joints in world/TrackUneven.h +STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00229, 0.4, 3.0 GOLDEN = math.pi * (3.0 - math.sqrt(5.0)) -UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))] +UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0), (.0761, .1058, .1393, .176, .2175, .2651, .3215, .3887)))] TOKEN = re.compile(r"//[^\n]*|\S+") NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$") diff --git a/track_uneven_doc.md b/track_uneven_doc.md index e4822b971..1899abdc3 100644 --- a/track_uneven_doc.md +++ b/track_uneven_doc.md @@ -46,15 +46,17 @@ A track with `uneven 18` measures as follows (`tests/unit/test_track_uneven.cpp` | parameter | result | Id-14 | |--------------------------|--------|-----------| | vertical irregularities | 18 mm | 18 mm | -| horizontal irregularities | 19 mm | 17 mm | +| horizontal irregularities | 17 mm | 17 mm | | twist on a 5 m base | 15 mm | 16 mm | | gauge | ±10 mm | +10/-8 mm | -| cross level | 20 mm | 20 mm | -| J index | 6.1 | 5.3 | +| cross level | 21 mm | 20 mm | +| J index | 5.7 | 5.3 | + +Id-14 only gives the scale of the value: how a track at that value measures. What the waves look like follows the track spectra of the literature, see "How it works". ## How it works -Unevenness is a displacement field that depends on the position on the map, made of waves 5-42 m long. Vertically there are fewer short waves, so the rails come near the peak value more often, and there are also waves of 47-83 m: they hardly count on the 10 m chord, the body rises and falls on them, and a pantograph keeps up with them. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. +Unevenness is a displacement field that depends on the position on the map, made of waves 7-90 m long sideways and 8-110 m long vertically, about the bands D1-D3 of EN 13848. Their heights follow the shape of the track spectra of the US FRA and of ORE B176 (the German spectrum): a power spectral density of `Wc² / (W² (W² + Wc²))`, `Wc = 0.8245 rad/m`, so the longer a wave, the higher it is. Most of the height is in the long waves: they hardly count on the 10 m chord, the body rises and falls on them slowly, and the cab hardly feels them. At `uneven 18` a track goes up to about 5 cm up or down and about 4.5 cm sideways off its design over the long waves, and the short ones of 7-10 m, the ones the cab shakes on, are a few millimetres. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. Each component joins separately: @@ -67,7 +69,7 @@ The ends of joined paths meet in the middle between them, with one vector across The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the body and the cab shake follow the unevenness. The slope of the ballast takes up the difference, and its foot stays as designed, on the ground. -Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres. +Models from includes (e.g. switch drives and timbers), platform edges, level crossing panels, the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres, sideways up to about 4.5 cm at `uneven 18`. On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before, as far as it has something to put in their place. It goes by the track under the vehicle, and on a switch by the path set and what its joined tracks allow. Dips at the joints and cross level replace nothing, as they don't shake the cab all the way along or sideways. On tracks with no unevenness everything works as before. @@ -83,7 +85,7 @@ On a track with unevenness the track itself shakes the cab, in place of two of t This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration. -A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. +A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 1150, for example 9.6 mm at 120 km/h, 16 mm at 70 km/h and 29 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. The physics takes the curve radius and the grade from the design, so unevenness doesn't change them. It adds only the cross level towards derailment, about 0.06 m/s² at `uneven 18` against a threshold of about 3.2 m/s². diff --git a/world/Segment.cpp b/world/Segment.cpp index d1c5f2c89..4fc928d47 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -433,8 +433,10 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; + glm::dvec3 result { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); return result; } @@ -469,7 +471,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; } @@ -507,7 +509,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist From 6c94f9743b4df9164d6444f1e9813296125e9760 Mon Sep 17 00:00:00 2001 From: pol102 Date: Fri, 20 Nov 2026 03:55:34 +0100 Subject: [PATCH 12/18] feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude --- application/editormode.cpp | 135 ++++++++++++++++++++++++++++++++++++ application/editormode.h | 6 ++ editor/editorOrthophoto.cpp | 81 ++++++++++++++++++++-- editor/editorOrthophoto.hpp | 10 +++ editor/editorSettings.cpp | 15 ++++ editor/editorSettings.hpp | 9 +++ lang/editor_pl.po | 36 ++++++++++ utilities/Globals.h | 6 ++ vehicle/Camera.cpp | 28 +++++++- 9 files changed, 317 insertions(+), 9 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index bb87aa5cb..2da0dd104 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "application/editormode.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" @@ -4258,6 +4259,11 @@ void editor_mode::render_view_menu() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + if (ImGui::BeginMenu(STR_C("Camera speed"))) + { + render_camera_settings(); + ImGui::EndMenu(); + } ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); @@ -6989,6 +6995,8 @@ void editor_mode::enter() simulation::Blackbox.close(); // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen ui_layer::draw_cursor(m_draw_cursor); + apply_camera_settings(); + Global.EditorCameraOn = true; if (simulation::Region != nullptr) { @@ -7090,6 +7098,7 @@ void editor_mode::exit() track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there ui_layer::draw_cursor(false); + Global.EditorCameraOn = false; Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -7489,6 +7498,22 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in lay_switch_mode(); break; + case GLFW_KEY_GRAVE_ACCENT: + // ~ (left of 1): the orthophoto shown or hidden; with Ctrl what the camera sees downloaded before anything else + if (false == is_press(Action) || ImGui::GetIO().WantTextInput) + break; + if (Mods & GLFW_MOD_CONTROL) + { + orthophoto_hurry(); + break; + } + if (false == anyModifier) + { + m_orthophoto.enabled(false == m_orthophoto.enabled()); + ui()->set_status(m_orthophoto.enabled() ? STR("Orthophoto on (~)") : STR("Orthophoto off (~)")); + } + break; + case GLFW_KEY_BACKSPACE: // the switch being clicked off the view: the last point taken back if (m_switch_designer.open && m_switch_designer.picking) @@ -8094,3 +8119,113 @@ void editor_mode::render_top_tracks_choice(bool const Combo) if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); } + +void editor_mode::apply_camera_settings() +{ + auto const &camera{EditorSettings.camera()}; + Global.EditorCameraSpeed = camera.speed; + Global.EditorCameraFast = camera.fast; + Global.EditorCameraZoomed = camera.zoomed; +} + +void editor_mode::render_camera_settings() +{ + auto &camera{EditorSettings.camera()}; + auto changed{false}; + auto release{false}; + ImGui::PushItemWidth(180.0f * Global.ui_scale); + auto speed{static_cast(camera.speed)}; + if (ImGui::SliderFloat(STR_C("Speed of the camera"), &speed, 0.05f, 10.0f, "x %.2f", ImGuiSliderFlags_Logarithmic)) + { + camera.speed = speed; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was")); + auto fast{static_cast(camera.fast)}; + if (ImGui::SliderFloat(STR_C("Ctrl speeds it up"), &fast, 1.0f, 30.0f, "x %.1f", ImGuiSliderFlags_Logarithmic)) + { + camera.fast = fast; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was")); + ImGui::PopItemWidth(); + if (ImGui::Checkbox(STR_C("In the top view as fast as the view is zoomed"), &camera.zoomed)) + changed = release = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("As it was"))) + { + camera = {}; + changed = release = true; + } + if (changed) + apply_camera_settings(); + if (release) + EditorSettings.save(); +} + +void editor_mode::orthophoto_hurry() +{ + if (false == m_orthophoto.enabled()) + m_orthophoto.enabled(true); + // what the camera sees of the ground: rays through a grid over the screen to the level of the ground under the camera, or as far + // as the reach of the orthophoto along it where they don't come down to it (the sky) + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + auto const camera{GfxRenderer->Camera_Position()}; + // the level of the ground under the camera: the terrain, else the scenery; with neither the rays go as far as the reach + std::optional level; + // only a level below the camera: one above it (in a tunnel, or flown under the terrain) would put the hits behind it + if (double ground{0.0}; m_streamer.active() && m_streamer.height_at(camera.x, camera.z, ground) && ground < camera.y) + level = ground; + else if (std::vector found; Global.EditorOrtho == false) + { + auto const heights{ground_heights({camera}, true, &found)}; + if (false == found.empty() && found.front() != 0 && heights.front() < camera.y) + level = heights.front(); + } + double constexpr reach{2500.0}; + glm::dvec2 low{camera.x, camera.z}; + glm::dvec2 high{camera.x, camera.z}; + for (int j = 0; j <= 6; ++j) + for (int i = 0; i <= 6; ++i) + { + glm::vec2 const ndc{static_cast(i) / 3.0f - 1.0f, static_cast(j) / 3.0f - 1.0f}; + auto const point = [&inverse, &ndc](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + if (Global.EditorOrtho) + { + // the view straight down: the corners of the screen are where it reaches on the ground + auto const corner{camera + point(0.0f)}; // the view matrix is camera-relative + low = glm::min(low, glm::dvec2{corner.x, corner.z}); + high = glm::max(high, glm::dvec2{corner.x, corner.z}); + continue; + } + auto direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + continue; + direction = glm::normalize(direction); + glm::dvec2 flat{direction.x, direction.z}; + auto distance{reach}; + if (level && direction.y < -1e-6) + distance = std::min(reach, (camera.y - *level) / -direction.y * glm::length(flat)); + if (glm::length(flat) < 1e-6) + continue; + flat = glm::normalize(flat) * distance; + glm::dvec2 const hit{camera.x + flat.x, camera.z + flat.y}; + low = glm::min(low, hit); + high = glm::max(high, hit); + } + auto const count{m_orthophoto.hurry(low, high, camera)}; + ui()->set_status(count > 0 ? format(STR_C("Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)"), count) + : std::string{STR("Orthophoto: the view is all shown already (Ctrl+~)")}); +} diff --git a/application/editormode.h b/application/editormode.h index 148edb25a..dcf5e0e3d 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -871,6 +871,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); + // View > Camera speed: the speed of the free camera, the Ctrl multiplier, in the top view as fast as it's zoomed; kept in the + // settings of the editor and handed to the camera + void render_camera_settings(); + void apply_camera_settings(); + // ~ (Ctrl): the orthophoto of what the camera sees downloaded before the rest, the ones which failed tried again at once + void orthophoto_hurry(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor void render_environment_window(); bool m_environment_open{false}; diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index f663dd012..926983444 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -1032,6 +1032,20 @@ editor_orthophoto::statistics editor_orthophoto::stats() const return out; } +int editor_orthophoto::first_level(tile const &Tile, int const Level) +{ + // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow + // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk + if (Level > standard_pixels && Tile.level < standard_pixels) + return standard_pixels; + return Level; +} + +bool editor_orthophoto::outside_area(tile_key const &Key) const +{ + return false == m_area.empty() && 0 == m_area_tiles.count(Key); +} + int editor_orthophoto::level_for(int Distance, bool Hires) { // coarser imagery further away keeps the memory use of large radii in check @@ -1630,7 +1644,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) { tile_key const key{centre.first + dx, centre.second + dy}; // outside the download area: nothing asked for, nothing shown - if (false == m_area.empty() && 0 == m_area_tiles.count(key)) + if (outside_area(key)) { if (auto const found{m_tiles.find(key)}; found != m_tiles.end()) { @@ -1642,11 +1656,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; - int level = level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires); - // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow - // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk - if (level > standard_pixels && t.level < standard_pixels) - level = standard_pixels; + int const level = first_level(t, level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires)); if (t.empty || (t.level == level && t.alpha == m_alpha) || (t.requested == level && t.requested_alpha == m_alpha) || now < t.retry_at) continue; schedule(key, t, level, m_alpha); @@ -1713,7 +1723,8 @@ void editor_orthophoto::worker() continue; long long const dx = it->key.first - m_focus.first; long long const dy = it->key.second - m_focus.second; - long long const d = dx * dx + dy * dy; + // the tiles hurried (Ctrl+~) before all the others, the nearest of them first + long long const d = dx * dx + dy * dy - (m_urgent.count(it->key) > 0 ? (1LL << 40) : 0LL); if (d < bestdistance) { bestdistance = d; @@ -1730,6 +1741,7 @@ void editor_orthophoto::worker() { current = *best; m_queue.erase(best); + m_urgent.erase(current.key); m_running.insert(current.key); if (current.level >= hires_pixels) ++m_running_hires; @@ -1957,3 +1969,58 @@ void editor_orthophoto::draw(glm::mat4 const &ViewProjection, glm::dvec3 const & drawlist->PopTextureID(); } } + +bool editor_orthophoto::hurry_tile(tile_key const &Key, int const Distance) +{ + // as update() does: nothing asked for outside the download area, nor outside the area the service covers, where the requests + // can't be answered + if (outside_area(Key)) + return false; + auto &t{m_tiles[Key]}; + if (false == in_service_area(Key.first, Key.second)) + t.empty = true; + if (t.empty) + return false; + auto const level{first_level(t, level_for(Distance, m_config.hires))}; + t.retry_at = 0.0; + if (t.level == level && t.alpha == m_alpha) + return false; // already shown as it should be + if (false == (t.requested == level && t.requested_alpha == m_alpha)) + schedule(Key, t, level, m_alpha); + return true; +} + +std::size_t editor_orthophoto::hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera) +{ + if (false == m_enabled) + return 0; + // the tile of the camera as it is now: it isn't followed while the layer is off + m_camera_tile = camera_tile(Camera); + { + std::lock_guard lock(m_mutex); + m_focus = m_camera_tile; + } + auto const a{camera_tile(glm::dvec3{Min.x, 0.0, Min.y})}; + auto const b{camera_tile(glm::dvec3{Max.x, 0.0, Max.y})}; + tile_key const first{std::min(a.first, b.first), std::min(a.second, b.second)}; + tile_key const last{std::max(a.first, b.first), std::max(a.second, b.second)}; + auto const centre{m_camera_tile}; + int const radius = m_config.radius; + std::vector keys; + for (int y = first.second; y <= last.second; ++y) + for (int x = first.first; x <= last.first; ++x) + { + tile_key const key{x, y}; + auto const distance{std::max(std::abs(x - centre.first), std::abs(y - centre.second))}; + if (distance <= radius && hurry_tile(key, distance)) + keys.push_back(key); + } + auto const count{keys.size()}; + { + std::lock_guard lock(m_mutex); + m_urgent.clear(); + m_urgent.insert(keys.begin(), keys.end()); + } + m_wakeup.notify_all(); + return count; +} diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index d6fd43f8d..450dca9b7 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -102,6 +102,9 @@ class editor_orthophoto editor_orthophoto(editor_orthophoto const &) = delete; editor_orthophoto &operator=(editor_orthophoto const &) = delete; + // the tiles over a rectangle of the world (x, z; what the camera sees), within the reach around the camera, asked for before anything + // else, the ones which failed tried again at once. returns: how many were put at the front of the queue + std::size_t hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera); bool enabled() const { return m_enabled; } // disabling drops the queue and returns the gpu memory of the resident tiles void enabled(bool State); @@ -245,6 +248,12 @@ class editor_orthophoto }; static int level_for(int Distance, bool Hires); + // the level a tile is asked for at first: a tile showing nothing yet takes the standard image before the 4K one + static int first_level(tile const &Tile, int Level); + // the tile is outside the download area set, which then has no imagery asked for it + bool outside_area(tile_key const &Key) const; + // a tile of the view hurried: put at the front of the queue unless it's shown as it should be. true: counted among the hurried + bool hurry_tile(tile_key const &Key, int Distance); tile_key camera_tile(glm::dvec3 const &Camera) const; glm::dvec2 tile_corner(tile_key const &Key) const; // world (x,z) of the north-west corner void schedule(tile_key const &Key, tile &Tile, int Level, std::uint8_t Alpha); @@ -300,6 +309,7 @@ class editor_orthophoto bool m_prefetch_paused{false}; source m_prefetch_source; std::uint32_t m_prefetch_generation{0}; + std::set m_urgent; // asked for by hurry(): workers take these first; guarded by m_mutex std::atomic m_stop{false}; std::atomic m_generation{1}; diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index c7e162c46..dd475b183 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -198,6 +198,18 @@ bool editorSettings::load() layer.terms = fields[5]; m_wms_layers.push_back(layer); } + else if (key == "camera_speed") + { + parse(value, m_camera.speed); + m_camera.speed = std::clamp(m_camera.speed, 0.05, 10.0); + } + else if (key == "camera_fast") + { + parse(value, m_camera.fast); + m_camera.fast = std::clamp(m_camera.fast, 1.0, 30.0); + } + else if (key == "camera_zoomed") + m_camera.zoomed = (value == "1"); else if (key.rfind(origin_prefix, 0) == 0) { // northing;easting @@ -269,6 +281,9 @@ bool editorSettings::save() stream << "laying_heights " << (m_heights == lay_heights::points ? "points" : m_heights == lay_heights::level ? "level" : "fitted") << "\n"; for (auto const &layer : m_wms_layers) stream << "wms_layer " << (layer.visible ? 1 : 0) << ";" << layer.opacity << ";" << encoded(layer.url) << ";" << encoded(layer.layers) << ";" << encoded(layer.title) << ";" << encoded(layer.terms) << "\n"; + stream << "camera_speed " << m_camera.speed << "\n"; + stream << "camera_fast " << m_camera.fast << "\n"; + stream << "camera_zoomed " << (m_camera.zoomed ? 1 : 0) << "\n"; stream << std::fixed << std::setprecision(3); for (auto const &origin : m_orthophoto_origins) stream << origin.first << " " << origin.second.first << ";" << origin.second.second << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index 548f12b61..5223fca51 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -119,10 +119,19 @@ public: }; lay_heights heights() const { return m_heights; } void heights(lay_heights Heights) { m_heights = Heights; } + // the free camera: its speed, how many times faster Ctrl makes it, and in the top view as fast as the view is zoomed + struct camera_settings + { + double speed{1.0}; + double fast{30.0}; + bool zoomed{false}; // off as the editor was before: "As it was" means it + }; + camera_settings &camera() { return m_camera; } private: movement_scheme m_movement{movement_scheme::wsad}; orthophoto_settings m_orthophoto; + camera_settings m_camera; std::map> m_orthophoto_origins; std::vector m_wms_layers; double m_platform_edge{1.725}; diff --git a/lang/editor_pl.po b/lang/editor_pl.po index b765a98d6..6484fdd75 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14266,3 +14266,39 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" + +msgid "Camera speed" +msgstr "Prędkość kamery" + +msgid "Speed of the camera" +msgstr "Prędkość kamery" + +msgid "How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was" +msgstr "Jak szybko strzałki albo WSAD przesuwają kamerę, z Shiftem trochę szybciej; 1 = jak dotąd" + +msgid "Ctrl speeds it up" +msgstr "Przyspieszenie z Ctrl" + +msgid "How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was" +msgstr "Ile razy szybciej jedzie kamera z wciśniętym Ctrl, także Ctrl+Shift; 30 = jak dotąd" + +msgid "In the top view as fast as the view is zoomed" +msgstr "W widoku z góry prędkość zależna od powiększenia" + +msgid "Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom" +msgstr "Przybliżona mapa jedzie wolno, oddalona szybko: po ekranie zawsze w tym samym tempie" + +msgid "As it was" +msgstr "Przywróć domyślne" + +msgid "Orthophoto on (~)" +msgstr "Ortofoto włączone (~)" + +msgid "Orthophoto off (~)" +msgstr "Ortofoto wyłączone (~)" + +msgid "Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)" +msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" + +msgid "Orthophoto: the view is all shown already (Ctrl+~)" +msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" diff --git a/utilities/Globals.h b/utilities/Globals.h index c20adc05e..cdbab2c74 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -199,6 +199,12 @@ struct global_settings { bool EditorOrtho{ false }; float EditorOrthoExtent{ 150.f }; int EditorOrthoTracks{ 0 }; // the railway in the top view of the editor: 0 whole, 1 without the ballast, 2 the rails alone + // the free camera of the editor: its speed set in the View menu, the Ctrl multiplier of it, and in the top view whether it goes as far + // as the view reaches, so the map moves across the screen as fast zoomed in as out + bool EditorCameraOn{ false }; // the editor is on: its camera goes by the settings below + double EditorCameraSpeed{ 1.0 }; + double EditorCameraFast{ 30.0 }; + bool EditorCameraZoomed{ false }; GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury GLint iMaxCabTextureSize{ 4096 }; // largest allowed texture in vehicle cab int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 55d4691d1..fe1a85c9a 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -62,6 +62,30 @@ TCamera::OnCommand( command_data const &Command ) { // threshold position on stick between walk lerp and walk/run lerp auto const stickthreshold = 2.0 / 3.0; + // the free camera of the editor as fast as its View menu sets it, Ctrl by the multiplier set there, in the top view by how far it reaches + auto editorscale { 1.0 }; + auto editorfast { -1.0 }; + if( Global.EditorCameraOn && m_owner == nullptr ) { + editorscale = Global.EditorCameraSpeed; + if( Global.EditorOrtho && Global.EditorCameraZoomed ) { + editorscale *= std::clamp( static_cast( Global.EditorOrthoExtent ) / 150.0, 0.02, 200.0 ); + } + editorfast = Global.EditorCameraFast; + } + // how many times faster the fast command of a move makes it: the editor's own, or the free fly's (Default) and the cab's (Cab) + auto const fastness = [&]( bool const Fast, double const Editor, double const Default, double const Cab ) { + if( false == Fast ) { + return 1.0; + } + if( editorfast > 0.0 ) { + return Editor; + } + if( false == FreeFlyModeFlag ) { + return 1.0; + } + return m_owner == nullptr ? Default : Cab; + }; + bool iscameracommand { true }; switch( Command.command ) { @@ -82,7 +106,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::movehorizontalfast ? m_owner == nullptr ? 30.0 : 5.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::movehorizontalfast, editorfast, 30.0, 5.0 ); // left-right m_moverate.x = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -101,7 +125,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::moveverticalfast ? m_owner == nullptr ? 10.0 : 3.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::moveverticalfast, std::max( 1.0, editorfast / 3.0 ), 10.0, 3.0 ); // up-down m_moverate.y = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; From c5d14e93ac9947a88730b2e490e367c6dc5116b0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:39:40 +0100 Subject: [PATCH 13/18] fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number again ee3af0bf (#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416: ee3af0bf moved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r --- application/scenarioloaderuilayer.cpp | 2 +- tests/unit/test_utilities.cpp | 52 +++++++++++++++++++++++---- utilities/utilities.cpp | 4 +-- utilities/utilities.h | 7 +++- 4 files changed, 54 insertions(+), 11 deletions(-) diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 207a1756e..87366757f 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -88,7 +88,7 @@ std::vector scenarioloader_ui::get_random_trivia() json triviaData = json::parse(fileContent); // select random - int i = Random(0, static_cast(triviaData.size()) - 1); + int i = RandomInt(0, static_cast(triviaData.size()) - 1); std::string triviaStr = triviaData[i]["text"]; std::string background = triviaData[i]["background"]; if (triviaData[i].contains("scenery")) diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index d26472248..3bcb565a8 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -8,6 +8,9 @@ #include "utilities/Globals.h" #include "utilities/utilities.h" +#include +#include + // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their // oddities included. the ones which look like mistakes are listed in COVERAGE.md. the helpers which read from a // parser (LoadPoint, the sets, the map) are in test_parser.cpp @@ -115,16 +118,31 @@ TEST_CASE("utilities: clearing a flag needs all of its bits set") { TEST_CASE("utilities: random whole numbers are within the bounds, both included, given in any order") { std::set seen; for (auto draw{0}; draw < 200; ++draw) { - auto const value{Random(3, 7)}; + auto const value{RandomInt(3, 7)}; CHECK(value >= 3); CHECK(value <= 7); seen.insert(value); - auto const swapped{Random(7, 3)}; + auto const swapped{RandomInt(7, 3)}; CHECK(swapped >= 3); CHECK(swapped <= 7); } CHECK(seen.size() == 5); - CHECK(Random(5, 5) == 5); + CHECK(RandomInt(5, 5) == 5); +} + +TEST_CASE("utilities: whole-number bounds still give a real number in between") { + // the wind, the wheel flats, the truck hunting and the tachometer draw with whole-number bounds + static_assert(std::is_same_v); + auto fractions{0}; + for (auto draw{0}; draw < 50; ++draw) { + auto const value{Random(0, 4)}; + CHECK(value >= 0.0); + CHECK(value <= 4.0); + if (value != std::floor(value)) { + ++fractions; + } + } + CHECK(fractions > 0); } TEST_CASE("utilities: random numbers are within the bounds given in any order") { @@ -157,17 +175,37 @@ TEST_CASE("utilities: random numbers are within the bounds given in any order") } TEST_CASE("utilities: the same seed gives the same random numbers") { - std::vector first; + std::vector first; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - first.push_back(Random(0, 1000000)); + first.push_back(Random(0.0, 1000000.0)); } - std::vector second; + std::vector second; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - second.push_back(Random(0, 1000000)); + second.push_back(Random(0.0, 1000000.0)); } CHECK(first == second); + std::vector localfirst; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localfirst.push_back(RandomInt(0, 1000000)); + } + std::vector localsecond; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localsecond.push_back(RandomInt(0, 1000000)); + } + CHECK(localfirst == localsecond); +} + +TEST_CASE("utilities: the whole numbers are drawn from the local engine, not from that of the run's seed") { + // the trivia of the loading screen is drawn before a network client gets the seed of the session + Global.random_engine.seed(5); + auto const first{Random()}; + Global.random_engine.seed(5); + RandomInt(0, 9); + CHECK(Random() == first); } TEST_CASE("utilities: the local random numbers have an engine of their own") { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index d704fe9b7..a88b692c1 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -150,11 +150,11 @@ double Random(double min, double max) return dist(Global.random_engine); } -int Random(int min, int max) +int RandomInt(int min, int max) { if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB) std::uniform_int_distribution dist(min, max); - return dist(Global.random_engine); + return dist(Global.local_random_engine); } std::uint64_t true_random_seed() diff --git a/utilities/utilities.h b/utilities/utilities.h index 8c4181475..d2b3e5a6f 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -64,7 +64,12 @@ inline long Round(double const f) } double Random(double a, double b); -int Random(int min, int max); +// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number +// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the +// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it +// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would +// put that engine out of step with the other machines of a network session +int RandomInt(int min, int max); /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. From c556c4c8fdc51982b91bef6432f48c68febc78ab Mon Sep 17 00:00:00 2001 From: pol102 Date: Sat, 21 Nov 2026 10:39:53 +0100 Subject: [PATCH 14/18] fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 --- application/editormode.cpp | 3 ++ editor/editorOrthophoto.cpp | 68 ++++++++++++++++++++++++++------ editor/editorOrthophoto.hpp | 12 ++++++ editor/editorTerrainStreamer.cpp | 39 ++++++++++++++++++ editor/editorTerrainStreamer.hpp | 9 +++++ 5 files changed, 118 insertions(+), 13 deletions(-) diff --git a/application/editormode.cpp b/application/editormode.cpp index 2da0dd104..c9b50c3f0 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -601,6 +601,9 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); }); Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // with the heightmap terrain, a new tile waits while a chunk under it is still to come; where none is nor will be, or the walk of + // the chunks doesn't reach, it lies on the other ground or on the NMT guess as before. A scenery without it as before + Layer.coming_source([](glm::dvec2 const &Min, glm::dvec2 const &Max) { return EditorTerrain.active() && EditorTerrain.ground_coming(Min, Max); }); // the imagery often comes before the terrain made from the model: it lies where the terrain will be Layer.guess_source([this](double const X, double const Z, double &Height) { if (nmt_ground(X, Z, Height)) diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index 926983444..ac198746c 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -937,23 +937,47 @@ void editor_orthophoto::ground_arrived() { if (!m_height) return; - for (auto &entry : m_tiles) + for (auto &[key, t] : m_tiles) { - auto &t{entry.second}; - if (!t.grounded || !t.guessed) - continue; - // the middle and the corners: a chunk of the terrain is much larger than a tile, it covers some of these when it comes. A tile - // lying flat, with nothing to go by, also goes onto the model once it's in - glm::dvec2 const corner = tile_corner(entry.first); - for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) - if (double y; m_height(corner.x - u * tile_size, corner.y - v * tile_size, y) || (t.heights.empty() && m_guess && m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y))) - { - t.grounded = false; - break; - } + if (t.grounded && ground_came(key, t)) + t.grounded = false; } } +bool editor_orthophoto::waits_for_ground(tile_key const &Key) const +{ + // a tile laid out already stays, sampled again when its ground comes (ground_came) + if (!m_coming || m_tiles.contains(Key)) + return false; + glm::dvec2 const corner = tile_corner(Key); + return m_coming(corner - glm::dvec2{tile_size}, corner); +} + +bool editor_orthophoto::ground_came(tile_key const &Key, tile const &Tile) const +{ + glm::dvec2 const corner = tile_corner(Key); + // a tile lying flat, with nothing to go by, also goes onto the model once it's in: the middle and the corners + if (Tile.guessed && Tile.heights.empty() && m_guess) + for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) + if (double y; m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y)) + return true; + // the points the ground didn't answer, every second one of the grid (16 m) and the edges: a chunk of the terrain is about as + // large as a tile and comes over a part of it, often a band along a side; partly answered tiles count too, not only the guessed + static_assert(ground_grid % 2 == 0, "the edges of the grid are among its even points"); + int constexpr samples{ground_grid + 1}; + double constexpr step{tile_size / ground_grid}; + for (auto const index : Tile.unanswered) + { + int const i{index % samples}; + int const j{index / samples}; + if (i % 2 != 0 || j % 2 != 0) + continue; + if (double y; m_height(corner.x - i * step, corner.y - j * step, y)) + return true; + } + return false; +} + void editor_orthophoto::detach_scene() { for (auto &entry : m_tiles) @@ -1247,6 +1271,7 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) Tile.scene_dirty = true; Tile.heights.clear(); Tile.surface.clear(); + Tile.unanswered.clear(); glm::dvec2 const corner = tile_corner(Key); glm::dvec2 const min(corner.x - tile_size, corner.y - tile_size); @@ -1318,6 +1343,21 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) } } + // the points the ground didn't answer: the ground coming there later (the terrain loaded after the imagery, which comes from the + // disk cache at once) has the tile sampled again, rather than left at the heights filled in or guessed now + Tile.unanswered.clear(); + auto const columns{static_cast(samples)}; + for (std::size_t index = 0; index < heights.size(); ++index) + { + if (heights[index] != no_height) + continue; + // in the scene the heights come from the triangles, and a steep spot (a wall, a quarry face) gives none: where the heightmap + // terrain answers the point, its ground is there already, and ground_came() would find it again on every chunk that comes + if (double y; surface && m_height && m_height(corner.x - static_cast(index % columns) * step, corner.y - static_cast(index / columns) * step, y)) + continue; + Tile.unanswered.push_back(static_cast(index)); + } + // holes (places without ground) take the average of their neighbours, spreading inwards std::size_t missing = std::count(heights.begin(), heights.end(), no_height); if (missing == heights.size()) @@ -1653,6 +1693,8 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) } continue; } + if (waits_for_ground(key)) + continue; tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index 450dca9b7..4811c99c1 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -120,6 +120,10 @@ class editor_orthophoto // the heights the ground will have where there's none yet, as of the terrain model on its way: a tile laid out before its // ground comes lies there, or level with the tiles beside, rather than at the height of the layer far below or above void guess_source(height_query Query) { m_guess = std::move(Query); } + // true while the ground under an XZ rectangle (Min/Max are x,z) is still to come. A new tile there waits for it, rather than + // being laid out at the height of the layer; elsewhere it lies on whatever ground there is, or on the guess, as without it + using coming_query = std::function; + void coming_source(coming_query Query) { m_coming = std::move(Query); } // the area the imagery is downloaded in, a polygon of PUWG 1992 (easting, northing): its tiles go to the disk cache in the // background, the products the settings ask for, and no tile outside it is asked for around the camera. Empty: no area, the // tiles around the camera as before @@ -239,6 +243,9 @@ class editor_orthophoto float height_max{0.0f}; std::vector surface; // upward facing ground triangles clipped to the tile (3 vertices each) bool guessed{false}; // no ground under it when sampled: the heights guessed, from the terrain model or the tiles beside + // the points of the grid of the heights the ground didn't answer when sampled (rows north->south, as heights): filled from + // the points beside or guessed, and sampled again once the ground comes under one of them + std::vector unanswered; // scene geometry scene::basic_section *section{nullptr}; // section holding the shape (nullptr = not in the scene) scene::basic_cell *cell{nullptr}; // set instead of the section's shape list when the shape is translucent @@ -262,6 +269,10 @@ class editor_orthophoto void release_tile(tile &Tile); texture_slot acquire_slot(); void sample_ground(tile_key const &Key, tile &Tile); + // the ground has come under a point of the tile which had none when it was sampled + bool ground_came(tile_key const &Key, tile const &Tile) const; + // a new tile isn't asked for yet: the ground under it is still to come + bool waits_for_ground(tile_key const &Key) const; // the height of the ground sampled under a tile beside Own at the point, the tiles with guessed heights left out bool sampled_height(tile_key const &Own, double const X, double const Z, float &Height) const; void build_shape(tile_key const &Key, tile &Tile); @@ -281,6 +292,7 @@ class editor_orthophoto ground_query m_ground; height_query m_height; height_query m_guess; + coming_query m_coming; scene::basic_region *m_region{nullptr}; // region the scene geometry was put into std::multimap m_free_chunks; // geometry chunks by capacity, reused between tiles // the scene opacity is baked into the textures, which means reading the tiles again; applied once the value settles diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a681b1a9e..9c00017de 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include terrain_streamer EditorTerrain; @@ -907,6 +908,44 @@ bool terrain_streamer::owns(gfx::geometry_handle const &Geometry) const return false; } +bool terrain_streamer::in_walk(chunk_key const &Key) const +{ + // the circle update() walks around the camera and around where it's heading + auto const within = [this, &Key](chunk_key const &Centre) { + auto const dx{Key.first - Centre.first}; + auto const dz{Key.second - Centre.second}; + return std::abs(dx) <= m_walkradius && std::abs(dz) <= m_walkradius && dx * dx + dz * dz <= (m_walkradius + 1) * (m_walkradius + 1); + }; + return within(m_walkhere) || within(m_walkthere); +} + +bool terrain_streamer::chunk_coming(chunk_key const &Key) const +{ + if (m_chunks.contains(Key) || m_removed.contains(Key)) + return false; + if (m_loading.contains(Key)) + return true; + // a chunk the walk doesn't reach at this distance isn't loaded, so it isn't waited for: it's taken in when the camera comes near + if (false == in_walk(Key)) + return false; + // still to come while its pack isn't read yet, or it's in its pack; not there where the pack is read without it + auto const pack{m_packs.find(heightmap::pack_of(Key))}; + if (pack == m_packs.end() || pack->second.status == pack_state::state::unknown || pack->second.status == pack_state::state::loading) + return true; + return pack->second.status == pack_state::state::ready && pack->second.file->has(Key); +} + +bool terrain_streamer::ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const first{heightmap::chunk_at(Low.x, Low.y)}; + auto const last{heightmap::chunk_at(High.x, High.y)}; + for (auto z{std::min(first.second, last.second)}; z <= std::max(first.second, last.second); ++z) + for (auto x{std::min(first.first, last.first)}; x <= std::max(first.first, last.first); ++x) + if (chunk_coming(chunk_key{x, z})) + return true; + return false; +} + bool terrain_streamer::exists(chunk_key const &Key) const { if (m_chunks.count(Key) > 0) diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index cf8407ac1..760335a75 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -81,6 +81,10 @@ class terrain_streamer std::string stats() const; // chunks in the pack files and in memory, less the removed ones; the files known so far bool exists(chunk_key const &Key) const; + // true while a chunk over an XZ rectangle (Low/High are x,z) is still to come at this distance of the camera: being loaded, or + // within the walk around the camera and in its pack or with its pack not read yet. False where all of them are in memory, where + // none is nor will be, and where the walk doesn't reach + bool ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const; // editing; the chunks changed are written to the files by save() heightmap::manifest const &manifest() const { return m_manifest; } @@ -235,6 +239,11 @@ class terrain_streamer scene::basic_cell *cell{nullptr}; }; + // within the circle of chunks the last walk of update() asked for + bool in_walk(chunk_key const &Key) const; + // the chunk is still to come at this distance of the camera (see ground_coming) + bool chunk_coming(chunk_key const &Key) const; + void start_workers(); void stop_workers(); void worker(); From 988c0af5895a01edca87a0faa474003b903e9e2e Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:40:07 +0100 Subject: [PATCH 15/18] fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r --- application/editormode.cpp | 4 +- application/editormode.h | 3 + editor/editorGeoMap.cpp | 8 +- editor/editorGeoMap.hpp | 2 + editor/editorHttp.cpp | 261 ++++++++++++++++++++++++-------- editor/editorOrthophoto.cpp | 14 +- editor/editorOrthophoto.hpp | 5 +- tests/unit/CMakeLists.txt | 2 + tests/unit/test_editor_http.cpp | 138 +++++++++++++++++ 9 files changed, 363 insertions(+), 74 deletions(-) create mode 100644 tests/unit/test_editor_http.cpp diff --git a/application/editormode.cpp b/application/editormode.cpp index c9b50c3f0..a40c6e081 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -618,6 +618,8 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) editor_mode::~editor_mode() { editor_track::observe(nullptr); + // the capabilities of a WMS service being read are given up rather than waited for to their timeouts + m_wms_adding.closing = true; } std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const @@ -4101,7 +4103,7 @@ void editor_mode::render_wms_adding() adding.info.reset(); adding.ticked.clear(); adding.service = url; - adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + adding.reading = std::async(std::launch::async, [url, closing = &adding.closing]() { return editor_orthophoto::describe(url, [closing]() { return closing->load(); }); }); } if (adding.reading.valid()) { diff --git a/application/editormode.h b/application/editormode.h index dcf5e0e3d..d25840e18 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -915,6 +916,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri { std::array url{}; std::array filter{}; + // the reading is given up: the editor goes. before the reading, so it outlives the future waiting for the reading to end + std::atomic closing{false}; std::future reading; std::optional info; std::string service; // the address the capabilities were read of diff --git a/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index ab7f74b24..68b153559 100644 --- a/editor/editorGeoMap.cpp +++ b/editor/editorGeoMap.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorGeoMap.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorHttp.hpp" #include "editor/editorOrthophoto.hpp" #include "utilities/translation.h" @@ -164,6 +165,8 @@ bool parse_place(std::string const &Text, glm::dvec2 &Point) editor_map::~editor_map() { + // the download running is broken off rather than waited for to its end or its timeout + m_closing = true; if (m_request.valid()) m_request.wait(); release(); @@ -328,12 +331,13 @@ void editor_map::request(glm::vec2 const &Size) char bbox[160]; std::snprintf(bbox, sizeof(bbox), "%.1f,%.1f,%.1f,%.1f", low.x, low.y, high.x, high.y); auto const url{kMapService + "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=osm&STYLES=&SRS=EPSG:2180&BBOX=" + bbox + "&WIDTH=" + std::to_string(width) + "&HEIGHT=" + std::to_string(height) + "&FORMAT=image/png"}; - m_request = std::async(std::launch::async, [url, low, high]() { + m_request = std::async(std::launch::async, [url, low, high, closing = &m_closing]() { image result; result.low = low; result.high = high; std::vector data; - if (false == editor_http_get(url, data, result.error)) + thread_local editor_http::client client; + if (false == client.get(url, data, result.error, [closing]() { return closing->load(); })) return result; int w{0}, h{0}, components{0}; // the texture loader turns the stb flip on for the whole process only once it loads its first texture: this thread diff --git a/editor/editorGeoMap.hpp b/editor/editorGeoMap.hpp index 5c160095b..a1dd07124 100644 --- a/editor/editorGeoMap.hpp +++ b/editor/editorGeoMap.hpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -86,6 +87,7 @@ class editor_map glm::vec2 m_pressed{0.f}; bool m_dragging{false}; std::future m_request; + std::atomic m_closing{false}; // the download of the map is given up: the map goes std::uint64_t m_texture{0}; glm::dvec2 m_image_low{0.0}; glm::dvec2 m_image_high{0.0}; diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 81a195aeb..cbda581f0 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -45,15 +45,209 @@ struct client::platform #if defined(_WIN32) +namespace +{ + +DWORD constexpr kStopCheck{50}; // ms between the looks at whether the transfer is to be given up + +// what the callback of WinHTTP hands over to the thread waiting for it +struct transfer_state +{ + HANDLE done{::CreateEventW(nullptr, FALSE, FALSE, nullptr)}; // the operation begun finished or failed + HANDLE closed{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; // the request is called back no more + DWORD error{ERROR_SUCCESS}; // of the operation that failed + DWORD size{0}; // bytes available or read + + transfer_state() = default; + transfer_state(transfer_state const &) = delete; + transfer_state &operator=(transfer_state const &) = delete; + ~transfer_state() + { + if (done != nullptr) + ::CloseHandle(done); + if (closed != nullptr) + ::CloseHandle(closed); + } +}; + +void CALLBACK on_status(HINTERNET, DWORD_PTR const Context, DWORD const Status, LPVOID const Info, DWORD const Length) +{ + auto *state{reinterpret_cast(Context)}; + if (state == nullptr) + return; + switch (Status) + { + case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: + case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: + break; + case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: + state->size = *static_cast(Info); + break; + case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: + state->size = Length; + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + state->error = static_cast(Info)->dwError; + break; + case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: + ::SetEvent(state->closed); + return; + default: + return; + } + ::SetEvent(state->done); +} + +// one GET on a connection of its own. the steps of WinHTTP are asynchronous and waited for while the stop is looked at, so a +// transfer is given up at once also while a service keeps the connection waiting: the closing of the editor doesn't wait for +// the timeouts of a service that doesn't answer +class transfer +{ + public: + transfer(stop_check const &Stop, std::string &Error) : + m_stop(Stop), + m_error(Error) + { + } + ~transfer() + { + close(); + } + transfer(transfer const &) = delete; + transfer &operator=(transfer const &) = delete; + + bool open(HINTERNET const Session, std::wstring const &Host, INTERNET_PORT const Port, std::wstring const &Path, bool const Secure) + { + if (m_state.done == nullptr || m_state.closed == nullptr) + return failed(::GetLastError()); + m_connection = ::WinHttpConnect(Session, Host.c_str(), Port, 0); + if (m_connection == nullptr) + return failed(::GetLastError()); + m_request = ::WinHttpOpenRequest(m_connection, L"GET", Path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, Secure ? WINHTTP_FLAG_SECURE : 0); + if (m_request == nullptr) + return failed(::GetLastError()); + auto context{reinterpret_cast(&m_state)}; + if (false == ::WinHttpSetOption(m_request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context))) + return failed(::GetLastError()); + if (::WinHttpSetStatusCallback(m_request, on_status, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, 0) == WINHTTP_INVALID_STATUS_CALLBACK) + return failed(::GetLastError()); + m_called_back = true; + return true; + } + + bool send() + { + return step([this]() { return ::WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast(&m_state)); }); + } + + bool receive() + { + return step([this]() { return ::WinHttpReceiveResponse(m_request, nullptr); }); + } + + DWORD status() const + { + DWORD status{0}; + DWORD size{sizeof(status)}; + ::WinHttpQueryHeaders(m_request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + return status; + } + + // the whole body of the response + bool read_all(std::vector &Out) + { + while (true) + { + if (m_stop()) + { + m_error = "cancelled"; + return false; + } + if (false == step([this]() { return ::WinHttpQueryDataAvailable(m_request, nullptr); })) + return false; + auto const available{m_state.size}; + if (available == 0) + return true; + if (Out.size() + available > kLargest) + { + m_error = kTooLarge; + Out.clear(); + return false; + } + auto const offset{Out.size()}; + Out.resize(offset + available); + auto const read{step([this, &Out, offset, available]() { return ::WinHttpReadData(m_request, Out.data() + offset, available, nullptr); })}; + Out.resize(offset + (read ? m_state.size : 0)); + if (false == read) + return false; + } + } + + void close() + { + if (m_request != nullptr) + { + ::WinHttpCloseHandle(m_request); + m_request = nullptr; + // the closing is the last callback: after it the state, and the buffer of a read broken off, are no longer written to + if (m_called_back) + ::WaitForSingleObject(m_state.closed, INFINITE); + m_called_back = false; + } + if (m_connection != nullptr) + { + ::WinHttpCloseHandle(m_connection); + m_connection = nullptr; + } + } + + private: + bool failed(DWORD const Code) + { + m_error = "WinHTTP error " + std::to_string(Code); + return false; + } + + // begins an operation and waits for it: false when it failed, or a stop was asked for meanwhile + template bool step(Begin const &Operation) + { + m_state.error = ERROR_SUCCESS; + if (false == Operation()) + return failed(::GetLastError()); + while (::WaitForSingleObject(m_state.done, kStopCheck) != WAIT_OBJECT_0) + { + if (m_stop()) + { + // closed at once: the operation broken off doesn't write into the buffer any more once this returns + close(); + m_error = "cancelled"; + return false; + } + } + if (m_state.error != ERROR_SUCCESS) + return failed(m_state.error); + return true; + } + + stop_check const &m_stop; + std::string &m_error; + transfer_state m_state; + HINTERNET m_connection{nullptr}; + HINTERNET m_request{nullptr}; + bool m_called_back{false}; // the closing of the request is called back +}; + +} // namespace + client::client() : m_platform(std::make_unique()) { wchar_t const *agent = L"MaSzyna-editor"; #ifdef WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); #endif if (m_platform->session == nullptr) // automatic proxy needs windows 8.1+ - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (m_platform->session != nullptr) ::WinHttpSetTimeouts(m_platform->session, 10000, 10000, 15000, 20000); } @@ -94,64 +288,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st std::wstring const host(parts.lpszHostName, parts.dwHostNameLength); std::wstring const path = std::wstring(parts.lpszUrlPath, parts.dwUrlPathLength) + std::wstring(parts.lpszExtraInfo, parts.dwExtraInfoLength); - HINTERNET connection = ::WinHttpConnect(m_platform->session, host.c_str(), parts.nPort, 0); - HINTERNET request = connection ? ::WinHttpOpenRequest(connection, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) - : nullptr; - auto const close = [&]() { - if (request != nullptr) - ::WinHttpCloseHandle(request); - if (connection != nullptr) - ::WinHttpCloseHandle(connection); - }; - - if (request == nullptr || !::WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || !::WinHttpReceiveResponse(request, nullptr)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); + transfer request{Stop, Error}; + if (false == request.open(m_platform->session, host, parts.nPort, path, parts.nScheme == INTERNET_SCHEME_HTTPS) || false == request.send() || false == request.receive()) return false; - } - - DWORD status{0}; - DWORD statussize{sizeof(status)}; - ::WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statussize, WINHTTP_NO_HEADER_INDEX); - - for (;;) - { - if (Stop()) - { - Error = "cancelled"; - close(); - return false; - } - DWORD available{0}; - if (!::WinHttpQueryDataAvailable(request, &available)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - if (available == 0) - break; - if (Out.size() + available > kLargest) - { - Error = kTooLarge; - close(); - Out.clear(); - return false; - } - std::size_t const offset = Out.size(); - Out.resize(offset + available); - DWORD received{0}; - if (!::WinHttpReadData(request, Out.data() + offset, available, &received)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - Out.resize(offset + received); - } - close(); + auto const status{request.status()}; + if (false == request.read_all(Out)) + return false; + request.close(); if (status != 200) { diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index ac198746c..d3254a2c1 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -63,12 +63,6 @@ double steady_seconds() } // namespace -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error) -{ - thread_local http_client client; - return client.get(Url, Out, Error, []() { return false; }); -} - namespace { @@ -688,7 +682,7 @@ std::string xml_element(std::string const &Xml, std::string const &Tag, std::siz } // namespace -editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service) +editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service, std::function const &Stop) { service_info info; auto url{Service}; @@ -700,8 +694,10 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S // a few tries, the services drop connections and time out now and then std::vector data; auto read{false}; - for (int attempt = 0; attempt < 3 && false == read; ++attempt) - read = editor_http_get(url, data, info.error); + stop_check const stopping{Stop ? Stop : stop_check{[]() { return false; }}}; + thread_local http_client client; + for (int attempt = 0; attempt < 3 && false == read && false == stopping(); ++attempt) + read = client.get(url, data, info.error, stopping); if (false == read) return info; info.error.clear(); diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index 4811c99c1..b56052e7e 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -28,8 +28,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" // material_handle #include "rendering/geometrybank.h" // gfx::geometry_handle -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error); - namespace scene { class basic_region; @@ -183,7 +181,8 @@ class editor_orthophoto bool puwg{false}; std::string error; }; - static service_info describe(std::string const &Service); + // Stop: true to give the reading up + static service_info describe(std::string const &Service, std::function const &Stop = {}); static std::string cache_directory(); private: diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c1ad98f35..cca503a01 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -32,6 +32,8 @@ add_executable(${UNIT_TESTS_NAME} # and the fouling points of the switches, widened in the curves as the gauge is "${CMAKE_SOURCE_DIR}/editor/editorGauge.cpp" "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" + # and the http client the editor fetches its aids with + "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp new file mode 100644 index 000000000..ffdfe9959 --- /dev/null +++ b/tests/unit/test_editor_http.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorHttp.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// a service on this machine. with no reply it takes the connection and the request and never answers, as geoportal.gov.pl +// does now and then +class local_server { + public: + explicit local_server(std::string Reply = {}) : + m_reply(std::move(Reply)) { + m_acceptor.open(asio::ip::tcp::v4()); + m_acceptor.bind({asio::ip::address_v4::loopback(), 0}); + m_acceptor.listen(); + m_port = m_acceptor.local_endpoint().port(); + m_thread = std::jthread{[this]() { serve(); }}; + } + ~local_server() { + m_done = true; + // a connection of its own wakes the server waiting for one + asio::ip::tcp::socket wake{m_context}; + asio::error_code ignored; + wake.connect({asio::ip::address_v4::loopback(), m_port}, ignored); + wake.close(ignored); + m_thread.join(); + } + local_server(local_server const &) = delete; + local_server &operator=(local_server const &) = delete; + + std::string url() const { + return std::format("http://127.0.0.1:{}/wcs?REQUEST=GetCapabilities", m_port); + } + + private: + void serve() { + while (false == m_done) { + asio::ip::tcp::socket socket{m_context}; + asio::error_code error; + m_acceptor.accept(socket, error); + if (error) + return; + if (false == m_reply.empty()) { + answer(socket); + continue; + } + // the request is left without an answer, the connection open, until the server goes + while (false == m_done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + // the reply once the whole request is read, then the connection closed + void answer(asio::ip::tcp::socket &Socket) const { + asio::error_code error; + asio::streambuf request; + asio::read_until(Socket, request, "\r\n\r\n", error); + if (!error) + asio::write(Socket, asio::buffer(m_reply), error); + Socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); + } + + std::string const m_reply; + asio::io_context m_context; + asio::ip::tcp::acceptor m_acceptor{m_context}; + unsigned short m_port{0}; + std::atomic m_done{false}; + std::jthread m_thread; +}; + +// the requests to the local server would go to a proxy named in the environment, which can't reach it +bool proxied() { + for (char const *variable : {"http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"}) { + if (char const *value{std::getenv(variable)}; value != nullptr && *value != '\0') + return true; + } + return false; +} + +} // namespace + +TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { + if (false == editor_http::available() || proxied()) + return; // a build with no http client, or a proxy in the way + local_server server; + auto const start{std::chrono::steady_clock::now()}; + auto const elapsed = [start]() { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); }; + editor_http::client client; + std::vector data; + std::string error; + // the stop comes while the client waits for the answer, long before any of its timeouts + auto const got{client.get(server.url(), data, error, [&elapsed]() { return elapsed() > 0.3; })}; + CHECK_FALSE(got); + CHECK_FALSE(error.empty()); + // the receive timeout is 20 s; the transfer ends within a moment of the stop (libcurl looks at it about once a second) + CHECK(elapsed() < 5.0); +} + +TEST_CASE("editor http: the whole body of a response is read") { + if (false == editor_http::available() || proxied()) + return; + std::string body(100000, '\0'); + for (std::size_t i = 0; i < body.size(); ++i) + body[i] = static_cast('a' + i % 26); + local_server server{std::format("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK(client.get(server.url(), data, error, []() { return false; })); + CHECK(error.empty()); + CHECK(std::string(data.begin(), data.end()) == body); +} + +TEST_CASE("editor http: the body of an error is kept with the status in the error") { + if (false == editor_http::available() || proxied()) + return; + // the terrain model service tells a place outside of its coverage in the body of an error + std::string const body{"outside requested coverage"}; + local_server server{std::format("HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get(server.url(), data, error, []() { return false; })); + CHECK(error == "HTTP 400"); + CHECK(std::string(data.begin(), data.end()) == body); +} From abdb814469dec0e5483aa262af42c37238517424 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:53:11 +0100 Subject: [PATCH 16/18] revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r --- simulation/simulationenvironment.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..4e8c0e5f7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -26,11 +26,12 @@ namespace { float turbidity_of( float const Overcast ) { + if( Overcast <= 0.10 ) { return 3.f; } if( Overcast <= 0.20 ) { return 4.f; } - if( Overcast <= 0.40 ) { return 5.f; } - if( Overcast <= 0.60 ) { return 6.f; } - if( Overcast <= 0.70 ) { return 7.f; } - if( Overcast <= 0.80 ) { return 8.f; } + if( Overcast <= 0.60 ) { return 5.f; } + if( Overcast <= 0.70 ) { return 6.f; } + if( Overcast <= 0.80 ) { return 7.f; } + if( Overcast <= 0.90 ) { return 8.f; } return 9.f; } From 65d3c020ebe85867183c67ad9c0ceedf704f0b40 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:26:20 +0100 Subject: [PATCH 17/18] fix(render): the free camera blurs with its own movement, the grass racing under it no longer strobes in rings (#441) The motion blur took the movement of the vehicle the camera sits in and nothing else, so in freefly (and the debug camera) the world got no blur from the camera at all. Low over grass the texture under the camera then moved tens of pixels a frame and strobed: rings around the camera, at the distances its pattern repeats, stronger with shift and ctrl, gone above about 20 m, worst on a 165 Hz screen. * the camera with no vehicle of its own blurs the world with its movement since the frame before, as a vehicle does with get_future_movement(); a jump of 50 m or more (a camera preset) is no movement * that movement is held to half a metre a frame: the blur takes the scene where the camera will be, and a camera faster than that passes the ground at the bottom of the screen within a frame, where its motion turned over into a bright band. with the shutter of the blur it still smears metres * the blur shader skips samples off the picture instead of reading its edge row again and again --- rendering/opengl33renderer.cpp | 25 +++++++++++++++++++++++++ rendering/opengl33renderer.h | 2 ++ shaders/postfx_motionblur.frag | 4 ++++ 3 files changed, 31 insertions(+) diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 3a3008a44..5215a7b9f 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -988,6 +988,31 @@ void opengl33_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const *vehicle = Global.pCamera.m_owner; glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); future = glm::translate(mv, -glm::vec3(vehicle->get_future_movement())) * glm::inverse(mv); + m_freecameraposition.reset(); + } + else if (vp.main) + { + // the free camera (freefly, debug camera) blurs the world with its own movement, as a vehicle does with its: + // without it the ground racing under a low camera strobes in rings at the distances its texture repeats. + // the movement of the frame before stands for the one to come; a jump (a camera preset) is no movement + auto const position{Global.pCamera.Pos}; + if (m_freecameraposition) + { + auto movement{glm::vec3(position - *m_freecameraposition)}; + auto const length{glm::length(movement)}; + if (length < 50.f) + { + // the blur takes the scene where the camera will be: a fast camera (shift, ctrl) moves past the ground + // at the bottom of the screen within a frame, it ends up behind it there and its motion turns over + // into a bright band. half a metre a frame still blurs metres with the shutter of the motion blur + auto const maxmovement{0.5f}; + if (length > maxmovement) + movement *= maxmovement / length; + glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); + future = glm::translate(mv, -movement) * glm::inverse(mv); + } + } + m_freecameraposition = position; } Update_Lights( simulation::Lights ); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 4322cc2db..3e97683ae 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -469,6 +469,8 @@ class opengl33_renderer : public gfx_renderer { GLuint64 m_gllasttime = 0; double m_precipitationrotation; + // where the camera with no vehicle of its own was at the frame before, for the motion blur of its movement + std::optional m_freecameraposition; glm::mat4 perspective_projection_raw(float fovy, float aspect, float znear, float zfar); glm::mat4 perspective_projection(const viewport_proj_config &c, float n, float f, glm::mat4 &frustum); diff --git a/shaders/postfx_motionblur.frag b/shaders/postfx_motionblur.frag index 146179ac9..d2b23fd03 100644 --- a/shaders/postfx_motionblur.frag +++ b/shaders/postfx_motionblur.frag @@ -32,6 +32,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) From 7c12b83ba470a83a391e61b4e654f2af29daa535 Mon Sep 17 00:00:00 2001 From: pawelw Date: Sun, 22 Nov 2026 12:27:18 +0100 Subject: [PATCH 18/18] fix(ai): an uphill start keeps the power on until the train brake is off (#396) * fix(ai): an uphill start keeps the power on until the train brake is off The uphill start of #265 ended as soon as the power held the train (or the head of the train moved back 0.5 km/h). From then on the brake still on in the wagons made Ready false, the power went off, the train rolled back, was braked again and the start began anew; only the cylinders falling below 0.8 bar let the train get away. - Once the power holds the train, the start goes on while the train brake is released: Ready holds, the power stays on, bounded to 1.5 x the grade force. It ends when the consist is released (the same test as Ready, without the hold) or after 60 s. - A start is given up for rolling back on the mass-weighted speed of the consist, not on the speed of the locomotive, which runs back into the slack of the train held by its brake. - A train slipping back uphill is not released by the rule for a train to go on. * fix(ai): an uphill start begins only with the whole train at a stand * fix(ai): an uphill start applies the train brake further while it doesn't hold the train without the locomotive brake * fix(ai): the speed and the tractive force of an uphill start in the direction of travel also from cab 2 * fix(ai): an uphill start tops up the train brake a full application time a step, at most to full service, and keeps the power between 1.1 and 1.5 times the grade force while the brake releases * fix(ai): an uphill start no longer takes a notch back in the release phase: the notch below doesn't hold the train * refactor(ai): the train brake top-up of an uphill start in uphill_start::brake_top_up(), with unit tests --- CMakeLists.txt | 1 + tests/unit/test_uphill_start.cpp | 103 +++++++++++++++++++++ vehicle/Driver.cpp | 150 ++++++++++++++++++++++++------- vehicle/Driver.h | 12 +++ vehicle/uphillstart.cpp | 36 ++++++++ vehicle/uphillstart.h | 41 +++++++++ 6 files changed, 312 insertions(+), 31 deletions(-) create mode 100644 tests/unit/test_uphill_start.cpp create mode 100644 vehicle/uphillstart.cpp create mode 100644 vehicle/uphillstart.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e563e587f..69dc5fbab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -557,6 +557,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/brakingcurve.cpp" "vehicle/handover.cpp" +"vehicle/uphillstart.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp new file mode 100644 index 000000000..d450af68b --- /dev/null +++ b/tests/unit/test_uphill_start.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/uphillstart.h" + +// starting uphill, the train brake is applied further, a step at a time, until the brake of the unpowered vehicles +// holds the train without the locomotive brake (eu07/maszyna#396). the numbers are those of an ST43 with 37 empty +// wagons on 12.5 per mille: 1040 t, 128.6 kN of grade force, the wagons on G with about 22 s to apply + +using uphill_start::brake_top_up; +using uphill_start::top_up; +using uphill_start::top_up_action; + +namespace { + +double const grade{128600.0}; // [N] +double const application{22.0}; // [s] + +// the train standing with the brake handle at Position, held there long enough for the cylinders to fill, while +// each step adds Gain of brake force (as a multiple of the grade force) to the Start it had. runs the top-up until it +// lets the locomotive brake off, and returns the handle position it stopped at and the number of steps +struct outcome { + double position; + int steps; +}; +outcome run_top_up(double Start, double Gain, double Position = 1.25) { + top_up state; + auto force{Start * grade}; + auto steps{0}; + for (auto guard{0}; guard < 100; ++guard) { + auto const action{brake_top_up(state, force, grade, Position, application, application)}; + if (action == top_up_action::none) { + break; + } + REQUIRE(action == top_up_action::step); + Position += 0.25; + force += Gain * grade; + ++steps; + } + return {Position, steps}; +} + +} // namespace + +TEST_CASE("uphill start: a brake that holds the train isn't applied further") { + top_up state; + CHECK(brake_top_up(state, 1.1 * grade, grade, 1.25, application, application) == top_up_action::none); + CHECK(state.last_force < 0.0); +} + +TEST_CASE("uphill start: each step waits the full application time of the brake") { + top_up state; + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, 0.5 * application, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, application, application) == top_up_action::step); + // the handle has just moved + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, 0.0, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, application - 0.1, application) == top_up_action::wait); +} + +TEST_CASE("uphill start: a light application is topped up until the brake holds the train") { + // before Nowy Zagorz on linia_107_objazdy: 0.64 bar in the wagons, 128 kN against 129 kN + auto const result{run_top_up(0.995, 0.15)}; + CHECK(result.steps == 1); + CHECK(result.position == doctest::Approx(1.5)); +} + +TEST_CASE("uphill start: a brake that doesn't get stronger ends the top-up after one more step") { + // all the wagon brakes cut out: no step adds anything + auto const result{run_top_up(0.0, 0.0)}; + CHECK(result.steps == 1); + CHECK(result.position < uphill_start::top_up_position); +} + +TEST_CASE("uphill start: a brake that gets stronger by too little ends the top-up") { + // a step adds 1% of the grade force, below the 2% that counts + auto const result{run_top_up(0.3, 0.01)}; + CHECK(result.steps == 1); + SUBCASE("and one that gets stronger by enough goes on") { + auto const going{run_top_up(0.3, 0.05)}; + CHECK(going.steps > 1); + } +} + +TEST_CASE("uphill start: the top-up goes no further than full service") { + // every step adds enough to go on, but never enough to hold the train + auto const result{run_top_up(0.0, 0.03)}; + CHECK(result.position == doctest::Approx(uphill_start::top_up_position)); + CHECK(result.steps == 11); + top_up state; + CHECK(brake_top_up(state, 0.0, grade, uphill_start::top_up_position, application, application) == top_up_action::none); +} + +TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { + top_up state; + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.25, application, application) == top_up_action::step); + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.5, application, application) == top_up_action::none); + CHECK(state.done); + // the brake gets stronger later all the same: the start has gone on without the top-up + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::none); + // a new start begins with a new top-up + state = {}; + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 0d80e105f..2deac6621 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3751,7 +3751,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart ) { + if( bUphillStart && ( false == bUphillRelease ) ) { // starting uphill the train brake holds the train until the power does break; } @@ -6549,24 +6549,35 @@ TController::determine_consist_state() { ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - // starting uphill the power is applied against the train brake on purpose, until the power holds the train - auto const heldforstart { bUphillStart }; - if (Ready) { + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + auto const wasready { Ready }; + if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - vehicle->Vel < 1.0 ? + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - // ready all the same only at a standstill with the power going on against the brake on purpose; - // in motion a braking force left anywhere in the train (a hand brake) stops it as before - Ready = heldforstart && ( vehicle->Vel < 1.0 ); + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); } + } + if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken @@ -6583,7 +6594,8 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -6679,6 +6691,10 @@ TController::determine_consist_state() { && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony Ready = true; //żeby uznać za odhamowany } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8717,6 +8733,12 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -8773,15 +8795,19 @@ void TController::control_uphill_start() { && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; false == uphill ) { - bUphillStart = false; + end_uphill_start(); return; } if( false == bUphillStart ) { if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; fUphillStartTime = ElapsedTime; } else { @@ -8790,31 +8816,86 @@ void TController::control_uphill_start() { } if( AccDesired <= EU07_AI_NOACCELERATION ) { // no longer to start: the standing rules take over - bUphillStart = false; + end_uphill_start(); return; } - if( velocity < -0.5 ) { - // rolling back all the same: the rules for a train slipping back take over and apply the brakes - bUphillStart = false; + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - auto tractiveforce { 0.0 }; + fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame - tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - auto const holdingforce { fMass * -fAccGravity }; - if( ( velocity > 1.0 ) - || ( tractiveforce > 1.1 * holdingforce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillStart = false; + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; } void TController::increase_tractive_force() { @@ -8888,10 +8969,17 @@ void TController::control_braking_force() { if( TestFlag( iDrivigFlags, movePress ) ) { return; } auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) ) { + && false == TestFlag(iDrivigFlags, movePress) + && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -8946,7 +9034,7 @@ void TController::control_braking_force() { else { // a stara wersja w miarę dobrze działa na składy wagonowe if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + || slippingbackuphill) && // also brake if uphill and slipping back (fBrakeTime < 0.0 // the size of the brake demand decides whether to skip the reaction time, so the brake-only part // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0794799dc..62b326696 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "utilities/translation.h" #include "application/driverhints.h" +#include "vehicle/uphillstart.h" #include "vehicle/blackbox.h" auto const EU07_AI_ACCELERATION = 0.05; @@ -27,6 +28,7 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back +auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; enum TOrders @@ -337,6 +339,8 @@ private: bool uphill_stop_hold() const; bool uphill_brake_committed( double const Velocity ) const; void control_uphill_start(); + void end_uphill_start(); + bool uphill_brake_top_up(); std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -441,6 +445,14 @@ private: int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does double fUphillStartTime = 0.0; // when the uphill start began + bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released + bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off + uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further + double fUphillReleaseTime = 0.0; // when the release began + double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] + double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp new file mode 100644 index 000000000..dd1895b11 --- /dev/null +++ b/vehicle/uphillstart.cpp @@ -0,0 +1,36 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/uphillstart.h" + +namespace uphill_start { + +top_up_action brake_top_up( + top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, + double const Applicationtime) { + + if (State.done || (Brakeforce >= holding_force * Holdingforce) || (Brakeposition >= top_up_position)) { + return top_up_action::none; + } + // each step is given the full application time of the train brake, for the cylinders along the train to fill + if (Heldtime < Applicationtime) { + return top_up_action::wait; + } + if ((State.last_force >= 0.0) && (Brakeforce - State.last_force < top_up_gain * Holdingforce)) { + // the last step added next to nothing: the brake of this train can't hold it (brakes cut out, a load setting + // too low), and the start goes on without + State.done = true; + return top_up_action::none; + } + State.last_force = Brakeforce; + return top_up_action::step; +} + +} // namespace uphill_start diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h new file mode 100644 index 000000000..108662cbe --- /dev/null +++ b/vehicle/uphillstart.h @@ -0,0 +1,41 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// starting uphill (TController::control_uphill_start()), the AI's driver lets the locomotive brake off only once +// the brake of the rest of the train holds the train on its own: a train stopped on a light application stands on +// the locomotive brake too, and rolls back as soon as it is off. until then the train brake is applied further, a +// step at a time +namespace uphill_start { + +auto const holding_force{1.1}; // a force that holds a train uphill, as a multiple of the grade force +auto const top_up_position{4.0}; // full service: the furthest the train brake is applied to hold the train +// a step that adds less brake force than this, as a multiple of the grade force, is the last one +auto const top_up_gain{0.02}; + +// what has been done to apply the train brake further, in one start +struct top_up { + double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] + bool done{false}; // a step added next to nothing: no more of them in this start +}; + +enum class top_up_action { + none, // the brake holds the train, or can't be made to: the start goes on + wait, // the cylinders are still filling after the last step + step // apply the train brake one step further +}; + +// Brakeforce: the brake force of the unpowered vehicles [N]; Holdingforce: the grade force on the train [N]; +// Brakeposition: the train brake handle, as BrakeCtrlPosition; Heldtime: how long the handle has been where it +// is [s]; Applicationtime: the time the train brake takes to apply, for the cylinders along the train to fill [s] +top_up_action brake_top_up( + top_up &State, double Brakeforce, double Holdingforce, double Brakeposition, double Heldtime, double Applicationtime); + +} // namespace uphill_start