diff --git a/application/application.cpp b/application/application.cpp index fa74c3d7d..66192746d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -991,7 +991,7 @@ void eu07_application::render_ui() return; } - if (m_modestack.empty()) + if (m_modestack.empty() || Global.test.enabled) { return; } @@ -1002,7 +1002,9 @@ void eu07_application::render_ui() void eu07_application::begin_ui_frame() { - if (m_modestack.empty()) + // in the test mode nobody sees the window (hidden, the null renderer): no ui frames, whose start polled the window, + // the mouse and the gamepads every frame through imgui's glfw backend + if (m_modestack.empty() || Global.test.enabled) { return; } diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 99c3ff31e..79186a4cd 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -487,13 +487,18 @@ bool driver_mode::update() Timer::subsystem.switching.update(); Timer::subsystem.loop_audio.start(); - simulation::Region->update_sounds(); + // the test mode has no sound: the sounds of the scenery and of the vehicles aren't gone through. they draw from the local + // engine of Random() only (LocalRandom()), and clear the sound flags of the vehicles, which nothing else reads + if (false == Global.test.enabled) + simulation::Region->update_sounds(); audio::renderer.update(Global.iPause ? 0.0 : deltarealtime); Timer::subsystem.loop_audio.stop(); // NOTE: particle system runs on simulation time, but needs actual camera position to determine how to update each particle source + // nor smoke in the test mode, which draws nothing: the particles draw from the local engine of Random() only Timer::subsystem.loop_particles.start(); - simulation::Particles.update(); + if (false == Global.test.enabled) + simulation::Particles.update(); Timer::subsystem.loop_particles.stop(); Timer::subsystem.loop_renderer_update.start(); diff --git a/application/uilayer.cpp b/application/uilayer.cpp index c24291047..d74513205 100644 --- a/application/uilayer.cpp +++ b/application/uilayer.cpp @@ -440,7 +440,9 @@ bool ui_layer::init(GLFWwindow *Window) void ui_layer::shutdown() { - ImGui::EndFrame(); + // the frame begun last, if there was one: the test mode begins none (eu07_application::begin_ui_frame()) + if (GImGui != nullptr && GImGui->WithinFrameScope) + ImGui::EndFrame(); // the vulkan renderer is gone by now (its backend of imgui went with it) if (auto *renderer{GfxRenderer->GetImguiRenderer()}) diff --git a/physics/components/hosetrains.h b/physics/components/hosetrains.h new file mode 100644 index 000000000..1eafce24e --- /dev/null +++ b/physics/components/hosetrains.h @@ -0,0 +1,56 @@ +/* +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/. +*/ + +// the trains of the air exchange through the hoses (physics::Vehicle::UpdatePipeCouplers()) kept from one step to the next + +#pragma once + +#include +#include +#include + +namespace physics +{ + +class Vehicle; + +// the trains of the hose exchange of the brake and the main reservoir pipe, worked out from the list of vehicles given, +// which of them stepped the pipe and which neighbours their hoses join them to. they change only with a coupling or an +// uncoupling, a vehicle going to sleep or waking up, or one added or taken away, so they're kept while all of that +// stays as it was in the step before, which is checked on every step: kept or worked out again, they're the same +class hose_trains_cache +{ + public: + // what the trains of a pipe were worked out from, for one vehicle of the list + struct input + { + Vehicle const *vehicle{nullptr}; + std::array joined{nullptr, nullptr}; // the neighbour the hose of each end joins it to, or none + bool pending{false}; // the vehicle stepped the pipe + bool operator==(input const &) const = default; + }; + // the trains of a pipe + struct pipe + { + std::vector inputs; + std::vector scratch; // the inputs of the step, read in to be compared with those, kept for the memory + std::vector trains; // the train of each vehicle of the list, none for one which didn't step the pipe + std::vector firsts; // train t is members[firsts[t]] up to members[firsts[t + 1]], not included + std::vector members; // the indices in the list of the vehicles of each train, in the order of the list + bool valid{false}; + }; + pipe brake; + pipe main; +}; + +// physics::Vehicle::UpdatePipeCouplers(), with the trains kept in Cache from one call to the next. for one list of +// vehicles which comes back in every step (all of the scenery's, vehicle_table::update_brake_pipes()) +void UpdatePipeCouplers(std::vector const &Vehicles, double dt, hose_trains_cache &Cache); + +} // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 335616420..cd85345ae 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/hosetrains.h" // Nastawianie hamulców @@ -1425,25 +1426,96 @@ std::vector hose_trains(std::vector const &Vehi return trains; } +// the trains of the pipe laid out: the vehicles of each train, in the order of the list, for going through a train alone. a +// sub-step of a train then costs its own vehicles, not a look at every vehicle of the list (all of the scenery's, in +// update_brake_pipes()), and takes them in the same order as that did +void lay_out_trains(physics::hose_trains_cache::pipe &Layout, std::vector Trains) +{ + Layout.trains = std::move(Trains); + std::size_t count{0}; + for (auto const train : Layout.trains) + { + if (train != std::numeric_limits::max()) + { + count = std::max(count, train + 1); + } + } + Layout.firsts.assign(count + 1, 0); + for (auto const train : Layout.trains) + { + if (train < count) + { + ++Layout.firsts[train + 1]; + } + } + for (std::size_t train = 0; train < count; ++train) + { + Layout.firsts[train + 1] += Layout.firsts[train]; + } + Layout.members.resize(Layout.firsts.back()); + auto next{Layout.firsts}; + for (std::size_t index = 0; index < Layout.trains.size(); ++index) + { + if (Layout.trains[index] < count) + { + Layout.members[next[Layout.trains[index]]++] = index; + } + } +} + +// what hose_trains() goes by, of each vehicle of the list: whether it stepped the pipe and the neighbours its hoses join it to +void hose_inputs(std::vector &Inputs, std::vector const &Vehicles, train_pipe const &trainPipe) +{ + Inputs.resize(Vehicles.size()); + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + auto const &vehicle{*Vehicles[index]}; + auto &input{Inputs[index]}; + input.vehicle = &vehicle; + input.pending = (vehicle.*trainPipe.pipe).CouplersPending(); + std::size_t end{0}; + for (auto const &hose : vehicle.Couplers) + { + input.joined[end++] = (hose.Connected != nullptr && hose.CouplingFlag.HasAll(trainPipe.hose)) ? hose.Connected : nullptr; + } + } +} + // the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order // they stepped: each train in as many sub-steps of dt as its vehicle needing the most of them takes, each going through // its vehicles one after another, as the step of the vehicles does. the air of a train stays in it, so a train comes out // the same whichever other vehicles are exchanged in the same call: all of them, or the ones of a group of -// vehicle_table::update_steps_parallel() -void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt) +// vehicle_table::update_steps_parallel(). with a Cache, the trains of the call before are taken again when what they +// were worked out from is the same +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt, physics::hose_trains_cache::pipe *Cache = nullptr) { - auto const trains{hose_trains(Vehicles, trainPipe)}; - std::vector substeps; + physics::hose_trains_cache::pipe fresh; + auto *layout{&fresh}; + if (Cache != nullptr) + { + hose_inputs(Cache->scratch, Vehicles, trainPipe); + if (false == Cache->valid || Cache->scratch != Cache->inputs) + { + lay_out_trains(*Cache, hose_trains(Vehicles, trainPipe)); + std::swap(Cache->inputs, Cache->scratch); + Cache->valid = true; + } + layout = Cache; + } + else + { + lay_out_trains(fresh, hose_trains(Vehicles, trainPipe)); + } + auto const &trains{layout->trains}; + auto const &firsts{layout->firsts}; + auto const &members{layout->members}; + std::vector substeps(firsts.size() - 1, 1); for (std::size_t index = 0; index < Vehicles.size(); ++index) { if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending()) { continue; } - if (substeps.size() <= trains[index]) - { - substeps.resize(trains[index] + 1, 1); - } substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); } for (std::size_t train = 0; train < substeps.size(); ++train) @@ -1451,13 +1523,9 @@ void exchange_through_hoses(std::vector const &Vehicles, tra auto const substep{dt / substeps[train]}; for (auto i = 0; i < substeps[train]; ++i) { - for (std::size_t index = 0; index < Vehicles.size(); ++index) + for (auto member = firsts[train]; member < firsts[train + 1]; ++member) { - if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending() || trains[index] != train) - { - continue; - } - auto *vehicle{Vehicles[index]}; + auto *vehicle{Vehicles[members[member]]}; auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; pipe.Act(); // what the neighbours have sent in the meantime (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); @@ -1507,6 +1575,12 @@ void physics::Vehicle::UpdatePipeCouplers(std::vector const exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); } +void physics::UpdatePipeCouplers(std::vector const &Vehicles, double const dt, hose_trains_cache &Cache) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt, &Cache.brake); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt, &Cache.main); +} + bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const Dt) { if (Demand <= 0.0) diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 2f86603cb..4e68f932f 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -193,11 +193,17 @@ void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, do // the log of the braking of the consist opened, once it brakes while moving void physics::ConsistBrakeBlending::OpenLog(Step const &state, Vehicle const &Lead) { - if (state.Fzad > 1 && !log.is_open() && Lead.Vel > 1) + if (state.Fzad > 1 && !log.is_open() && false == logUnavailable && Lead.Vel > 1) { log.open( "MEDLOGS/" + Lead.Name + "_" + std::to_string( ++logCount ) + ".csv", std::ios::in | std::ios::out | std::ios::trunc ); + if( false == log.is_open() ) { + // no MEDLOGS folder (the usual case, the game doesn't come with one): not tried again for this vehicle. + // an attempt costs a file system call, and it used to be made on every step of the braking + logUnavailable = true; + return; + } log << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; for(int k=1;k<=state.np;k++) { diff --git a/physics/consistbraking.h b/physics/consistbraking.h index bef61ff4c..78794864a 100644 --- a/physics/consistbraking.h +++ b/physics/consistbraking.h @@ -63,6 +63,7 @@ class ConsistBrakeBlending double logTime{0.0}; double logInactiveTime{0.0}; int logCount{0}; + bool logUnavailable{false}; // the log couldn't be opened (no MEDLOGS folder): it isn't tried again }; } // namespace physics diff --git a/physics/oerlikonest.cpp b/physics/oerlikonest.cpp index 70c3d4f8e..524624a21 100644 --- a/physics/oerlikonest.cpp +++ b/physics/oerlikonest.cpp @@ -66,12 +66,12 @@ void TPrzekladnik::Update(double dt) double BCP{ Next->P() }; double BVP{ BrakeRes->P() }; - - if ( BCP > P() ) - dV = -PFVd(BCP, 0, d2A(10), P()) * dt; + // the pressure of the relay itself, read once: nothing changes it before the flows are applied (Act()) + if ( double const ownP{ P() }; BCP > ownP ) + dV = -PFVd(BCP, 0, d2A(10), ownP) * dt; else { - if( BCP < P() ) - dV = PFVa( BVP, BCP, d2A( 10 ), P() ) * dt; + if( BCP < ownP ) + dV = PFVa( BVP, BCP, d2A( 10 ), ownP ) * dt; else dV = 0; } @@ -120,10 +120,10 @@ void TRapid::Update(double dt) ActMult = 1.0; } - if (BCP * RapidMult > P() * ActMult) - dV = -PFVd(BCP, 0, DL, P() * ActMult / RapidMult) * dt; - else if (BCP * RapidMult < P() * ActMult) - dV = PFVa(BVP, BCP, DN, P() * ActMult / RapidMult) * dt; + if (double const ownP{ P() }; BCP * RapidMult > ownP * ActMult) + dV = -PFVd(BCP, 0, DL, ownP * ActMult / RapidMult) * dt; + else if (BCP * RapidMult < ownP * ActMult) + dV = PFVa(BVP, BCP, DN, ownP * ActMult / RapidMult) * dt; else dV = 0.0; @@ -145,10 +145,10 @@ void TPrzekCiagly::Update(double dt) double const BCP{ Next->P() }; double dV; - if ( BCP > P() * Mult) - dV = -PFVd(BCP, 0, d2A(8.0), P() * Mult) * dt; - else if (BCP < P() * Mult) - dV = PFVa(BVP, BCP, d2A(8.0), P() * Mult) * dt; + if ( double const ownP{ P() }; BCP > ownP * Mult) + dV = -PFVd(BCP, 0, d2A(8.0), ownP * Mult) * dt; + else if (BCP < ownP * Mult) + dV = PFVa(BVP, BCP, d2A(8.0), ownP * Mult) * dt; else dV = 0.0; @@ -193,10 +193,11 @@ void TPrzekED::SetP(double P) void TPrzekED::Update(double dt) { - if (Next->P() > MaxP) + // the pressure after the relay, read once: the flows change it only once applied (Act()) + if (double const nextP{ Next->P() }; nextP > MaxP) { BrakeRes->Flow(dVol); - Next->Flow(PFVd(Next->P(), 0, d2A(10.0) * dt, MaxP)); + Next->Flow(PFVd(nextP, 0, d2A(10.0) * dt, MaxP)); } else Next->Flow(dVol); @@ -232,7 +233,8 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr dV = 0.0; // BrakeCyl.Flow(-dV); Przekladniki[1]->Flow(-dV); - if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP ) + // the flows above change the pressure of the cylinder only once applied (Act()), it's still BCP + if ( (BrakeStatus & b_on) == b_on && BCP * HBG300 < MaxBP ) dV = PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) ) * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) ); @@ -262,8 +264,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr if( PrzekPZZ != nullptr ) PrzekPZZ->SetLBP(LBP); + // the nozzle of the control reservoir's filler, the same for both flows below: the flows change the pressures it + // goes by only once applied (Act()) + double const temp = CVs(BCP); // przeplyw testowy miedzypojemnosci - dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, CVs(BCP)); + dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, temp); if (MPP - 0.05 > BVP) dV += PF(MPP - 0.05, BVP, Nozzles[dPT] * nastG + (1.0 - nastG) * Nozzles[dPO]); if (MPP > VVP) @@ -271,7 +276,6 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr Miedzypoj->Flow(dV * dt * 0.15); // przeplyw ZS <-> PG - double const temp = CVs(BCP); dV = PF(CVP, MPP, temp) * dt; CntrlRes->Flow(dV); ValveRes->Flow(-0.02 * dV); diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 796943c7d..0cd0c1063 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -100,7 +100,12 @@ void consist::update_brake_pipes(double Dt) const { for (auto const &vehicle : m_vehicles) { vehicles.push_back(&vehicle->physics()); } - physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); + if (m_keephosetrains) { + physics::UpdatePipeCouplers(vehicles, Dt, m_hosetrains); + } + else { + physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); + } } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 73daa6294..2131bba2d 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -5,6 +5,7 @@ #include #include "vehicle.h" +#include "physics/components/hosetrains.h" class TDynamicObject; @@ -43,6 +44,10 @@ public: // distance between the couplers of the vehicle and the one behind it [m], negative when the buffers press double gap(std::size_t Index) const; + // whether the trains of the hose exchange are kept from one step to the next, as the game keeps them (the default), or + // worked out again in every step + void keep_hose_trains(bool Keep) { m_keephosetrains = Keep; } + private: void update_neighbours(); void update_brake_pipes(double Dt) const; @@ -53,6 +58,9 @@ private: // the game's object can't be made without the rest of the game, so it's a stand-in: storage of its size // with that one member set, never constructed, which only the physics ever looks into std::vector> m_objects; + // the trains of the hoses kept from one step to the next, as vehicle_table::update_brake_pipes() keeps them + mutable physics::hose_trains_cache m_hosetrains; + bool m_keephosetrains{true}; }; } // namespace test diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index e1281992b..66026591e 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -3,9 +3,15 @@ #include "physics/vehicle.h" #include "physics/brakes.h" +#include "utilities/Globals.h" +#include "utilities/utilities.h" #include "consist.h" #include "vehicle.h" +#include +#include +#include + // the air exchange through the brake hoses between the vehicles of a train (physics::Vehicle::UpdatePipeCouplers()). // taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens // out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to @@ -116,3 +122,79 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, CAPTURE(usual); CHECK(usual == doctest::Approx(converged).epsilon(0.05)); } + +namespace { + +// Global.physics_sleepheld, off by default, on for the test it's made in +struct sleepheld_on { + bool const was{Global.physics_sleepheld}; + sleepheld_on() { Global.physics_sleepheld = true; } + ~sleepheld_on() { Global.physics_sleepheld = was; } + sleepheld_on(sleepheld_on const &) = delete; + sleepheld_on &operator=(sleepheld_on const &) = delete; +}; + +} // namespace + +TEST_CASE("brake pipe: the trains of the hose exchange kept from one step to the next come out as worked out in every step") { + // a locomotive with five freight wagons on a gradient, charged and braked; the last two wagons uncoupled, then the train + // released. with Global.physics_sleepheld the wagons held by their brakes fall asleep and wake on the way (a vehicle + // asleep doesn't step its pipe, so it ends the trains of the hoses), and the uncoupling splits a train in two + sleepheld_on const sleepheld; + test::track slope; + slope.gradient = 0.01; + auto const build = [](test::consist &Train) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < 5; ++i) { + Train.add(definition::fiz("3wl_v2/3wl")); + } + Train[0].hold_brake_pipe(5.0); + }; + // each train with an engine of its own for the draws of its physics, seeded alike + std::mt19937 keptdraws{12345}; // NOSONAR: randomness of the simulation, not of anything security-relevant + std::mt19937 freshdraws{12345}; // NOSONAR: randomness of the simulation, not of anything security-relevant + test::consist kept; + test::consist fresh; + fresh.keep_hose_trains(false); + auto const both = [&keptdraws, &freshdraws, &kept, &fresh](auto const &Action) { + set_thread_random_engine(&keptdraws); + Action(kept); + set_thread_random_engine(&freshdraws); + Action(fresh); + set_thread_random_engine(nullptr); + }; + both(build); + // the vehicles which came out of a step differing between the two trains, and the times a vehicle fell asleep or woke + int differing{0}; + int sleeps{0}; + int wakes{0}; + std::vector awake(kept.size(), true); + auto const run = [&both, &slope, &kept, &fresh, &differing, &sleeps, &wakes, &awake](double const Seconds) { + for (auto step = std::lround(Seconds / 0.01); step > 0; --step) { + both([&slope](test::consist &Train) { Train.step(slope); }); + for (std::size_t i = 0; i < kept.size(); ++i) { + auto const &a{kept[i].physics()}; + auto const &b{fresh[i].physics()}; + if (a.brakePipe.Pressure() != b.brakePipe.Pressure() || a.brakePipe.reservoir->P() != b.brakePipe.reservoir->P() || + a.mainPipe.Pressure() != b.mainPipe.Pressure() || a.mainPipe.reservoir->P() != b.mainPipe.reservoir->P() || + a.brakes.cylinderPressure != b.brakes.cylinderPressure) { + ++differing; + } + if (awake[i] != a.PhysicActivation()) { + ++(a.PhysicActivation() ? wakes : sleeps); + awake[i] = a.PhysicActivation(); + } + } + } + }; + run(60.0); + both([](test::consist &Train) { Train[0].hold_brake_pipe(3.5); }); + run(30.0); + both([](test::consist &Train) { REQUIRE(Train[3]->Dettach(VehicleEnd::rear)); }); + run(60.0); + both([](test::consist &Train) { Train[0].hold_brake_pipe(5.0); }); + run(60.0); + CHECK(differing == 0); + CHECK(sleeps > 0); + CHECK(wakes > 0); +} diff --git a/tests/unit/test_random_engine.cpp b/tests/unit/test_random_engine.cpp new file mode 100644 index 000000000..b36005d08 --- /dev/null +++ b/tests/unit/test_random_engine.cpp @@ -0,0 +1,71 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "utilities/utilities.h" +#include "utilities/lazyrandom.h" + +#include +#include + +namespace +{ +// what Random() draws in the calling thread with the engine set before, n times +std::vector draws(int const Count) +{ + std::vector result; + for (int i = 0; i < Count; ++i) + result.push_back(Random(0.0, 1.0)); + return result; +} +} // namespace + +TEST_CASE("random engine: the lazily seeded engine draws as one seeded up front from the same numbers") +{ + std::pair const seeds[]{{0u, 0u}, {12345u, 7u}, {0xFFFFFFFFu, 4096u}}; + for (auto const &seed : seeds) + { + CAPTURE(seed.first); + CAPTURE(seed.second); + std::seed_seq eagerseed{seed.first, seed.second}; + std::mt19937 eager{eagerseed}; // NOSONAR: randomness of the simulation, not of anything security-relevant + set_thread_random_engine(&eager); + auto const expected{draws(100)}; + set_thread_random_engine(nullptr); + + lazy_random_engine lazy; + lazy.seed[0] = seed.first; + lazy.seed[1] = seed.second; + set_thread_lazy_random_engine(&lazy); + auto const actual{draws(100)}; + set_thread_lazy_random_engine(nullptr); + + CHECK(actual == expected); + } +} + +TEST_CASE("random engine: the lazy engine is seeded at the first draw only, and stands ahead of the thread's engine") +{ + std::mt19937 threadengine{1u}; // NOSONAR: randomness of the simulation, not of anything security-relevant + auto const untouched{threadengine}; // NOSONAR: randomness of the simulation, not of anything security-relevant + set_thread_random_engine(&threadengine); + + lazy_random_engine lazy; + lazy.seed[0] = 3u; + lazy.seed[1] = 5u; + set_thread_lazy_random_engine(&lazy); + CHECK(thread_lazy_random_engine() == &lazy); + // a group that draws nothing never seeds it + CHECK_FALSE(lazy.engine.has_value()); + static_cast(Random(0.0, 1.0)); + CHECK(lazy.engine.has_value()); + // the draw came from the lazy engine, the one of the thread is left as it was + CHECK(threadengine == untouched); + + set_thread_lazy_random_engine(nullptr); + CHECK(thread_lazy_random_engine() == nullptr); + // without the lazy engine the draws come from the thread's engine again + static_cast(Random(0.0, 1.0)); + CHECK_FALSE(threadengine == untouched); + set_thread_random_engine(nullptr); +} diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 47852be26..a918abb9f 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -141,7 +141,6 @@ void LogService() crash_signals::set_log_path(filename); } output << msg << "\n"; - output.flush(); } // log to scrollback imgui @@ -159,6 +158,11 @@ void LogService() } } + // the lines of the pass written out together, rather than one by one: at most the 50 ms of a pass after they're logged + // (and a crash report takes the last lines from crashdump_note_log() anyway) + if (output.is_open()) + output.flush(); + // --- Obsługa ErrorStack --- while (!ErrorStack.empty()) { diff --git a/utilities/lazyrandom.h b/utilities/lazyrandom.h new file mode 100644 index 000000000..c55ebedd5 --- /dev/null +++ b/utilities/lazyrandom.h @@ -0,0 +1,31 @@ +/* +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/. +*/ + +// an engine of Random() seeded from two numbers (std::seed_seq) only when the first draw needs it: seeding a std::mt19937 +// fills its whole state (624 numbers), which took longer than the steps of most of the groups of vehicles it was made for +// in every frame (vehicle_table::update_steps_parallel()), and most of them (parked wagons, cars) draw nothing + +#pragma once + +#include +#include +#include +#include + +struct lazy_random_engine +{ + std::array seed{}; + std::optional engine; // NOSONAR: randomness of the simulation, not of anything security-relevant +}; + +// the engine Random() draws from in the calling thread ahead of the one of set_thread_random_engine(), or none for that one +// again. its draws are the ones of a std::mt19937 built from std::seed_seq{ seed[0], seed[1] } up front +void set_thread_lazy_random_engine(lazy_random_engine *Engine); +// the engine set for the calling thread by set_thread_lazy_random_engine(), or none +lazy_random_engine *thread_lazy_random_engine(); diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 1adb80a5b..d38e4baa0 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -28,6 +28,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#endif #include "utilities/utilities.h" +#include "utilities/lazyrandom.h" #include "utilities/Globals.h" #include "utilities/parser.h" #include "utilities/U8.h" @@ -181,13 +182,33 @@ bool ClearFlag(int &Flag, int const Value) namespace { thread_local std::mt19937 *t_random_engine{nullptr}; // NOSONAR: randomness of the simulation, not of anything security-relevant +thread_local lazy_random_engine *t_lazy_random_engine{nullptr}; // NOSONAR: randomness of the simulation, not of anything security-relevant std::mt19937 &random_engine() // NOSONAR: randomness of the simulation, not of anything security-relevant { + if (t_lazy_random_engine != nullptr) + { + if (false == t_lazy_random_engine->engine.has_value()) + { + std::seed_seq seed{t_lazy_random_engine->seed[0], t_lazy_random_engine->seed[1]}; + t_lazy_random_engine->engine.emplace(seed); + } + return *t_lazy_random_engine->engine; + } return t_random_engine != nullptr ? *t_random_engine : Global.random_engine; } } // namespace +void set_thread_lazy_random_engine(lazy_random_engine *Engine) +{ + t_lazy_random_engine = Engine; +} + +lazy_random_engine *thread_lazy_random_engine() +{ + return t_lazy_random_engine; +} + void set_thread_random_engine(std::mt19937 *Engine) // NOSONAR: randomness of the simulation, not of anything security-relevant { t_random_engine = Engine; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 97aa9b658..92d043b44 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/vehicletypes.h" #include "physics/derailment.h" #include "physics/consistbraking.h" +#include "physics/components/hosetrains.h" #include "vehicle/derailmotion.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" @@ -1160,6 +1161,8 @@ private: double m_overlapdue { 1.0 }; bool m_overlaplogged { false }; std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + // the trains of the hoses of m_brakepipes, which change seldom: kept from one step to the next while they stay + physics::hose_trains_cache m_hosetrains; std::vector> m_offtrackterrains; // of off_track_terrain() }; diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 93af2a6f5..d7aff2512 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -23,6 +23,10 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakereleaser.h" +#include +#include +#include +#include #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" #include "vehicle/fieldshunting.h" @@ -61,38 +65,76 @@ std::string_view TController::physicslog_header() { "\r\n"; } +namespace { + +// a number of the physics log as `<< std::fixed << std::setprecision( 4 )` writes it into a stream of the C locale, which +// is printf's "%.4f": std::to_chars gives the same digits, rounded to the nearest as printf rounds them, without the +// stream and the locale. infinities and NaNs (printf's inf, nan(ind)) and numbers too long for the buffer go through +// snprintf with the same format +void append_fixed( std::string &Line, double const Value ) { + std::array buffer; + if( std::isfinite( Value ) ) { + auto const result { std::to_chars( buffer.data(), buffer.data() + buffer.size(), Value, std::chars_format::fixed, 4 ) }; + if( result.ec == std::errc{} ) { + Line.append( buffer.data(), result.ptr ); + return; + } + } + auto const length { std::snprintf( nullptr, 0, "%.4f", Value ) }; // NOSONAR: printf's own text of inf and NaN, which std::format writes otherwise + std::string text( static_cast( length ) + 1, '\0' ); + std::snprintf( text.data(), text.size(), "%.4f", Value ); // NOSONAR: printf's own text of inf and NaN, which std::format writes otherwise + text.resize( static_cast( length ) ); + Line += text; +} + +void append_int( std::string &Line, int const Value ) { + std::array buffer; + auto const result { std::to_chars( buffer.data(), buffer.data() + buffer.size(), Value ) }; + Line.append( buffer.data(), result.ptr ); +} + +} // namespace + std::string TController::physicslog_line() const { - std::ostringstream line; - line << std::fixed << std::setprecision( 4 ) - << ElapsedTime << " " - << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) << " " - << mvControlling->AccS() << " " - << occupied->Couplers[1].Dist << " " - << occupied->Couplers[1].CForce << " " - << occupied->Ft() << " " - << occupied->Ff << " " - << occupied->Fb() << " " - << occupied->brakes.cylinderPressure << " " - << occupied->brakePipe.Pressure() << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos()) << " " - << int(mvControlling->ScndCtrlPos()) << " " - << occupied->brakes.HandlePositionSmooth() << " " - << occupied->brakes.IndependentPosition() << " " - << int(mvControlling->DirActive) << " " - << ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ) << " " - << occupied->CommandIn.Value1 << " " - << occupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels()) << " " - << mvControlling->diesel.heat.Ts << " " - << mvControlling->diesel.heat.To << " " - << mvControlling->diesel.heat.temperatura1 << " " - << mvControlling->diesel.heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << occupied->V() * 3.6 - << "\r\n"; - return line.str(); + // the columns of physicslog_header(), separated by spaces; the numbers as a stream with std::fixed and std::setprecision( 4 ) wrote them + std::string line; + line.reserve( 320 ); + auto const number = [ &line ]( double const Value ) { + append_fixed( line, Value ); + line += ' '; }; + auto const integer = [ &line ]( int const Value ) { + append_int( line, Value ); + line += ' '; }; + number( ElapsedTime ); + number( fabs( 11.31 * occupied->WheelDiameter() * occupied->nrot() ) ); + number( mvControlling->AccS() ); + number( occupied->Couplers[ 1 ].Dist ); + number( occupied->Couplers[ 1 ].CForce ); + number( occupied->Ft() ); + number( occupied->Ff ); + number( occupied->Fb() ); + number( occupied->brakes.cylinderPressure ); + number( occupied->brakePipe.Pressure() ); + number( mvControlling->Im ); + integer( int( mvControlling->MainCtrlPos() ) ); + integer( int( mvControlling->ScndCtrlPos() ) ); + number( occupied->brakes.HandlePositionSmooth() ); + number( occupied->brakes.IndependentPosition() ); + integer( int( mvControlling->DirActive ) ); + line += ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ); + line += ' '; + number( occupied->CommandIn.Value1 ); + number( occupied->CommandIn.Value2 ); + integer( int( mvControlling->SecuritySystem.is_blinking() ) ); + integer( int( mvControlling->SlippingWheels() ) ); + number( mvControlling->diesel.heat.Ts ); + number( mvControlling->diesel.heat.To ); + number( mvControlling->diesel.heat.temperatura1 ); + number( mvControlling->diesel.heat.temperatura2 ); + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + append_fixed( line, occupied->V() * 3.6 ); + line += "\r\n"; + return line; } void TController::begin_physicslog() diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 398fe1241..a2328b958 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -159,8 +159,11 @@ bool TDynamicObject::Update(double dt, double dt1) updateWheelAngles( dt1 ); updateCurrentCollectors( dt1 ); - updateWipers( dt1 ); - updateMirrors( dt1 ); + // the wipers and the mirrors only move in the cab and make their sounds: the test mode shows and plays neither + if( false == Global.test.enabled ) { + updateWipers( dt1 ); + updateMirrors( dt1 ); + } // compartment lights // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index c99e603f3..7942cef23 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -41,6 +41,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Timer.h" #include "utilities/workerpool.h" +#include "utilities/lazyrandom.h" +#include "physics/components/hosetrains.h" #include "utilities/Logs.h" #include "utilities/glmHelpers.h" #include "Console.h" @@ -197,12 +199,16 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { && Global.network_servers.empty() && ( false == Global.network_client.has_value() ) }; auto const camera { Global.pCamera.Pos }; - for( std::size_t index = 0; index < m_items.size(); ++index ) { + // the counts and the times by kind are for the debug panel only, which the test mode doesn't show: there the loop is + // gone through only for the coarse steps, and the vehicles aren't timed + auto const counted { false == Global.test.enabled }; + for( std::size_t index = 0; ( counted || roadlod ) && index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; auto const road { ( vehicle->physics->CategoryFlag & 2 ) != 0 }; auto const distant { glm::length2( vehicle->GetPosition() - camera ) > Timer::subsystem.VEHICLE_NEAR * Timer::subsystem.VEHICLE_NEAR }; kinds[ index ] = static_cast( ( road ? 2 : 0 ) + ( distant ? 1 : 0 ) ); coarse[ index ] = static_cast( roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); + if( false == counted ) { continue; } if( false == vehicle->bEnabled ) { continue; } ++counts.kind[ kinds[ index ] ]; auto const *physics { vehicle->physics }; @@ -225,6 +231,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { + if( false == counted ) { return; } auto const now { std::chrono::steady_clock::now() }; if( Index < kinds.size() ) { Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); @@ -232,6 +239,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { Mark = now; }; for( auto const *vehicle : m_items ) { + if( false == counted ) { break; } if( false == vehicle->bEnabled ) { continue; } ++counts.enabled; if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } @@ -286,7 +294,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { if( threads > 1 ) { counts.singlethread = "a vehicle coupled with one it doesn't see"; } - auto mark { std::chrono::steady_clock::now() }; + auto mark { counted ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point {} }; if( Iterationcount > 1 ) { // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { @@ -324,7 +332,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { Timer::subsystem.vehicles_update.start(); { std::size_t index { 0 }; - auto mark { std::chrono::steady_clock::now() }; + auto mark { counted ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point {} }; for( auto *vehicle : m_items ) { auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; // Ra 2015-01: tylko tu przelicza sieć trakcyjną @@ -580,7 +588,7 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.push_back( vehicle->physics ); } } - physics::Vehicle::UpdatePipeCouplers( m_brakepipes, Deltatime ); + physics::UpdatePipeCouplers( m_brakepipes, Deltatime, m_hosetrains ); } // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) @@ -684,10 +692,12 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio auto const seed { static_cast( Global.random_engine() ) }; auto const steps = [ & ]( std::uint32_t const Group ) { auto const &members { m_groups[ Group ] }; - std::seed_seq groupseed { seed, members.front() }; - std::mt19937 engine { groupseed }; // NOSONAR: randomness of the simulation, not of anything security-relevant - auto *const threadengine { thread_random_engine() }; - set_thread_random_engine( &engine ); + // seeded at the first draw, if the group makes one: the seeding took longer than the steps of most groups + lazy_random_engine engine; + engine.seed[ 0 ] = seed; + engine.seed[ 1 ] = members.front(); + auto *const threadengine { thread_lazy_random_engine() }; + set_thread_lazy_random_engine( &engine ); // the hoses join only vehicles coupled with each other, which are in one group: the air they carry is exchanged // within the group after each step, as update_brake_pipes() does for all the vehicles in one thread std::vector pipes; @@ -714,7 +724,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio // the vehicles going by one step take it with the time of all of them m_items[ index ]->UpdateForce( coarse( index ) ? totaltime : Deltatime ); } - set_thread_random_engine( threadengine ); }; + set_thread_lazy_random_engine( threadengine ); }; Workers().run( m_threadgroups.size(), Threads, diff --git a/world/Segment.cpp b/world/Segment.cpp index 6e0326c33..f9ec7f85e 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -187,11 +187,11 @@ bool TSegment::InitChain(std::vector> Pieces) fDirection = -std::atan2(Point2.x - Point1.x, Point2.z - Point1.z); fStoop = std::atan2(Point2.y - Point1.y, fLength); fStep = fLength / iSegCount; - fTsBuffer.resize( iSegCount + 1 ); + fTs.resize( iSegCount + 1 ); for( int i = 0; i <= iSegCount; ++i ) { - fTsBuffer[ i ] = static_cast( i ) / iSegCount; + fTs[ i ].t = static_cast( i ) / iSegCount; + fTs[ i ].slope = fStep / fLength; } - fTsSlope.assign( iSegCount + 1, fStep / fLength ); return true; } @@ -204,28 +204,27 @@ std::size_t TSegment::piece_at(double const s) const void TSegment::InitTFromSInterpolateData() { // pre-compute the curve parameter t at equal distance intervals - fTsBuffer.resize( iSegCount + 1 ); - fTsBuffer[ 0 ] = 0.0; + fTs.resize( iSegCount + 1 ); + fTs[ 0 ].t = 0.0; for( int i = 1; i < iSegCount; ++i ) { - fTsBuffer[ i ] = GetTFromS( i * fStep ); + fTs[ i ].t = GetTFromS( i * fStep ); } - fTsBuffer[ iSegCount ] = 1.0; + fTs[ iSegCount ].t = 1.0; // pre-compute Hermite slopes dt/du = fStep / |B'(t)| for FastGetTFromS // (dt/ds = 1/|B'(t)|, scaled by fStep to the interval coordinate u) - fTsSlope.resize( iSegCount + 1 ); for( int i = 0; i <= iSegCount; ++i ) { // compute ds/dt derivative = |B'(t)| - double const speed = glm::length( GetFirstDerivative( fTsBuffer[ i ] ) ); + double const speed = glm::length( GetFirstDerivative( fTs[ i ].t ) ); // compute dt/du derivative = fStep / (ds/dt) - fTsSlope[ i ] = speed > 0.0 ? fStep / speed : 0.0; + fTs[ i ].slope = speed > 0.0 ? fStep / speed : 0.0; } // clamp slopes to keep t(s) monotone (PCHIP / Fritsch-Carlson condition) for( int i = 0; i <= iSegCount; ++i ) { double limit = std::numeric_limits::max(); - if( i > 0 ) { limit = std::min( limit, 3.0 * ( fTsBuffer[ i ] - fTsBuffer[ i - 1 ] ) ); } - if( i < iSegCount ) { limit = std::min( limit, 3.0 * ( fTsBuffer[ i + 1 ] - fTsBuffer[ i ] ) ); } - fTsSlope[ i ] = std::min( fTsSlope[ i ], limit ); + if( i > 0 ) { limit = std::min( limit, 3.0 * ( fTs[ i ].t - fTs[ i - 1 ].t ) ); } + if( i < iSegCount ) { limit = std::min( limit, 3.0 * ( fTs[ i + 1 ].t - fTs[ i ].t ) ); } + fTs[ i ].slope = std::min( fTs[ i ].slope, limit ); } } @@ -296,7 +295,7 @@ double TSegment::GetTFromS(double const s) const double TSegment::FastGetTFromS(double const s) const { // Faster version of GetTFromS: cubic Hermite interpolation using - // the precomputed values in fTsBuffer and slopes in fTsSlope. It + // the precomputed values and slopes in fTs. It // avoids the expensive RombergIntegral+Newton per call. Hermite // interpolation is C1-continuous, so no sudden speed changes when // moving from one interval to the next. @@ -310,10 +309,12 @@ double TSegment::FastGetTFromS(double const s) const double const u2 = u * u; double const u3 = u2 * u; double const h01 = -2.0 * u3 + 3.0 * u2; - double const t = ( ( 1.0 - h01 ) * fTsBuffer[ i ] + - ( u3 - 2.0 * u2 + u ) * fTsSlope [ i ] + - h01 * fTsBuffer[ i + 1 ] + - ( u3 - u2 ) * fTsSlope [ i + 1 ] ); + auto const &from { fTs[ i ] }; + auto const &to { fTs[ i + 1 ] }; + double const t = ( ( 1.0 - h01 ) * from.t + + ( u3 - 2.0 * u2 + u ) * from.slope + + h01 * to.t + + ( u3 - u2 ) * to.slope ); return t; } @@ -375,11 +376,11 @@ TSegment::find_nearest_point( glm::dvec3 const &Point ) const { auto const segmentpoint = std::clamp( nearest_segment_point( - glm::dvec3{ FastGetPoint( fTsBuffer[ segmentidx ] ) }, - glm::dvec3{ FastGetPoint( fTsBuffer[ segmentidx + 1 ] ) }, + glm::dvec3{ FastGetPoint( fTs[ segmentidx ].t ) }, + glm::dvec3{ FastGetPoint( fTs[ segmentidx + 1 ].t ) }, Point ) // point in range 0-1 on current segment - * ( fTsBuffer[ segmentidx + 1 ] - fTsBuffer[ segmentidx ] ) // segment length - + fTsBuffer[ segmentidx ], // segment offset + * ( fTs[ segmentidx + 1 ].t - fTs[ segmentidx ].t ) // segment length + + fTs[ segmentidx ].t, // segment offset 0.0, 1.0 ); // we clamp the range in case there's some floating point math inaccuracies auto const segmentdistance = glm::length2( Point - glm::dvec3{ FastGetPoint( segmentpoint ) } ); @@ -545,7 +546,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { - if( fTsBuffer.empty() ) { + if( fTs.empty() ) { // never made into a path: tt_Cross and the like Point = Point1; Across = glm::dvec3 { 0.0 }; @@ -573,7 +574,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, // standardowo tworzy triangle_strip dla prostego albo ich zestaw dla łuku // po modyfikacji - dla ujemnego (iNumShapePoints) w dodatkowych polach tabeli podany jest przekrój końcowy - if( fTsBuffer.empty() ) + if( fTs.empty() ) return false; // prowizoryczne zabezpieczenie przed wysypem - ustalić faktyczną przyczynę glm::vec3 pos1; @@ -602,7 +603,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, tv1 = 1.0; // Ra: to by można było wyliczać dla odcinka, wyglądało by lepiej s = static_cast(fStep * iSkip); // iSkip - ile odcinków z początku pominąć int i = iSkip; // domyślnie 0 - t = static_cast(fTsBuffer[ i ]); // tabela wattości t dla segmentów + t = static_cast(fTs[ i ].t); // tabela wattości t dla segmentów // BUG: length of spline can be 0, we should skip geometry generation for such cases fOffset = static_cast(0.1 / fLength); // pierwsze 10cm pos1 = glm::dvec3{ FastGetPoint( t ) - Origin }; // wektor początku segmentu @@ -653,7 +654,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, tv1 = clamp_circular( tv1, 1.0f ); tv2 = tv1 - step / texturelength; // mapowanie na końcu segmentu - t = static_cast(fTsBuffer[ i ]); // szybsze od GetTFromS(s); + t = static_cast(fTs[ i ].t); // szybsze od GetTFromS(s); pos2 = glm::dvec3{ FastGetPoint( t ) - Origin }; dir = glm::dvec3{ FastGetDirection( t, fOffset ) }; // nowy wektor kierunku parallel2 = glm::vec3{ -dir.z, 0.f, dir.x }; // wektor poprzeczny @@ -769,7 +770,7 @@ void TSegment::roll_vertex( gfx::basic_vertex &Vertex, glm::vec3 const &Position bool TSegment::RenderLoftSteps( gfx::vertex_array &Output, glm::dvec3 const &Origin, gfx::vertex_array const &ShapePoints, double fTextureLength, int const Steps ) const { - if( fTsBuffer.empty() || Steps < 1 || fLength <= 0.0 ) + if( fTs.empty() || Steps < 1 || fLength <= 0.0 ) return false; auto const shapepoints { ShapePoints.size() / 2 }; @@ -1431,7 +1432,7 @@ gfx::vertex_array const &low_section::profile_at( gfx::vertex_array const &Shape bool TSegment::RenderLoftSpan( gfx::vertex_array &Output, glm::dvec3 const &Origin, gfx::vertex_array const &ShapePoints, loft_span const &Span ) const { - if( fTsBuffer.empty() || Span.to - Span.from < 0.001 || ShapePoints.empty() ) + if( fTs.empty() || Span.to - Span.from < 0.001 || ShapePoints.empty() ) return false; auto const stations { loft_stations( Span, ShapePoints, std::max( fStep, 0.2 ), m_dense ) }; diff --git a/world/Segment.h b/world/Segment.h index 88aa9adff..26ee986d1 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -116,8 +116,12 @@ class TSegment }; setting m_setting; double fLength { -1.0 }; // długość policzona - std::vector fTsBuffer; // wartości parametru krzywej t dla równych odcinków s - std::vector fTsSlope; // nachylenie dt/du (= dt/ds * fStep) w tych samych punktach + // the curve at equal intervals of s, for FastGetTFromS(): the two it reads of a point side by side, in one cache line + struct ts_point { + double t; // wartość parametru krzywej t dla równych odcinków s + double slope; // nachylenie dt/du (= dt/ds * fStep) w tym punkcie + }; + std::vector fTs; double fStep = 0.0; int iSegCount = 0; // ilość odcinków do rysowania krzywej double fDirection = 0.0; // Ra: kąt prostego w planie; dla łuku kąt od Point1 @@ -275,7 +279,7 @@ public: inline int RaSegCount() const { - return fTsBuffer.empty() ? 1 : iSegCount; }; + return fTs.empty() ? 1 : iSegCount; }; void render_lines(std::vector &out, float quality = 1.0f) const;