From c85aab4f3f1ef321a71f111a8f6c9521fae1d267 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Wed, 11 Nov 2026 01:43:46 +0100 Subject: [PATCH] feat(physics): physical coupler model with slack, hysteresis and breaking --- CMakeLists.txt | 1 + McZapkie/MOVER.h | 14 + McZapkie/Mover.cpp | 306 +++++++++++++++--- McZapkie/couplerphysics.cpp | 285 +++++++++++++++++ McZapkie/couplerphysics.h | 133 ++++++++ tests/unit/test_coupler_physics.cpp | 460 ++++++++++++++++++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 3 + 8 files changed, 1168 insertions(+), 41 deletions(-) create mode 100644 McZapkie/couplerphysics.cpp create mode 100644 McZapkie/couplerphysics.h create mode 100644 tests/unit/test_coupler_physics.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index fc98ead00..243ac8b79 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -471,6 +471,7 @@ set(CORE_SOURCES "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" +"McZapkie/couplerphysics.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 9502de95a..4158825c2 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "hamulce.h" +#include "couplerphysics.h" #include "scripting/ladderlogic.h" class cParser; @@ -1264,6 +1265,11 @@ struct TCoupling power_coupling power_110v; power_coupling power_24v; + // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, + // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end + coupler_physics::end_parameters physics; + coupler_physics::pair_state physics_state; + int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ std::string control_type; // abstraction of control coupling interface and communication standard @@ -2529,6 +2535,14 @@ class TMoverParameters double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); + // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h + double coupler_force_physical(int const End, double const dt); + // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and + // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers + bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd); + // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit + // is too fast for them to catch + void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd); void CollisionDetect(int const End, double const dt); // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio static constexpr double SafeCollisionVelocity{15.0}; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1ad97530e..4ed1f0048 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -643,6 +643,9 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie if (thiscoupler.CouplingFlag == coupling::faux) { + // a new coupling: the play of the coupling as set up anew, without the stretch of the one before + thiscoupler.physics_state.couple(); + othercoupler.physics_state.couple(); // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg thiscoupler.Render = true; // tego rysować othercoupler.Render = false; // a tego nie @@ -1334,6 +1337,11 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const otherend{Neighbours[End].vehicle_end}; auto const &othercoupler{othervehicle->Couplers[otherend]}; + if (Global.coupler_physics && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each // other (touch with the same ends), as in CouplerForce() auto const otherdirection{DirPatch(End, otherend)}; @@ -1363,7 +1371,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) if (Global.crash_damage) { - if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) + // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) + if (false == Global.coupler_physics && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) { // small chance to smash the coupler if it's hit with excessive force damage_coupler(End); @@ -1392,18 +1401,21 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - // adjust velocity and acceleration of affected vehicles + // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the + // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the + // velocity once more, and the vehicles would bounce off the stop faster than they hit it + auto const accelerationspike{Global.coupler_physics ? 0.0 : 1.0}; if (false == TestFlag(DamageFlag, dtrain_out)) { auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange; + AccS += accelerationchange * accelerationspike; V = velocity; } if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange; + othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; othervehicle->V = othervehiclenewvelocity; } } @@ -1421,7 +1433,8 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) + auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; @@ -1431,23 +1444,13 @@ void TMoverParameters::damage_coupler(int const End) if (thiscoupler.Connected != nullptr) { - switch (End) + // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too + // for vehicles facing each other + thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].CouplingFlag = coupling::faux; + if (hosetorn && Global.coupler_physics) { - // break connection with other vehicle, if there's any - case 0: - { - thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; - break; - } - case 1: - { - thiscoupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux; - break; - } - default: - { - break; - } + // the brake pipe of the other part of the train vents through the torn hose as well + thiscoupler.Connected->AlarmChainFlag = true; } } @@ -5470,6 +5473,10 @@ double TMoverParameters::Adhesive(double staticfriction) const // ************************************************************************************************* double TMoverParameters::CouplerForce(int const End, double dt) { + if (Global.coupler_physics) + { + return coupler_force_physical(End, dt); + } auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; @@ -5583,27 +5590,9 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux && - thiscoupler.AutomaticCouplingAllowed && - othercoupler.AutomaticCouplingAllowed) + if (-newdistance >= std::min(collisiondistance, dEpsilon)) { - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (thiscoupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype); - - // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) - auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)}; - auto const caught{safe && Attach(End, otherend, othervehicle, couplingtype)}; - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - AIFlag |= (caught ? sound::attachcoupler : 0); - // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down - thiscoupler.AutomaticCouplingAllowed = safe && false == caught; - othercoupler.AutomaticCouplingAllowed = safe && false == caught; + automatic_coupling(End, *othervehicle, otherend); } } } @@ -5618,6 +5607,157 @@ double TMoverParameters::CouplerForce(int const End, double dt) return CF; } +void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || + false == othercoupler.AutomaticCouplingAllowed) + { + return; + } + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) + { + couplingtype &= ~coupling::control; + } + couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); + + // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) + auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; + auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + AIFlag |= (caught ? sound::attachcoupler : 0); + // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down + thiscoupler.AutomaticCouplingAllowed = safe && false == caught; + othercoupler.AutomaticCouplingAllowed = safe && false == caught; +} + +namespace +{ + +// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train +constexpr double coupler_stretch_threshold{0.001}; + +// the sounds of the buffers hitting each other, and of the coupling taking up its play +struct coupler_sound_input +{ + double gap{0.0}; // between the ends [m] + double previous_gap{0.0}; + double gap_rate{0.0}; // [m/s] + double draw_gear{0.0}; // deflection [m] + double previous_draw_gear{0.0}; + bool coupled{false}; + bool adapter{false}; + bool moving{false}; +}; + +int coupler_sounds(coupler_sound_input const &Input) +{ + if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) + { + // 090503: dzwieki pracy zderzakow + return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; + } + if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) + { + // 090503: dzwieki pracy sprzegu + return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; + } + return sound::none; +} + +} // namespace + +double TMoverParameters::coupler_force_physical(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + auto &state{thiscoupler.physics_state}; + + // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since + auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; + auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind + auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; + + if (false == coupled && Neighbours[End].distance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + auto const previousgap{state.gap}; + auto const previousdrawgear{state.draw_gear.deflection}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; + + SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); + + thiscoupler.CheckCollision = state.stop != 0; + // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end + thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); + // the link pulled past its yield force, which the AI drivers ease off on + thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; + + if (result.broken) + { + damage_coupler(End); + } + if (false == coupled && gap < 0.0) + { + auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; + if (-gap >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + + // tension pulls this vehicle towards the other one + auto const force{result.force * -DirF(End)}; + if (thiscoupler.CouplingFlag != coupling::faux) + { + // uzgadnianie prawa Newtona, as in CouplerForce() + othercoupler.CForce = -force * DirPatch(End, otherend); + } + return force; +} + +bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + auto &state{thiscoupler.physics_state}; + + // the draw gear went solid with the gap opening up, the buffers with it closing + auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; + auto const closing{state.stop > 0 ? gaprate : -gaprate}; + if (state.stop == 0 || closing <= 0.0) + { + // parting from the stop already, after the hit on the other vehicle's end + return false; + } + if (false == Global.crash_damage) + { + return true; + } + auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; + // the other vehicle keeps the state of the pair alike + othercoupler.physics_state.elongation = state.elongation; + if (hit.broken || hit.crushed) + { + damage_coupler(End); + } + // a broken coupling lets the vehicles part + return false == hit.broken; +} + // ************************************************************************************************* // Q: 20160714 // oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) @@ -10972,6 +11112,80 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); } +namespace +{ + +// the value of an optional key of the line, or the default without it +double optional_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{Default}; + extract_value(value, Key, Line, ""); + return value; +} + +// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it +double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{0.0}; + return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; +} + +// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of +// an automatic coupler have about a centimetre between them, a chain hangs loose +double default_slack(TCouplerType const Type) +{ + switch (Type) + { + case TCouplerType::Automatic: + return 0.005; + case TCouplerType::Chain: + return 0.05; + default: + return 0.0; + } +} + +// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from +// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: +// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in +// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 +// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one +// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks +// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it +coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) +{ + coupler_physics::end_parameters parameters; + parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; + parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; + // only a screw coupling can be tightened to press the buffers in, and not past their travel + auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; + parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); + // the legacy model sprang back at beta of the force it was loaded with + auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; + parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); + parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); + // as much as the legacy model had + parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); + + // FmaxC is the rated breaking force of the coupling + auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; + auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; + auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; + parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; + // the steel parts give a few millimetres under the rated force + parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); + parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); + return parameters; +} + +void scale_strength(coupler_physics::link_strength &Link, double const Factor) +{ + Link.yield *= Factor; + Link.ultimate *= Factor; +} + +} // namespace + void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) { @@ -11050,11 +11264,21 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (Index == 0) { // 0 indicates single entry for both couplers Couplers[1] = Couplers[0]; } + // each coupling as made is a little stronger than its rated force, a different one at each end + for (int end = end::front; end <= end::rear; ++end) + { + if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) + { + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); + } + } } void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp new file mode 100644 index 000000000..ab253e7c0 --- /dev/null +++ b/McZapkie/couplerphysics.cpp @@ -0,0 +1,285 @@ +/* +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 "couplerphysics.h" + +#include +#include +#include +#include + +namespace coupler_physics { + +namespace { + +// the transition between the loading and the unloading curve of a device, to the secant stiffness of the pair: the +// friction holds the device stiffer than its springs until the force changes enough to slip it +constexpr double transition_factor{3.0}; +// the force, the deflection and the energy of a curve are computed within this many iterations of the inverse +constexpr int inverse_iterations{50}; +constexpr int series_iterations{60}; + +// a device which doesn't give at all, standing in for the buffers of an end with an adapter +constexpr spring_curve rigid{1.0, 0.0, 0.0}; + +double series_stiffness(double First, double Second) { + return First * Second / (First + Second); +} + +// the buffers of the pair: those of both ends in series, or with an adapter on either end, the device with the shorter +// travel alone, the one of the automatic coupler which takes the push +struct pressed_devices { + spring_curve first; + spring_curve second; + double unloading{0.5}; + double damping{0.0}; +}; + +bool shorter(spring_curve const &First, spring_curve const &Second) { + return std::tie(First.travel, First.stiffness, First.progression) <= std::tie(Second.travel, Second.stiffness, Second.progression); +} + +pressed_devices buffers_of(end_parameters const &First, end_parameters const &Second, bool const Adapter) { + auto const unloading{0.5 * (First.buffers_unloading + Second.buffers_unloading)}; + auto const damping{0.5 * (First.damping + Second.damping)}; + if (false == Adapter) { + return {First.buffers, Second.buffers, unloading, damping}; + } + auto const &coupler{shorter(First.buffers, Second.buffers) ? First.buffers : Second.buffers}; + return {coupler, rigid, unloading, damping}; +} + +pressed_devices draw_gears_of(end_parameters const &First, end_parameters const &Second) { + return {First.draw_gear, Second.draw_gear, 0.5 * (First.draw_gear_unloading + Second.draw_gear_unloading), 0.5 * (First.damping + Second.damping)}; +} + +struct pressed_force { + double force{0.0}; // with the friction and the damping [N] + double curve_force{0.0}; // of the loading curve [N] + double first_deflection{0.0}; // of the first device [m] + bool solid{false}; // both devices at the end of their travel +}; + +// the force of the devices pressed (or pulled) by the deflection growing at the rate +pressed_force press(pressed_devices const &Devices, hysteresis &State, double const Deflection, double const Rate) { + if (Deflection <= 0.0) { + State.reset(); + return {}; + } + auto const split{series(Devices.first, Devices.second, Deflection)}; + auto const travel{Devices.first.travel + Devices.second.travel}; + auto const top{std::max(Devices.first.end_force(), Devices.second.end_force())}; + auto const transition{transition_factor * top / std::max(travel, 1e-3)}; + auto const friction{State.update(Deflection, split.force, Devices.unloading * split.force, transition)}; + // a buffer pushes, a draw gear pulls, neither the other way round however fast they spring back + return {std::max(0.0, friction + Devices.damping * Rate), split.force, split.first, Deflection >= travel}; +} + +bool weaker(link_strength const &First, link_strength const &Second) { + return std::tie(First.ultimate, First.yield, First.hardening) <= std::tie(Second.ultimate, Second.yield, Second.hardening); +} + +} // namespace + +double spring_curve::force(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * ((1.0 - progression) * u + progression * u * u * u); +} + +double spring_curve::deflection(double const Force) const { + if (travel <= 0.0 || Force <= 0.0) { + return 0.0; + } + auto const f{Force / end_force()}; + if (f >= 1.0) { + return travel; + } + if (progression <= 0.0) { + return f * travel; + } + // the curve is rising and convex, so Newton's method from the end of the travel closes in from above + auto u{1.0}; + auto step{1.0}; + for (int iteration = 0; iteration < inverse_iterations && std::abs(step) > 1e-15; ++iteration) { + auto const value{progression * u * u * u + (1.0 - progression) * u - f}; + auto const slope{3.0 * progression * u * u + (1.0 - progression)}; + step = value / slope; + u -= step; + } + return std::clamp(u, 0.0, 1.0) * travel; +} + +double spring_curve::energy(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * travel * ((1.0 - progression) * u * u / 2.0 + progression * u * u * u * u / 4.0); +} + +series_split series(spring_curve const &First, spring_curve const &Second, double const Deflection) { + if (Deflection <= 0.0) { + return {}; + } + if (Second.travel <= 0.0) { + return {First.force(Deflection), std::min(Deflection, First.travel), 0.0}; + } + if (First.travel <= 0.0) { + return {Second.force(Deflection), 0.0, std::min(Deflection, Second.travel)}; + } + if (std::tie(First.stiffness, First.travel, First.progression) == std::tie(Second.stiffness, Second.travel, Second.progression)) { + auto const half{std::min(Deflection / 2.0, First.travel)}; + return {First.force(half), half, half}; + } + auto const top{std::max(First.end_force(), Second.end_force())}; + if (Deflection >= First.travel + Second.travel) { + return {top, First.travel, Second.travel}; + } + // the force at which the deflections of both add up to the given one. the sum doesn't depend on the order of + // the devices, so neither does the result + auto low{0.0}; + auto high{top}; + for (int iteration = 0; iteration < series_iterations; ++iteration) { + auto const middle{0.5 * (low + high)}; + if (First.deflection(middle) + Second.deflection(middle) < Deflection) { + low = middle; + } + else { + high = middle; + } + } + auto const force{0.5 * (low + high)}; + return {force, First.deflection(force), Second.deflection(force)}; +} + +double hysteresis::update(double const Deflection, double const Loading, double const Unloading, double const Transition) { + force = std::clamp(force + Transition * (Deflection - deflection), std::min(Unloading, Loading), Loading); + deflection = Deflection; + return force; +} + +void hysteresis::reset() { + force = 0.0; + deflection = 0.0; +} + +double plastic_elongation(link_strength const &Link, double const Force, double const Elongation) { + if (false == Link.breakable || Force <= Link.yield) { + return Elongation; + } + return std::max(Elongation, (Force - Link.yield) / Link.hardening); +} + +double impact_force(double const Velocity, double const Stiffness, double const Mass1, double const Mass2) { + if (Velocity <= 0.0 || Mass1 <= 0.0 || Mass2 <= 0.0) { + return 0.0; + } + auto const mass{Mass1 * Mass2 / (Mass1 + Mass2)}; + return Velocity * std::sqrt(Stiffness * mass); +} + +double strength_scatter(std::string_view const Name, int const End) { + // FNV-1a, which std::hash isn't on every compiler + std::uint64_t hash{14695981039346656037ULL}; + auto const mix = [&hash](unsigned char const Byte) { + hash ^= Byte; + hash *= 1099511628211ULL; + }; + for (auto const character : Name) { + mix(static_cast(character)); + } + mix(static_cast(End)); + // the 53 high bits, as a fraction + auto const fraction{static_cast(hash >> 11) / 9007199254740992.0}; + return 1.0 + 0.2 * fraction; +} + +link_strength weaker_link(end_parameters const &First, end_parameters const &Second) { + auto link{weaker(First.link, Second.link) ? First.link : Second.link}; + // an articulated joint holds whatever the end of the other section is set up to + link.breakable = First.link.breakable && Second.link.breakable; + return link; +} + +void pair_state::couple() { + draw_gear.reset(); + elongation = 0.0; +} + +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input) { + pair_result result; + State.stop = 0; + State.stop_force = 0.0; + + pressed_force pulled; + if (Input.coupled) { + auto const play{First.slack + Second.slack + State.elongation}; + pulled = press(draw_gears_of(First, Second), State.draw_gear, Input.gap - play, Input.gap_rate); + } + else { + State.draw_gear.reset(); + } + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + + result.tension = pulled.force; + result.compression = pushed.force; + result.buffers_deflection = Input.adapter ? 0.0 : pushed.first_deflection; + if (pulled.solid) { + State.stop = 1; + State.stop_force = pulled.curve_force; + } + else if (pushed.solid) { + State.stop = -1; + State.stop_force = pushed.curve_force; + } + + if (Input.coupled) { + auto const link{weaker_link(First, Second)}; + result.overloaded = result.tension > link.yield; + if (Input.damage && link.breakable && result.tension >= link.ultimate) { + result.broken = true; + result.tension = 0.0; + State.draw_gear.reset(); + State.stop = std::min(State.stop, 0); + } + else if (Input.damage) { + State.elongation = plastic_elongation(link, result.tension, State.elongation); + } + } + + result.force = result.tension - result.compression; + State.gap = Input.gap; + return result; +} + +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double const Velocity, double const Mass1, double const Mass2) { + impact_result result; + if (State.stop == 0 || Velocity <= 0.0) { + return result; + } + auto const stiffness{series_stiffness(First.link_stiffness, Second.link_stiffness)}; + result.force = State.stop_force + impact_force(Velocity, stiffness, Mass1, Mass2); + if (State.stop > 0) { + auto const link{weaker_link(First, Second)}; + result.broken = link.breakable && result.force >= link.ultimate; + if (false == result.broken) { + State.elongation = plastic_elongation(link, result.force, State.elongation); + } + } + else { + result.crushed = result.force >= std::min(First.crush_force, Second.crush_force); + } + return result; +} + +} // namespace coupler_physics diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h new file mode 100644 index 000000000..98eaf8b3c --- /dev/null +++ b/McZapkie/couplerphysics.h @@ -0,0 +1,133 @@ +#pragma once + +#include +#include + +// the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of +// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive +// springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack) +// in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its +// yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack +namespace coupler_physics { + +// force-deflection characteristic of the spring device of one vehicle end, its buffers or its draw gear: +// F(d) = F_end * ((1 - p) * u + p * u^3), u = d / travel, F_end = stiffness * travel +// p (the progression) 0 gives a linear spring; towards 1 it's soft at first and stiffens towards the end of the +// travel, as ring springs and elastomer pads do +struct spring_curve { + double stiffness{1.0}; // secant stiffness, up to the end of the travel [N/m] + double travel{0.1}; // [m] + double progression{0.0}; // 0 to 0.9 + + double end_force() const { return stiffness * travel; } + // force at the deflection [N], the deflection held within the travel + double force(double Deflection) const; + // deflection at the force [m]: the end of the travel at the end force and past it + double deflection(double Force) const; + // energy the device takes in along the curve up to the deflection [J] + double energy(double Deflection) const; +}; + +// the devices of both ends pressed against each other: they carry the same force, their deflections add up. past +// the end of the travel of one, the other one takes the rest. the result doesn't depend on the order of the two +struct series_split { + double force{0.0}; // [N] + double first{0.0}; // deflection of the first device [m] + double second{0.0}; // of the second one [m] +}; +series_split series(spring_curve const &First, spring_curve const &Second, double Deflection); + +// friction (Coulomb) hysteresis of a spring device: the force follows the loading curve while the deflection grows, +// drops to the unloading curve when it shrinks, and in between moves along a stiff transition line, as the friction +// of ring springs or of the wedges of a draw gear holds the device until the force changes enough +struct hysteresis { + double force{0.0}; // carried at the last update [N] + double deflection{0.0}; // at the last update [m] + + // the force at the new deflection, given the force of the loading and of the unloading curve there, and the + // stiffness of the transition between them [N/m] + double update(double Deflection, double Loading, double Unloading, double Transition); + void reset(); +}; + +// steel link of the coupling (the screw coupling and the hook, the knuckle of an automatic coupler): elastic up to +// the yield force, stretched for good past it (the hardening gives the force for each metre of it), broken at the +// ultimate force +struct link_strength { + double yield{std::numeric_limits::max()}; // [N] + double ultimate{std::numeric_limits::max()}; // [N] + double hardening{1.0}; // [N/m] + bool breakable{false}; // an articulated joint, or an end without a coupler set up, holds whatever +}; + +// the permanent elongation [m] the link has after carrying the force, given the one it had +double plastic_elongation(link_strength const &Link, double Force, double Elongation); +// peak force [N] of an elastic hit of two masses [kg] at the closing velocity [m/s] on a stop of the stiffness [N/m]: +// the kinetic energy of their relative motion all goes into the stop +double impact_force(double Velocity, double Stiffness, double Mass1, double Mass2); +// spread of the strength of the couplings as made: 1.0 to 1.2 of the rated force, fixed for the vehicle end, and the +// same on every compiler +double strength_scatter(std::string_view Name, int End); + +// what the model takes of one vehicle end +struct end_parameters { + spring_curve buffers; + spring_curve draw_gear; + double slack{0.0}; // play of the coupling in tension [m], negative for the buffers pressed in by a tightened screw coupling + double buffers_unloading{0.5}; // force of the unloading curve to that of the loading one + double draw_gear_unloading{0.5}; + double damping{0.0}; // viscous damping of the devices, while pressed [N s/m] + double link_stiffness{1.0}; // of the steel parts of the end, past the travel of the springs [N/m] + double crush_force{std::numeric_limits::max()}; // a hit on the buffers past their travel with this force crushes them [N] + link_strength link; +}; + +// the weaker of the links of the two ends, which gives first; the same whichever end asks +link_strength weaker_link(end_parameters const &First, end_parameters const &Second); + +// state of the coupling of two vehicle ends, which both vehicles keep alike: each updates its own copy with the same +// gap, so the copies stay the same +struct pair_state { + hysteresis draw_gear; + hysteresis buffers; + double elongation{0.0}; // permanent, of the link [m]; it adds to the slack until the vehicles are coupled again + double gap{0.0}; // at the last update [m] + int stop{0}; // at the last update: 1 the draw gear went solid, -1 the buffers did, 0 neither + double stop_force{0.0}; // the springs carried at the stop [N] + + // a new coupling of the ends: the link adjusted (a screw coupling tightened anew), the draw gear released + void couple(); +}; + +struct pair_input { + double gap{0.0}; // between the ends [m], negative with the buffers pressed in + double gap_rate{0.0}; // [m/s] + bool coupled{false}; + bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone + bool damage{false}; // the link can stretch and break (crash damage on) +}; + +struct pair_result { + double force{0.0}; // between the ends, tension positive [N] + double tension{0.0}; // carried by the link [N] + double compression{0.0}; // carried by the buffers [N] + double buffers_deflection{0.0}; // of the buffers of the first end [m] + bool overloaded{false}; // the link was pulled past its yield force + bool broken{false}; // the link broke, it carries nothing now +}; + +// the force between the first end and the second one at the gap, updating the state of the pair +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input); + +// what a hit on the stop does to the ends +struct impact_result { + double force{0.0}; // peak force of the hit [N] + bool broken{false}; // the link broke under it + bool crushed{false}; // the buffers or the coupler of an end were crushed by it +}; + +// the hit on the stop the pair went solid against at the last update (State.stop), at the closing velocity [m/s], of +// the vehicles of the masses [kg]: stretches or breaks the link of a coupled pair, may crush the buffers +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double Velocity, double Mass1, double Mass2); + +} // namespace coupler_physics diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp new file mode 100644 index 000000000..d8d1003b9 --- /dev/null +++ b/tests/unit/test_coupler_physics.cpp @@ -0,0 +1,460 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "McZapkie/couplerphysics.h" +#include "utilities/Globals.h" + +#include +#include + +// the physical model of the couplings (McZapkie/couplerphysics.h, couplerphysics in eu07.ini): progressive buffers and +// draw gear with friction hysteresis, pressed in series, the play of the coupling, its yield and its breaking + +using test::definition; +using test::vehicle; +namespace cp = coupler_physics; + +namespace { + +// the given setting of a global flag for the test, restored after it +class flag_setting { +public: + flag_setting(bool &Flag, bool Enabled) : m_flag{Flag}, m_previous{Flag} { m_flag = Enabled; } + ~flag_setting() { m_flag = m_previous; } + flag_setting(flag_setting const &) = delete; + flag_setting &operator=(flag_setting const &) = delete; + +private: + bool &m_flag; + bool m_previous; +}; + +// one end of the wagon of data/wagon.json as the model takes it, with the play of a loose screw coupling +cp::end_parameters wagon_end() { + cp::end_parameters wagon; + wagon.buffers = {9.2e6, 0.11, 0.5}; + wagon.draw_gear = {4.5e6, 0.1, 0.3}; + wagon.slack = 0.05; + wagon.buffers_unloading = 0.58; + wagon.draw_gear_unloading = 0.58; + wagon.link_stiffness = 850e3 / 0.003; + wagon.crush_force = 2125e3; + wagon.link = {680e3, 850e3, 170e3 / 0.02, true}; + return wagon; +} + +// the force between two such ends at the gap, the state of the pair fresh +cp::pair_result fresh_pair(double Gap, bool Coupled = true, cp::end_parameters const &End = wagon_end()) { + cp::pair_state state; + return cp::update_pair(End, End, state, {Gap, 0.0, Coupled, false, true}); +} + +} // namespace + +TEST_CASE("coupler physics: a progressive spring is soft at first and reaches its end force at the end of its travel") { + cp::spring_curve const buffers{9.2e6, 0.11, 0.5}; + CHECK(buffers.force(0.0) == 0.0); + CHECK(buffers.force(0.11) == doctest::Approx(buffers.end_force())); + CHECK(buffers.end_force() == doctest::Approx(1012e3)); + // held at the end of the travel + CHECK(buffers.force(0.2) == doctest::Approx(buffers.end_force())); + CHECK(buffers.force(0.055) < 0.5 * buffers.end_force()); + CHECK(buffers.energy(0.11) == doctest::Approx(1012e3 * 0.11 * (0.5 - 0.5 / 4.0))); + for (auto const deflection : {0.001, 0.01, 0.05, 0.1}) { + CAPTURE(deflection); + CHECK(buffers.deflection(buffers.force(deflection)) == doctest::Approx(deflection)); + } + CHECK(buffers.deflection(2.0 * buffers.end_force()) == doctest::Approx(0.11)); + + cp::spring_curve const linear{9.2e6, 0.11, 0.0}; + CHECK(linear.force(0.05) == doctest::Approx(9.2e6 * 0.05)); + CHECK(linear.deflection(9.2e6 * 0.05) == doctest::Approx(0.05)); +} + +TEST_CASE("coupler physics: the devices of both ends carry the same force, their deflections add up") { + SUBCASE("alike, they share the deflection") { + cp::spring_curve const draw{4.5e6, 0.1, 0.3}; + auto const split{cp::series(draw, draw, 0.1)}; + CHECK(split.first == doctest::Approx(0.05)); + CHECK(split.second == doctest::Approx(0.05)); + CHECK(split.force == doctest::Approx(draw.force(0.05))); + } + SUBCASE("the softer one gives more") { + cp::spring_curve const soft{4.5e6, 0.1, 0.3}; + cp::spring_curve const stiff{9e6, 0.1, 0.3}; + auto const split{cp::series(soft, stiff, 0.12)}; + CHECK(split.first + split.second == doctest::Approx(0.12)); + CHECK(split.first > split.second); + CHECK(soft.force(split.first) == doctest::Approx(split.force)); + CHECK(stiff.force(split.second) == doctest::Approx(split.force)); + // the same force whichever end asks, as both vehicles of the pair do + CHECK(cp::series(stiff, soft, 0.12).force == split.force); + } + SUBCASE("past the travel of one, the other takes the rest") { + cp::spring_curve const short_travel{1e6, 0.02, 0.0}; + cp::spring_curve const long_travel{1e6, 0.2, 0.0}; + auto const split{cp::series(short_travel, long_travel, 0.1)}; + CHECK(split.first == doctest::Approx(0.02)); + CHECK(split.second == doctest::Approx(0.08)); + CHECK(split.force == doctest::Approx(80e3)); + // both solid + CHECK(cp::series(short_travel, long_travel, 0.3).force == doctest::Approx(200e3)); + } +} + +TEST_CASE("coupler physics: the friction of a spring device takes energy on each stroke") { + cp::spring_curve const draw{4.5e6, 0.1, 0.3}; + auto const unloading{0.5}; + auto const transition{3.0 * draw.end_force() / draw.travel}; + cp::hysteresis device; + auto work{0.0}; + auto deflection{0.0}; + auto const move_to = [&device, &work, &deflection, &draw, unloading, transition](double Target) { + while (std::abs(Target - deflection) > 1e-9) { + auto const next{deflection + std::clamp(Target - deflection, -1e-4, 1e-4)}; + auto const before{device.force}; + auto const after{device.update(next, draw.force(next), unloading * draw.force(next), transition)}; + work += 0.5 * (before + after) * (next - deflection); + deflection = next; + } + }; + + move_to(0.08); + // loading, along the loading curve + CHECK(device.force == doctest::Approx(draw.force(0.08))); + move_to(0.06); + // unloading, on the unloading one + CHECK(device.force == doctest::Approx(unloading * draw.force(0.06))); + // loaded again, the friction holds the device stiff until it slips onto the loading curve + auto const held{device.force}; + device.update(0.0601, draw.force(0.0601), unloading * draw.force(0.0601), transition); + CHECK(device.force == doctest::Approx(held + transition * 0.0001)); + device.update(0.06, draw.force(0.06), unloading * draw.force(0.06), transition); + move_to(0.0); + CHECK(device.force == doctest::Approx(0.0)); + // the stroke took part of the energy of the loading curve, less than the unloading curve alone would have: the + // device springs back stiffly at first, along the transition + CHECK(work > 0.3 * draw.energy(0.08)); + CHECK(work < (1.0 - unloading) * draw.energy(0.08)); +} + +TEST_CASE("coupler physics: the link stretches for good past its yield force and breaks at its ultimate one") { + cp::link_strength const link{600e3, 850e3, 250e3 / 0.02, true}; + CHECK(cp::plastic_elongation(link, 500e3, 0.0) == 0.0); + CHECK(cp::plastic_elongation(link, 700e3, 0.0) == doctest::Approx(0.008)); + // it doesn't get shorter again + CHECK(cp::plastic_elongation(link, 650e3, 0.008) == doctest::Approx(0.008)); + // an articulated joint holds whatever + auto joint{link}; + joint.breakable = false; + CHECK(cp::plastic_elongation(joint, 700e3, 0.0) == 0.0); + + // all the kinetic energy of the relative motion into the stop + CHECK(cp::impact_force(1.0, 1e8, 2e4, 2e4) == doctest::Approx(1e6)); + CHECK(cp::impact_force(-1.0, 1e8, 2e4, 2e4) == 0.0); + + for (int index = 0; index < 2; ++index) { + auto const scatter{cp::strength_scatter("wagon", index)}; + CHECK(scatter >= 1.0); + CHECK(scatter <= 1.2); + CHECK(cp::strength_scatter("wagon", index) == scatter); + } + CHECK(cp::strength_scatter("wagon", 0) != cp::strength_scatter("wagon", 1)); +} + +TEST_CASE("coupler physics: the coupling pulls only past its play, the buffers push") { + auto const wagon{wagon_end()}; + // the play of both ends: 0.1 m + CHECK(fresh_pair(0.05).force == 0.0); + CHECK(fresh_pair(0.099).force == 0.0); + + auto const pulled{fresh_pair(0.15)}; + CHECK(pulled.force > 0.0); + CHECK(pulled.tension == doctest::Approx(cp::series(wagon.draw_gear, wagon.draw_gear, 0.05).force)); + // uncoupled vehicles don't pull each other + CHECK(fresh_pair(0.15, false).force == 0.0); + + auto const pushed{fresh_pair(-0.05)}; + CHECK(pushed.force == doctest::Approx(-cp::series(wagon.buffers, wagon.buffers, 0.05).force)); + CHECK(pushed.buffers_deflection == doctest::Approx(0.025)); + CHECK(fresh_pair(-0.05, false).force == pushed.force); + + SUBCASE("a tightened screw coupling presses the buffers in, both carry force at rest") { + auto tight{wagon_end()}; + tight.slack = -0.02; + auto const atrest{fresh_pair(-0.02, true, tight)}; + CHECK(atrest.tension > 0.0); + CHECK(atrest.compression > 0.0); + } +} + +TEST_CASE("coupler physics: the springs of a pair go solid at the end of their travel") { + cp::pair_state state; + auto const wagon{wagon_end()}; + cp::update_pair(wagon, wagon, state, {0.1 + 0.2, 0.0, true, false, true}); + CHECK(state.stop == 1); + CHECK(state.stop_force == doctest::Approx(450e3)); + cp::update_pair(wagon, wagon, state, {-0.25, 0.0, true, false, true}); + CHECK(state.stop == -1); + CHECK(state.stop_force == doctest::Approx(1012e3)); + cp::update_pair(wagon, wagon, state, {0.0, 0.0, true, false, true}); + CHECK(state.stop == 0); +} + +TEST_CASE("coupler physics: a pull past the ultimate force breaks the coupling, past the yield force stretches it") { + auto weak{wagon_end()}; + weak.link = {300e3, 400e3, 100e3 / 0.02, true}; + + SUBCASE("broken, with crash damage") { + cp::pair_state state; + auto const result{cp::update_pair(weak, weak, state, {0.1 + 0.19, 0.0, true, false, true})}; + CHECK(result.broken); + CHECK(result.tension == 0.0); + CHECK(result.force == 0.0); + } + SUBCASE("held, without it") { + cp::pair_state state; + auto const result{cp::update_pair(weak, weak, state, {0.1 + 0.19, 0.0, true, false, false})}; + CHECK_FALSE(result.broken); + CHECK(result.tension > 400e3); + CHECK(state.elongation == 0.0); + } + SUBCASE("stretched for good, which eases the pull") { + auto stronger{weak}; + stronger.link.ultimate = 1000e3; + cp::pair_state state; + auto const first{cp::update_pair(stronger, stronger, state, {0.1 + 0.19, 0.0, true, false, true})}; + CHECK(first.overloaded); + CHECK(state.elongation == doctest::Approx((first.tension - 300e3) / stronger.link.hardening)); + auto const second{cp::update_pair(stronger, stronger, state, {0.1 + 0.19, 0.0, true, false, true})}; + CHECK(second.tension < first.tension); + } +} + +TEST_CASE("coupler physics: a jerk on the solid draw gear breaks the coupling by the force of the hit") { + auto const wagon{wagon_end()}; + constexpr double mass{42200.0}; + auto const stopped = [&wagon](cp::pair_state &State) { cp::update_pair(wagon, wagon, State, {0.1 + 0.21, 0.0, true, false, true}); }; + + cp::pair_state state; + stopped(state); + auto const hard{cp::impact(wagon, wagon, state, 1.0, mass, mass)}; + // 450 kN of the springs and about 1.7 MN of the hit + CHECK(hard.force == doctest::Approx(450e3 + std::sqrt(850e3 / 0.003 / 2.0 * mass / 2.0))); + CHECK(hard.broken); + + cp::pair_state gentle; + stopped(gentle); + CHECK_FALSE(cp::impact(wagon, wagon, gentle, 0.1, mass, mass).broken); + CHECK(gentle.elongation == 0.0); + + cp::pair_state harder; + stopped(harder); + auto const yielding{cp::impact(wagon, wagon, harder, 0.15, mass, mass)}; + CHECK_FALSE(yielding.broken); + CHECK(yielding.force > 680e3); + CHECK(harder.elongation > 0.0); + + // the buffers crushed by a hit past their travel + cp::pair_state pressed; + cp::update_pair(wagon, wagon, pressed, {-0.25, 0.0, false, false, true}); + CHECK_FALSE(cp::impact(wagon, wagon, pressed, 0.1, mass, mass).crushed); + CHECK(cp::impact(wagon, wagon, pressed, 1.0, mass, mass).crushed); +} + +// the model in the simulation, two vehicles on a track + +namespace { + +// couples the facing ends of the two vehicles, as the scenery does +void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, int Coupling = coupling::coupler) { + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling, true, false)); +} + +// the wagon of data/wagon.json with the given play of its screw couplings +vehicle loose_wagon(double Slack, double Velocity, std::string const &Name) { + return vehicle{definition::load("wagon").set("BuffCoupl", "Slack", Slack), Velocity, Name}; +} + +bool coupler_damaged(vehicle &Vehicle) { + return TestFlag(Vehicle->DamageFlag, dtrain_coupling); +} + +} // namespace + +TEST_CASE("coupler physics: the play of the coupling and the parameters of the model come from the vehicle definition") { + auto loose{loose_wagon(0.05, 0.0, "loose")}; + auto const &physics{loose->Couplers[end::front].physics}; + CHECK(physics.slack == doctest::Approx(0.05)); + CHECK(loose->Couplers[end::rear].physics.slack == doctest::Approx(0.05)); + CHECK(physics.buffers.stiffness == doctest::Approx(9200e3)); + CHECK(physics.buffers.travel == doctest::Approx(0.11)); + CHECK(physics.draw_gear.end_force() == doctest::Approx(450e3)); + CHECK(physics.buffers_unloading == doctest::Approx(0.58)); + // the rated breaking force, and a little more for the coupling as made + CHECK(physics.link.ultimate >= 850e3); + CHECK(physics.link.ultimate <= 1020e3); + CHECK(physics.link.yield == doctest::Approx(0.8 * physics.link.ultimate)); + CHECK(physics.link.breakable); + + auto tight{vehicle{definition::load("wagon"), 0.0, "tight"}}; + CHECK(tight->Couplers[end::front].physics.slack == 0.0); + auto automatic{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Automatic"), 0.0, "automatic"}}; + CHECK(automatic->Couplers[end::front].physics.slack == doctest::Approx(0.005)); + auto articulated{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Articulated"), 0.0, "articulated"}}; + CHECK_FALSE(articulated->Couplers[end::front].physics.link.breakable); +} + +TEST_CASE("coupler physics: a coupling with play pulls only once the play is taken up") { + flag_setting const physics{Global.coupler_physics, true}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto front{loose_wagon(0.05, 3.0, "front")}; + auto rear{loose_wagon(0.05, 0.1, "rear")}; + join(rear, end::front, front, end::rear); + test::pair pair{rear, end::front, front, end::rear, 0.0}; + front.hold_brake_pipe(5.0); + rear.hold_brake_pipe(5.0); + + auto pulledwithinplay{false}; + for (int i = 0; i < 300 && pair.gap() < 0.09; ++i) { + pair.step(); + pulledwithinplay = pulledwithinplay || rear->Couplers[end::front].CForce != 0.0; + } + REQUIRE(pair.gap() >= 0.09); + CHECK_FALSE(pulledwithinplay); + CHECK(rear.speed() == doctest::Approx(0.1).epsilon(0.5)); + + pair.run(3.0); + CHECK(pair.coupled()); + CHECK_FALSE(coupler_damaged(rear)); + CHECK_FALSE(coupler_damaged(front)); + // the front wagon took the rear one along + CHECK(rear.speed() > 1.0); + CHECK(front.speed() < 2.5); +} + +TEST_CASE("coupler physics: buffers hit at a walking pace give back less than they took") { + flag_setting const physics{Global.coupler_physics, true}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto moving{vehicle{definition::load("wagon"), 5.0, "moving"}}; + // barely moving, so that its brakes are released + auto standing{vehicle{definition::load("wagon"), 0.1, "standing"}}; + test::pair pair{moving, end::front, standing, end::rear, 0.3}; + moving.hold_brake_pipe(5.0); + standing.hold_brake_pipe(5.0); + + auto touched{false}; + auto solid{false}; + for (int i = 0; i < 500; ++i) { + pair.step(); + touched = touched || pair.gap() < 0.0; + solid = solid || moving->Couplers[end::front].physics_state.stop != 0; + if (touched && pair.gap() > 0.3) { + break; // parted + } + } + CAPTURE(moving.speed()); + CAPTURE(standing.speed()); + REQUIRE(touched); + REQUIRE(pair.gap() > 0.3); + // the buffers took the hit within their travel, nothing collided + CHECK_FALSE(solid); + CHECK_FALSE(pair.coupled()); + // the momentum stays, rolling resistance aside + CHECK(moving.speed() + standing.speed() == doctest::Approx(5.1).epsilon(0.05)); + // the vehicles part slower than they met: the friction of the buffers took part of the energy + auto const restitution{(standing.speed() - moving.speed()) / (5.0 - 0.1)}; + CHECK(restitution > 0.3); + CHECK(restitution < 0.95); +} + +TEST_CASE("coupler physics: coupled vehicles at rest stay at rest") { + flag_setting const physics{Global.coupler_physics, true}; + auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; + auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; + join(first, end::rear, second, end::front); + test::pair pair{first, end::rear, second, end::front, 0.0}; + + pair.run(5.0); + CHECK(std::abs(first.speed()) < 0.01); + CHECK(std::abs(second.speed()) < 0.01); + CHECK(std::abs(pair.gap()) < 0.001); +} + +TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake hoses torn off") { + flag_setting const physics{Global.coupler_physics, true}; + auto front{loose_wagon(0.05, 20.0, "front")}; + auto rear{loose_wagon(0.05, 0.1, "rear")}; + join(rear, end::front, front, end::rear, coupling::coupler | coupling::brakehose); + test::pair pair{rear, end::front, front, end::rear, 0.0}; + front.hold_brake_pipe(5.0); + rear.hold_brake_pipe(5.0); + + SUBCASE("with crash damage, it breaks") { + flag_setting const crashdamage{Global.crash_damage, true}; + pair.run(1.0); + CHECK_FALSE(pair.coupled()); + CHECK((coupler_damaged(rear) || coupler_damaged(front))); + // both parts of the train brake, their pipe vented through the torn hoses + CHECK(rear->AlarmChainFlag); + CHECK(front->AlarmChainFlag); + // the front wagon runs away from the rear one + CHECK(front.speed() > rear.speed() + 5.0); + CHECK(pair.gap() > 0.3); + } + SUBCASE("without it, the coupling holds and the wagons run on together") { + flag_setting const crashdamage{Global.crash_damage, false}; + pair.run(3.0); + CHECK(pair.coupled()); + CHECK_FALSE(coupler_damaged(rear)); + CHECK_FALSE(coupler_damaged(front)); + CHECK(front.speed() == doctest::Approx(rear.speed()).epsilon(0.2)); + } +} + +TEST_CASE("coupler physics: a gentle pull on a coupling with play doesn't hurt it") { + flag_setting const physics{Global.coupler_physics, true}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto front{loose_wagon(0.05, 3.0, "front")}; + auto rear{loose_wagon(0.05, 0.1, "rear")}; + join(rear, end::front, front, end::rear); + test::pair pair{rear, end::front, front, end::rear, 0.0}; + front.hold_brake_pipe(5.0); + rear.hold_brake_pipe(5.0); + + pair.run(3.0); + CHECK(pair.coupled()); + CHECK_FALSE(coupler_damaged(rear)); + CHECK(rear->Couplers[end::front].physics_state.elongation == 0.0); +} + +TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into a standing one") { + flag_setting const physics{Global.coupler_physics, true}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + auto moving{vehicle{automatic, 5.0, "moving"}}; + auto standing{vehicle{automatic, 0.0, "standing"}}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + + pair.run(3.0); + REQUIRE(pair.coupled()); + pair.run(2.0); + CHECK(moving.speed() == doctest::Approx(standing.speed()).epsilon(0.1)); + CHECK_FALSE(TestFlag(moving->DamageFlag, dtrain_out)); +} + +TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples the ends coupled") { + // it used to uncouple the far end of the other vehicle, presuming the vehicles faced the same way + auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; + auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; + auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; + join(first, end::front, second, end::front); + join(second, end::rear, third, end::front); + + first->damage_coupler(end::front); + CHECK(first->Couplers[end::front].CouplingFlag == coupling::faux); + CHECK(second->Couplers[end::front].CouplingFlag == coupling::faux); + // the other coupling of the second vehicle stays + CHECK(second->Couplers[end::rear].CouplingFlag == coupling::coupler); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 7e2188038..828737ed0 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -819,6 +819,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "couplerphysics") + { + ParseOne(Parser, coupler_physics, 1); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1707,6 +1713,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.weather.temperature", AirTemperature ); export_as_text( Output, "ai.trainman", AITrainman ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); + export_as_text( Output, "couplerphysics", coupler_physics ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); export_as_text( Output, "shadows", RenderShadows ); diff --git a/utilities/Globals.h b/utilities/Globals.h index b006fe9cb..783a0c769 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -275,6 +275,9 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, + // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it + bool coupler_physics = false; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true;